Skip to content

Instantly share code, notes, and snippets.

@hit0ri
Created October 28, 2023 16:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hit0ri/20b4f8f8a951e4555d75f3ecacc63244 to your computer and use it in GitHub Desktop.
Save hit0ri/20b4f8f8a951e4555d75f3ecacc63244 to your computer and use it in GitHub Desktop.
WireGuard server setup (user-data)
DEBIAN_FRONTEND=noninteractive apt-get update -qq
DEBIAN_FRONTEND=noninteractive apt-get upgrade -y -qq
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq wireguard
curl -fsSL https://get.docker.com | sh
gpasswd -a ubuntu docker
sed -i 's|//Unattended-Upgrade::Remove-Unused-Dependencies.*$|Unattended-Upgrade::Remove-Unused-Dependencies "true";|' /etc/apt/apt.conf.d/50unattended-upgrades
sed -i 's|\("^linux-image.*\)|//\1|' /etc/apt/apt.conf.d/01autoremove

cat > /etc/systemd/system/wg-gen-web.path <<-EOF
[Unit]
Description=Watch /etc/wireguard for changes

[Path]
PathModified=/etc/wireguard

[Install]
WantedBy=multi-user.target
EOF

cat > /etc/systemd/system/wg-gen-web.service <<-EOF
[Unit]
Description=Reload WireGuard
After=network.target

[Service]
Type=oneshot
ExecStart=/usr/bin/systemctl reload wg-quick@wg0.service

[Install]
WantedBy=multi-user.target
EOF

systemctl enable /etc/systemd/system/wg-gen-web.{path,service}

cat > /etc/wireguard/wg0.conf <<EOF
[Interface]
Address = 10.200.200.1/24
MTU = 1420
ListenPort = 51820

PrivateKey = $(wg genkey)

PostUp = iptables -A FORWARD -i %i -j ACCEPT; iptables -A FORWARD -o %i -j ACCEPT; iptables -t nat -A POSTROUTING -o ens5 -j MASQUERADE
PostDown = iptables -D FORWARD -i %i -j ACCEPT; iptables -D FORWARD -o %i -j ACCEPT; iptables -t nat -D POSTROUTING -o ens5 -j MASQUERADE
EOF

chmod 0600 /etc/wireguard/*

systemctl enable wg-quick@wg0
systemctl reboot

mkdir wg-gen-web
cd $_
_WG_STATS_API_TOKEN=$(openssl rand -base64 24)
export _WG_STATS_API_TOKEN
cat > docker-compose.yaml <<-EOF
services:

  web:
    image: vx3r/wg-gen-web:latest
    restart: unless-stopped
    ports:
    - 127.0.0.1:8080:8080
    environment:
      WG_CONF_DIR: /data
      WG_INTERFACE_NAME: wg0.conf
      WG_STATS_API: http://172.17.0.1:8081
      WG_STATS_API_TOKEN: $_WG_STATS_API_TOKEN
    volumes:
    - /etc/wireguard:/data

  api:
    image: james/wg-api:latest
    restart: unless-stopped
    command: wg-api --device wg0 --listen 172.17.0.1:8081
    network_mode: host
    cap_add:
    - NET_ADMIN
    environment:
      WGAPI_TOKENS: $_WG_STATS_API_TOKEN
EOF
unset _WG_STATS_API_TOKEN
docker compose up -d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment