最近駭客事件頻傳,因為各個服務的升級速度實在是拼不上漏洞被發現的速度了。
所以我決定把關鍵設施全部移動到家中的內網,再進行連線。
我的需求:
- 可以繼續用子域名的方式登入、使用
- 不需要額外開多的 port
- 使用 VPN 時只讓特定服務走 VPN,其他網站不走 VPN,不需要一直切換
技術選擇:
- Nginx 在最前面:雖然 GitLab 可以直接對外,但是我前面還是先擋一層 Nginx,雖然前陣子有 Nginx 漏洞,但是至少出事的時候我可以確定先單獨補它就是了。
- WireGuard 作為 VPN:支援產生多組 key,我可以讓協作者也能用 GitLab,當合作結束的時候我除了關掉 GitLab 帳號之外也可以 revoke WireGuard 帳戶來禁止連線。
架構:
|
1 2 3 4 |
公網 ── 路由器 ───── UDP 51820 → wg0 10.66.66.1(在 nginx 容器的 network namespace 裡) ├─ :53 CoreDNS:gitlab → 10.66.66.1 ├─ :443 gitlab └─ :22 GitLab SSH(nginx stream → gitlab:22) |
Nginx 設定:
主要用 Docker 同時啟動 Nginx 跟 WireGuard,下面的 conf 選項僅供參考,以你實際用的為準
docker-compose.yml
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
networks: gitlab: name: gitlab-network external: true services: nginx: container_name: nginx image: nginx:latest volumes: - ${PWD}/conf/nginx.conf:/etc/nginx/nginx.conf - ${PWD}/conf/conf.d:/etc/nginx/conf.d - ${PWD}/conf/stream.d:/etc/nginx/stream.d - ${PWD}/conf/snippets:/etc/nginx/snippets - ${PWD}/conf/fastcgi_params:/etc/nginx/fastcgi_params - ${PWD}/conf/ssl:/etc/nginx/ssl restart: always ports: # WireGuard runs in this container's network namespace, so its UDP port is published here. - 51820:51820/udp networks: gitlab: # gitlab-runner / CI jobs reach https://gitlab.hiraku.tw directly through nginx # instead of the public IP (which would be rejected as a non-VPN source). aliases: - gitlab.hiraku.tw # WireGuard VPN server + in-VPN DNS, sharing nginx's network namespace. # VPN clients connecting to 10.66.66.1 talk to nginx directly, and nginx sees their 10.66.66.x source IP. # Image and config live in ../wireguard (use --build after changing Corefile or entrypoint.sh). wireguard: container_name: wireguard image: hiraku/wireguard:local build: ../wireguard restart: always network_mode: service:nginx depends_on: nginx: condition: service_started restart: true cap_add: - NET_ADMIN environment: WG_ADDRESS: 10.66.66.1/24 volumes: - /srv/wireguard:/etc/wireguard |
nginx.conf
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
user nginx; worker_processes auto; error_log /var/log/nginx/error.log notice; pid /run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; #tcp_nopush on; keepalive_timeout 65; #gzip on; include /etc/nginx/conf.d/*.conf; } # Everything above is identical to the official nginx image's default nginx.conf. # The stream block below is the only addition (GitLab SSH over the VPN, see stream.d/gitlab-ssh.conf). stream { include /etc/nginx/stream.d/*.conf; } |
conf.d/gitlab.hiraku.tw.conf
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
# GitLab: VPN only, https://gitlab.hiraku.tw # # Listens on port 443 inside the nginx container. That port is NOT published to the host # (the public listener is container port 8443), so neither the internet nor the office LAN # can reach it. Only: # - VPN users: Surge -> WireGuard -> 10.66.66.1:443 (wg0 lives in the nginx container) # - gitlab-runner / CI jobs: via the gitlab.hiraku.tw alias on gitlab-network -> nginx:443 server { listen 443 ssl; http2 on; server_name gitlab.hiraku.tw; server_tokens off; ## Don't show the nginx version number, a security best practice # This port is only reachable from the VPN and local containers (not published). # Source restrictions on top of that: # 10.66.66.0/24 VPN users # 172.16.0.0/12, 192.168.0.0/16 Docker networks (gitlab-runner, CI job containers) # The office LAN cannot reach this port even if it is 192.168.x, because it is not published. # To be stricter, replace the last two with gitlab-network's actual subnet: # docker network inspect gitlab-network -f '{{range .IPAM.Config}}{{.Subnet}}{{end}}' allow 10.66.66.0/24; allow 172.16.0.0/12; allow 192.168.0.0/16; deny all; # HTTPS SSL key ssl_certificate /etc/nginx/ssl/gitlab.hiraku.tw/fullchain.cer; ssl_certificate_key /etc/nginx/ssl/gitlab.hiraku.tw/private.key; # Include settings include /etc/nginx/snippets/ssl_intermediate_configuration; set $gitlab_upstream http://gitlab; location / { resolver 127.0.0.11 ipv6=off valid=30s; client_max_body_size 0; gzip off; ## https://github.com/gitlabhq/gitlabhq/issues/694 ## Some requests take more than 30 seconds. proxy_read_timeout 300; proxy_connect_timeout 300; proxy_redirect off; proxy_http_version 1.1; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Ssl on; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass $gitlab_upstream; } } |
stream.d/gitlab-ssh.conf
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
# GitLab SSH (git clone [email protected]:group/repo.git), VPN only. # # Port 22 exists only inside the nginx container and is not published to the host, # so only VPN clients (via wg0, source 10.66.66.x) can reach it. server { listen 22; allow 10.66.66.0/24; deny all; resolver 127.0.0.11 ipv6=off valid=30s; set $gitlab_ssh gitlab:22; proxy_pass $gitlab_ssh; proxy_connect_timeout 10s; } |
WireGuard 設定:
建立一個 wireguard 資料夾,跟 nginx 在同一個根目錄內,然後新增以下檔案(不需要任何資料夾)
Corefile:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
# In-VPN DNS. Listens only on wg0 (10.66.66.1); unreachable from the internet # and from Docker networks. # # Surge's WireGuard section uses dns-server = 10.66.66.1, queried through the tunnel. # gitlab resolve to 10.66.66.1 here, so https://gitlab.hiraku.tw go straight through the VPN. .:53 { bind 10.66.66.1 hosts { 10.66.66.1 gitlab.hiraku.tw ttl 60 fallthrough } # Everything else goes to Docker's embedded DNS, which forwards upstream. forward . 127.0.0.11 cache 60 errors } |
Dockerfile:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
# Minimal WireGuard server + in-VPN DNS (CoreDNS). # # wg-quick and linuxserver/wireguard are avoided on purpose: this container runs # inside the nginx container's network namespace and must never touch nginx's # routes or iptables (linuxserver/wireguard runs `ip route del default` on failure). FROM alpine:3.22 RUN apk add --no-cache iproute2 wireguard-tools-wg coredns COPY Corefile /etc/coredns/Corefile COPY --chmod=755 entrypoint.sh /entrypoint.sh HEALTHCHECK --interval=10s --timeout=3s --start-period=5s \ CMD wg show wg0 >/dev/null 2>&1 || exit 1 ENTRYPOINT ["/entrypoint.sh"] |
Entrypoint.sh:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 |
#!/bin/sh # Bring up wg0 inside the nginx container's network namespace and start the # in-VPN DNS server (CoreDNS). # # - Only creates the interface and sets keys / address. It never touches the # default route and adds no iptables rules. # - IP forwarding is off in this netns, so VPN clients can only reach ports nginx # listens on. They cannot be routed to other containers or the office LAN. # - Generates a server key on first start if no config exists. # - SIGHUP reloads the config (add / remove peers without a restart): # docker kill -s HUP wireguard # - If the nginx container is restarted on its own (docker restart nginx), this # container is left in the old, dead netns. A check every 10 seconds detects # that and exits, so Docker restarts it and it joins the new nginx netns. set -eu IFACE="${WG_INTERFACE:-wg0}" CONF="${WG_CONFIG:-/etc/wireguard/wg0.conf}" ADDR="${WG_ADDRESS:?WG_ADDRESS is required, e.g. 10.66.66.1/24}" PORT="${WG_LISTEN_PORT:-51820}" COREFILE="${COREFILE:-/etc/coredns/Corefile}" SLEEP_PID="" DNS_PID="" log() { echo "[wireguard] $*"; } down() { [ -n "$DNS_PID" ] && kill "$DNS_PID" 2>/dev/null || true ip link del "$IFACE" 2>/dev/null || true } init_config() { log "$CONF not found, generating a new server key" umask 077 mkdir -p "$(dirname "$CONF")" { echo "[Interface]" echo "PrivateKey = $(wg genkey)" echo "ListenPort = $PORT" } >"$CONF" } reload() { log "reloading $CONF" if wg syncconf "$IFACE" "$CONF"; then log "reloaded, peers: $(wg show "$IFACE" peers | wc -l)" else log "invalid config, keeping the running one" fi [ -n "$SLEEP_PID" ] && kill "$SLEEP_PID" 2>/dev/null || true } stop() { log "stopping, removing $IFACE" [ -n "$SLEEP_PID" ] && kill "$SLEEP_PID" 2>/dev/null || true down exit 0 } fail() { log "$*; exiting in 3 seconds so Docker restarts the container" down sleep 3 exit 1 } # The netns is alive as long as it has a Docker network interface besides lo / wg0. netns_alive() { ip -4 -o address show scope global | awk -v wg="$IFACE" '$2 != wg { found = 1 } END { exit !found }' } [ -s "$CONF" ] || init_config netns_alive || fail "no nginx network interface found (is the nginx container running?)" # Remove an interface left behind by an unclean exit. ip link del "$IFACE" 2>/dev/null || true ip link add "$IFACE" type wireguard wg setconf "$IFACE" "$CONF" ip address add "$ADDR" dev "$IFACE" ip link set "$IFACE" up log "$IFACE up: $ADDR, UDP $(wg show "$IFACE" listen-port), peers: $(wg show "$IFACE" peers | wc -l)" log "server public key: $(wg show "$IFACE" public-key)" coredns -conf "$COREFILE" -quiet & DNS_PID=$! trap stop TERM INT trap reload HUP while :; do sleep 10 & SLEEP_PID=$! wait "$SLEEP_PID" || true kill -0 "$DNS_PID" 2>/dev/null || fail "CoreDNS stopped" netns_alive || fail "nginx network namespace is gone (nginx was restarted)" done |
wg.sh
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 |
#!/usr/bin/env bash # Hiraku VPN peer management (run on the server; needs access to docker) # # ./wg.sh add <name> add a peer and print its Surge config (includes the private key, shown once) # ./wg.sh remove <name> revoke a peer (takes effect immediately) # ./wg.sh list list peers, VPN IPs and last handshake # # Use one key per device and name it person-device, e.g. hiraku-mac, hiraku-iphone, # so a lost device can be revoked on its own. set -euo pipefail CONTAINER="${WG_CONTAINER:-wireguard}" ENDPOINT="${WG_ENDPOINT:-vpn.hiraku.tw:51820}" # public address Surge connects to (router forwards UDP 51820) CONF=/etc/wireguard/wg0.conf # path inside the container; /srv/wireguard/wg0.conf on the host NET_PREFIX=10.66.66 SERVER_IP=10.66.66.1 SURGE_POLICY=Hiraku-VPN SURGE_SECTION=Hiraku die() { echo "error: $*" >&2; exit 1; } info() { echo "$*" >&2; } cexec() { docker exec -i "$CONTAINER" "$@"; } require_running() { [[ "$(docker inspect -f '{{.State.Running}}' "$CONTAINER" 2>/dev/null)" == "true" ]] || die "container $CONTAINER is not running; run docker compose up -d in nginx/ first" } read_conf() { cexec cat "$CONF"; } # Write stdin back to the config atomically (temp file + rename). write_conf() { cexec sh -c "umask 077 && cat > '$CONF.tmp' && mv '$CONF.tmp' '$CONF'"; } reload() { docker kill -s HUP "$CONTAINER" >/dev/null; } check_name() { [[ "$1" =~ ^[A-Za-z0-9][A-Za-z0-9._-]{0,31}$ ]] || die "name may only contain letters, digits, '.', '_' and '-' (max 32 chars)" } cmd_add() { local name=${1:-} [[ -n "$name" ]] || die "usage: $0 add <name>" check_name "$name" require_running local conf used ip="" n conf=$(read_conf) grep -qxF "# Name = $name" <<<"$conf" && die "peer $name already exists" used=$(sed -n "s#^AllowedIPs *= *${NET_PREFIX//./\\.}\.\([0-9]*\)/32.*#\1#p" <<<"$conf") for n in $(seq 2 254); do if ! grep -qx "$n" <<<"$used"; then ip="$NET_PREFIX.$n"; break; fi done [[ -n "$ip" ]] || die "no free VPN addresses left" local priv pub psk server_pub priv=$(cexec wg genkey) pub=$(cexec wg pubkey <<<"$priv") psk=$(cexec wg genpsk) server_pub=$(cexec wg show wg0 public-key) { printf '%s\n\n' "$conf" printf '[Peer]\n' printf '# Name = %s\n' "$name" printf '# Added = %s\n' "$(date '+%Y-%m-%d %H:%M')" printf 'PublicKey = %s\n' "$pub" printf 'PresharedKey = %s\n' "$psk" printf 'AllowedIPs = %s/32\n' "$ip" } | cat -s | write_conf reload info "Added $name ($ip). Surge config below. It contains the private key, which the server does not keep." info "" cat <<EOF # ============================================================ # Hiraku VPN (WireGuard) - peer: $name / VPN IP: $ip # Contains a private key: hand it over through a secure channel # (e.g. Bitwarden Send), never in a chat room. # ============================================================ # (1) Add to [Proxy] $SURGE_POLICY = wireguard, section-name = $SURGE_SECTION # (2) Add to the TOP of [Rule], so they match before any other rule DOMAIN,gitlab.hiraku.tw,$SURGE_POLICY # (3) Paste this whole section at the end of the profile [WireGuard $SURGE_SECTION] private-key = $priv self-ip = $ip dns-server = $SERVER_IP mtu = 1280 peer = (public-key = $server_pub, allowed-ips = $SERVER_IP/32, endpoint = $ENDPOINT, keepalive = 25, preshared-key = $psk) EOF } cmd_remove() { local name=${1:-} [[ -n "$name" ]] || die "usage: $0 remove <name>" check_name "$name" require_running local conf conf=$(read_conf) grep -qxF "# Name = $name" <<<"$conf" || die "peer $name not found" # Drop the [section] that contains "# Name = <name>". awk -v target="# Name = $name" ' function flush() { if (!skip) printf "%s", block; block = ""; skip = 0 } /^\[/ { flush() } { block = block $0 "\n" } $0 == target { skip = 1 } END { flush() } ' <<<"$conf" | cat -s | write_conf reload info "Revoked $name. The device can no longer connect." } cmd_list() { require_running local conf dump conf=$(read_conf) dump=$(cexec wg show wg0 dump) awk -v now="$(date +%s)" ' function human(b) { if (b >= 1073741824) return sprintf("%.1fG", b / 1073741824) if (b >= 1048576) return sprintf("%.1fM", b / 1048576) if (b >= 1024) return sprintf("%.1fK", b / 1024) return b "B" } function ago(t, d) { if (t == 0) return "never" d = now - t if (d < 60) return d "s ago" if (d < 3600) return int(d / 60) "m ago" if (d < 86400) return int(d / 3600) "h ago" return int(d / 86400) "d ago" } # First input: the config file, builds public key -> name. FNR == NR { if ($0 ~ /^\[/) name = "" if (index($0, "# Name = ") == 1) name = substr($0, 10) if ($1 == "PublicKey") names[$3] = name next } # Second input: `wg show dump` (the first line is the interface itself). FNR == 1 { printf "%-24s %-14s %-22s %-12s %s\n", "NAME", "VPN IP", "ENDPOINT", "HANDSHAKE", "RX / TX" next } { n = ($1 in names && names[$1] != "") ? names[$1] : "(unnamed)" ip = $4; sub(/\/32$/, "", ip) ep = ($3 == "(none)") ? "-" : $3 printf "%-24s %-14s %-22s %-12s %s / %s\n", n, ip, ep, ago($5), human($6), human($7) } ' <(printf '%s\n' "$conf") <(printf '%s\n' "$dump") } case "${1:-}" in add) shift; cmd_add "$@" ;; remove | rm | revoke) shift; cmd_remove "$@" ;; list | ls) cmd_list ;; *) sed -n '2,9s/^# \{0,1\}//p' "$0" exit 1 ;; esac |
wireguard-boot.service
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
# Boot safety net: the wireguard container shares nginx's network namespace. # If Docker starts wireguard before nginx at boot, the start fails and Docker # does not retry it. This unit starts it again once everything is up. # # Install: # sudo cp wireguard-boot.service /etc/systemd/system/ # sudo systemctl daemon-reload && sudo systemctl enable wireguard-boot.service [Unit] Description=Ensure WireGuard container is running after nginx Requires=docker.service After=docker.service [Service] Type=oneshot ExecStartPre=/bin/sleep 20 ExecStart=/usr/bin/docker start wireguard [Install] WantedBy=multi-user.target |
這樣設定就可以了。接著 docker compose up,把 nginx 跟 wireguard 一起啟動
最後做開機保險,讓 WireGuard 在重新開機之後確保是比 nginx 晚啟動的
|
1 2 3 |
cd wireguard sudo cp wireguard-boot.service /etc/systemd/system/ sudo systemctl daemon-reload && sudo systemctl enable wireguard-boot.service |
新增 / 撤銷使用者
一台裝置一組金鑰:
|
1 2 3 4 |
cd wireguard ./wg.sh add hiraku-mac # 輸出 Surge 設定(含私鑰,只會顯示這一次) ./wg.sh list # 使用者、VPN IP、最後連線時間 ./wg.sh remove hiraku-mac # 撤銷,立即生效(裝置遺失、離職) |
新增與撤銷都是熱更新,不用重啟。私鑰伺服器不保存,弄丟就撤銷後重新發一組。
因為我是用 Surge 連線的關係,所以上面的腳本會提示使用者如何用 Surge 設定。
如果你不是用 Surge 的話,總之先設定 WireGuard 的部分,然後在 CloudFlare 設定你的 GitLab domain 走 WireGuard 就是了。
最後,在 CloudFlare 設定你的 WireGuard 域名 A 紀錄到你的 IP,並且關掉 GitLab 的 A 紀錄,路由器記得開對應的 WireGuard UDP Port forwarding 就好了。
