Created
July 26, 2026 01:02
-
-
Save mohashari/aa89ff66ce724c57b1c184c855236714 to your computer and use it in GitHub Desktop.
Implementing Ephemeral WireGuard VPN Tunnels for Secure Cross-Cloud Database Replication — code snippets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env bash | |
| set -euo pipefail | |
| # Enable IP forwarding and disable reverse path filtering hazards | |
| echo "Optimizing network sysctl for WireGuard gateway..." | |
| sudo sysctl -w net.ipv4.ip_forward=1 | |
| sudo sysctl -w net.ipv4.conf.all.forwarding=1 | |
| sudo sysctl -w net.ipv4.conf.all.rp_filter=2 | |
| sudo sysctl -w net.ipv4.conf.default.rp_filter=2 | |
| # Persist configuration | |
| cat <<EOF | sudo tee /etc/sysctl.d/99-wireguard-replication.conf | |
| net.ipv4.ip_forward = 1 | |
| net.ipv4.conf.all.forwarding = 1 | |
| net.ipv4.conf.all.rp_filter = 2 | |
| net.ipv4.conf.default.rp_filter = 2 | |
| EOF | |
| # Install wireguard utilities | |
| sudo apt-get update && sudo apt-get install -y wireguard iptables-persistent | |
| # Create private/public key directories with strict permissions | |
| sudo mkdir -p -m 0700 /etc/wireguard |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| [Interface] | |
| # Local node settings | |
| PrivateKey = [LOCAL_PRIVATE_KEY] | |
| Address = 192.168.2.1/30 | |
| ListenPort = 51820 | |
| MTU = 1420 | |
| # Post-up: Clamp MSS to match MTU and prevent TCP handshaking stalls | |
| PostUp = iptables -A FORWARD -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtud | |
| PostUp = iptables -A FORWARD -i %i -j ACCEPT; iptables -A FORWARD -o %i -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE | |
| PostDown = iptables -D FORWARD -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtud | |
| PostDown = iptables -D FORWARD -i %i -j ACCEPT; iptables -D FORWARD -o %i -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE | |
| [Peer] | |
| # Remote peer settings (e.g. GCP replica node gateway) | |
| PublicKey = [REMOTE_PUBLIC_KEY] | |
| PresharedKey = [PRE_SHARED_KEY] | |
| Endpoint = 34.120.45.67:51820 | |
| AllowedIPs = 192.168.2.2/32, 10.2.0.0/16 | |
| PersistentKeepalive = 25 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "fmt" | |
| "log" | |
| "net" | |
| "github.com/vishvananda/netlink" | |
| "golang.zx2c4.com/wireguard/wgctrl" | |
| "golang.zx2c4.com/wireguard/wgctrl/wgtypes" | |
| ) | |
| // setupWireGuard programmatically configures the network interface | |
| func setupWireGuard(linkName string, privateKeyHex string, peerPublicKeyHex string, localIP string, peerEndpoint string, allowedIPs []string) error { | |
| // 1. Create WireGuard link in the kernel | |
| la := netlink.NewLinkAttrs() | |
| la.Name = linkName | |
| wgLink := &netlink.GenericLink{ | |
| LinkAttrs: la, | |
| LinkType: "wireguard", | |
| } | |
| if err := netlink.LinkAdd(wgLink); err != nil { | |
| return fmt.Errorf("failed to create interface %s: %w", linkName, err) | |
| } | |
| // 2. Assign IP Address to interface | |
| addr, err := netlink.ParseAddr(localIP) | |
| if err != nil { | |
| return fmt.Errorf("invalid local IP %s: %w", localIP, err) | |
| } | |
| if err := netlink.AddrAdd(wgLink, addr); err != nil { | |
| return fmt.Errorf("failed to assign IP: %w", err) | |
| } | |
| // 3. Configure WireGuard device keys and peers | |
| client, err := wgctrl.New() | |
| if err != nil { | |
| return fmt.Errorf("failed to open wgctrl client: %w", err) | |
| } | |
| defer client.Close() | |
| privKey, err := wgtypes.ParseKey(privateKeyHex) | |
| if err != nil { | |
| return fmt.Errorf("invalid private key: %w", err) | |
| } | |
| peerPub, err := wgtypes.ParseKey(peerPublicKeyHex) | |
| if err != nil { | |
| return fmt.Errorf("invalid peer public key: %w", err) | |
| } | |
| var parsedAllowedIPs []net.IPNet | |
| for _, cidr := range allowedIPs { | |
| _, ipNet, err := net.ParseCIDR(cidr) | |
| if err != nil { | |
| return fmt.Errorf("invalid CIDR %s: %w", cidr, err) | |
| } | |
| parsedAllowedIPs = append(parsedAllowedIPs, *ipNet) | |
| } | |
| udpAddr, err := net.ResolveUDPAddr("udp", peerEndpoint) | |
| if err != nil { | |
| return fmt.Errorf("failed to resolve endpoint %s: %w", peerEndpoint, err) | |
| } | |
| cfg := wgtypes.Config{ | |
| PrivateKey: &privKey, | |
| ReplacePeers: true, | |
| Peers: []wgtypes.PeerConfig{ | |
| { | |
| PublicKey: peerPub, | |
| Endpoint: udpAddr, | |
| AllowedIPs: parsedAllowedIPs, | |
| ReplaceAllowedIPs: true, | |
| }, | |
| }, | |
| } | |
| if err := client.ConfigureDevice(linkName, cfg); err != nil { | |
| return fmt.Errorf("failed to configure WireGuard device: %w", err) | |
| } | |
| // 4. Bring the interface UP | |
| if err := netlink.LinkSetUp(wgLink); err != nil { | |
| return fmt.Errorf("failed to set interface UP: %w", err) | |
| } | |
| fmt.Printf("WireGuard interface %s successfully configured and brought online.\n", linkName) | |
| return nil | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| -- postgresql.conf updates | |
| -- Listen on both the internal VPC network and the WireGuard tunnel interface | |
| listen_addresses = 'localhost,10.0.1.50,192.168.2.1' | |
| wal_level = replica | |
| max_wal_senders = 5 | |
| max_replication_slots = 5 | |
| hot_standby = on | |
| -- pg_hba.conf updates (allow replication over the WireGuard tunnel only) | |
| -- TYPE DATABASE USER ADDRESS METHOD | |
| host replication replicator 192.168.2.2/32 scram-sha-256 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env bash | |
| # Note: This script runs on the GCP database replica instance to initialize replication | |
| set -euo pipefail | |
| PRIMARY_WG_IP="192.168.2.1" | |
| REPLICA_DATA_DIR="/var/lib/postgresql/15/main" | |
| REPLICATOR_USER="replicator" | |
| echo "Stopping local database replica instance..." | |
| sudo systemctl stop postgresql | |
| echo "Cleaning up local cluster state..." | |
| sudo -u postgres rm -rf "${REPLICA_DATA_DIR:?}/*" | |
| echo "Initiating pg_basebackup over ephemeral WireGuard link..." | |
| PGPASSWORD="HighlySecureProductionPassword123!" \ | |
| sudo -u postgres pg_basebackup \ | |
| -h "${PRIMARY_WG_IP}" \ | |
| -D "${REPLICA_DATA_DIR}" \ | |
| -U "${REPLICATOR_USER}" \ | |
| -P \ | |
| -R \ | |
| -X stream \ | |
| --checkpoint=fast | |
| echo "Base backup completed. Starting replica PostgreSQL service..." | |
| sudo systemctl start postgresql |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env bash | |
| set -euo pipefail | |
| # Define interface variables | |
| WG_INTERFACE="wg0" | |
| DB_PORT="5432" | |
| echo "Enforcing zero-trust network boundaries on WireGuard gateway..." | |
| # Drop all forwarding traffic by default through the tunnel | |
| sudo iptables -I FORWARD -i ${WG_INTERFACE} -j DROP | |
| sudo iptables -I FORWARD -o ${WG_INTERFACE} -j DROP | |
| # Allow only PostgreSQL replication traffic (Port 5432) from the replica peer to primary | |
| sudo iptables -I FORWARD -i ${WG_INTERFACE} -p tcp --dport ${DB_PORT} -j ACCEPT | |
| sudo iptables -I FORWARD -o ${WG_INTERFACE} -p tcp --sport ${DB_PORT} -j ACCEPT | |
| # Allow established/related traffic | |
| sudo iptables -I FORWARD -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT | |
| # Save the iptables rules to remain persistent across reboots | |
| sudo iptables-save | sudo tee /etc/iptables/rules.v4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment