mirror of
https://github.com/fosrl/gerbil.git
synced 2026-02-07 21:46:40 +00:00
Compare commits
24 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c3e73d0189 | ||
|
|
df2fbdf160 | ||
|
|
cb4ac8199d | ||
|
|
dd4b86b3e5 | ||
|
|
bad290aa4e | ||
|
|
8c27d5e3bf | ||
|
|
7e7a37d49c | ||
|
|
d44aa97f32 | ||
|
|
b57ad74589 | ||
|
|
82256a3f6f | ||
|
|
9e140a94db | ||
|
|
d0c9ea5a57 | ||
|
|
c88810ef24 | ||
|
|
463a4eea79 | ||
|
|
4576a2e8a7 | ||
|
|
69c13adcdb | ||
|
|
3886c1a8c1 | ||
|
|
06eb4d4310 | ||
|
|
247c47b27f | ||
|
|
060038c29b | ||
|
|
5414d21dcd | ||
|
|
364fa020aa | ||
|
|
b96ee16fbf | ||
|
|
467d69aa7c |
17
.github/workflows/cicd.yml
vendored
17
.github/workflows/cicd.yml
vendored
@@ -14,9 +14,10 @@ permissions:
|
|||||||
# - COSIGN_PRIVATE_KEY / COSIGN_PASSWORD / COSIGN_PUBLIC_KEY: for key-based signing
|
# - COSIGN_PRIVATE_KEY / COSIGN_PASSWORD / COSIGN_PUBLIC_KEY: for key-based signing
|
||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
tags:
|
tags:
|
||||||
- "*"
|
- "[0-9]+.[0-9]+.[0-9]+"
|
||||||
|
- "[0-9]+.[0-9]+.[0-9]+.rc.[0-9]+"
|
||||||
|
|
||||||
concurrency:
|
concurrency:
|
||||||
group: ${{ github.ref }}
|
group: ${{ github.ref }}
|
||||||
@@ -30,18 +31,18 @@ jobs:
|
|||||||
timeout-minutes: 120
|
timeout-minutes: 120
|
||||||
env:
|
env:
|
||||||
# Target images
|
# Target images
|
||||||
DOCKERHUB_IMAGE: docker.io/${{ secrets.DOCKER_HUB_USERNAME }}/${{ github.event.repository.name }}
|
DOCKERHUB_IMAGE: docker.io/fosrl/${{ github.event.repository.name }}
|
||||||
GHCR_IMAGE: ghcr.io/${{ github.repository_owner }}/${{ github.event.repository.name }}
|
GHCR_IMAGE: ghcr.io/${{ github.repository_owner }}/${{ github.event.repository.name }}
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout code
|
- name: Checkout code
|
||||||
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0
|
uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1
|
||||||
|
|
||||||
- name: Set up QEMU
|
- name: Set up QEMU
|
||||||
uses: docker/setup-qemu-action@c7c53464625b32c7a7e944ae62b3e17d2b600130 # v3.7.0
|
uses: docker/setup-qemu-action@c7c53464625b32c7a7e944ae62b3e17d2b600130 # v3.7.0
|
||||||
|
|
||||||
- name: Set up Docker Buildx
|
- name: Set up Docker Buildx
|
||||||
uses: docker/setup-buildx-action@e468171a9de216ec08956ac3ada2f0791b6bd435 # v3.11.1
|
uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3.12.0
|
||||||
|
|
||||||
- name: Log in to Docker Hub
|
- name: Log in to Docker Hub
|
||||||
uses: docker/login-action@5e57cd118135c172c3672efd75eb46360885c0ef # v3.6.0
|
uses: docker/login-action@5e57cd118135c172c3672efd75eb46360885c0ef # v3.6.0
|
||||||
@@ -56,7 +57,7 @@ jobs:
|
|||||||
shell: bash
|
shell: bash
|
||||||
|
|
||||||
- name: Install Go
|
- name: Install Go
|
||||||
uses: actions/setup-go@4dc6199c7b1a012772edbd06daecab0f50c9053c # v6.1.0
|
uses: actions/setup-go@7a3fe6cf4cb3a834922a1244abfce67bcef6a0c5 # v6.2.0
|
||||||
with:
|
with:
|
||||||
go-version: 1.25
|
go-version: 1.25
|
||||||
|
|
||||||
@@ -154,7 +155,7 @@ jobs:
|
|||||||
shell: bash
|
shell: bash
|
||||||
|
|
||||||
- name: Upload artifacts from /bin
|
- name: Upload artifacts from /bin
|
||||||
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0
|
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
|
||||||
with:
|
with:
|
||||||
name: binaries
|
name: binaries
|
||||||
path: bin/
|
path: bin/
|
||||||
|
|||||||
4
.github/workflows/test.yml
vendored
4
.github/workflows/test.yml
vendored
@@ -14,10 +14,10 @@ jobs:
|
|||||||
runs-on: amd64-runner
|
runs-on: amd64-runner
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0
|
- uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1
|
||||||
|
|
||||||
- name: Set up Go
|
- name: Set up Go
|
||||||
uses: actions/setup-go@4dc6199c7b1a012772edbd06daecab0f50c9053c # v6.1.0
|
uses: actions/setup-go@7a3fe6cf4cb3a834922a1244abfce67bcef6a0c5 # v6.2.0
|
||||||
with:
|
with:
|
||||||
go-version: 1.25
|
go-version: 1.25
|
||||||
|
|
||||||
|
|||||||
@@ -42,13 +42,12 @@ In single node (self hosted) Pangolin deployments this can be bypassed by using
|
|||||||
|
|
||||||
## CLI Args
|
## CLI Args
|
||||||
|
|
||||||
|
Important:
|
||||||
- `reachableAt`: How should the remote server reach Gerbil's API?
|
- `reachableAt`: How should the remote server reach Gerbil's API?
|
||||||
- `generateAndSaveKeyTo`: Where to save the generated WireGuard private key to persist across restarts.
|
- `generateAndSaveKeyTo`: Where to save the generated WireGuard private key to persist across restarts.
|
||||||
- `remoteConfig` (optional): Remote config location to HTTP get the JSON based config from. See `example_config.json`
|
- `remoteConfig`: Remote config location to HTTP get the JSON based config from.
|
||||||
- `config` (optional): Local JSON file path to load config. Used if remote config is not supplied. See `example_config.json`
|
|
||||||
|
|
||||||
Note: You must use either `config` or `remoteConfig` to configure WireGuard.
|
|
||||||
|
|
||||||
|
Others:
|
||||||
- `reportBandwidthTo` (optional): **DEPRECATED** - Use `remoteConfig` instead. Remote HTTP endpoint to send peer bandwidth data
|
- `reportBandwidthTo` (optional): **DEPRECATED** - Use `remoteConfig` instead. Remote HTTP endpoint to send peer bandwidth data
|
||||||
- `interface` (optional): Name of the WireGuard interface created by Gerbil. Default: `wg0`
|
- `interface` (optional): Name of the WireGuard interface created by Gerbil. Default: `wg0`
|
||||||
- `listen` (optional): Port to listen on for HTTP server. Default: `:3004`
|
- `listen` (optional): Port to listen on for HTTP server. Default: `:3004`
|
||||||
@@ -66,7 +65,6 @@ Note: You must use either `config` or `remoteConfig` to configure WireGuard.
|
|||||||
All CLI arguments can also be provided via environment variables:
|
All CLI arguments can also be provided via environment variables:
|
||||||
|
|
||||||
- `INTERFACE`: Name of the WireGuard interface
|
- `INTERFACE`: Name of the WireGuard interface
|
||||||
- `CONFIG`: Path to local configuration file
|
|
||||||
- `REMOTE_CONFIG`: URL of the remote config server
|
- `REMOTE_CONFIG`: URL of the remote config server
|
||||||
- `LISTEN`: Address to listen on for HTTP server
|
- `LISTEN`: Address to listen on for HTTP server
|
||||||
- `GENERATE_AND_SAVE_KEY_TO`: Path to save generated private key
|
- `GENERATE_AND_SAVE_KEY_TO`: Path to save generated private key
|
||||||
|
|||||||
@@ -1,23 +0,0 @@
|
|||||||
{
|
|
||||||
"privateKey": "kBGTgk7c+zncEEoSnMl+jsLjVh5ZVoL/HwBSQem+d1M=",
|
|
||||||
"listenPort": 51820,
|
|
||||||
"ipAddress": "10.0.0.1/24",
|
|
||||||
"peers": [
|
|
||||||
{
|
|
||||||
"publicKey": "5UzzoeveFVSzuqK3nTMS5bA1jIMs1fQffVQzJ8MXUQM=",
|
|
||||||
"allowedIps": ["10.0.0.0/28"]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"publicKey": "kYrZpuO2NsrFoBh1GMNgkhd1i9Rgtu1rAjbJ7qsfngU=",
|
|
||||||
"allowedIps": ["10.0.0.16/28"]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"publicKey": "1YfPUVr9ZF4zehkbI2BQhCxaRLz+Vtwa4vJwH+mpK0A=",
|
|
||||||
"allowedIps": ["10.0.0.32/28"]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"publicKey": "2/U4oyZ+sai336Dal/yExCphL8AxyqvIxMk4qsUy4iI=",
|
|
||||||
"allowedIps": ["10.0.0.48/28"]
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
6
go.mod
6
go.mod
@@ -5,7 +5,8 @@ go 1.25
|
|||||||
require (
|
require (
|
||||||
github.com/patrickmn/go-cache v2.1.0+incompatible
|
github.com/patrickmn/go-cache v2.1.0+incompatible
|
||||||
github.com/vishvananda/netlink v1.3.1
|
github.com/vishvananda/netlink v1.3.1
|
||||||
golang.org/x/crypto v0.45.0
|
golang.org/x/crypto v0.46.0
|
||||||
|
golang.org/x/sync v0.1.0
|
||||||
golang.zx2c4.com/wireguard/wgctrl v0.0.0-20230429144221-925a1e7659e6
|
golang.zx2c4.com/wireguard/wgctrl v0.0.0-20230429144221-925a1e7659e6
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -17,7 +18,6 @@ require (
|
|||||||
github.com/mdlayher/socket v0.4.1 // indirect
|
github.com/mdlayher/socket v0.4.1 // indirect
|
||||||
github.com/vishvananda/netns v0.0.5 // indirect
|
github.com/vishvananda/netns v0.0.5 // indirect
|
||||||
golang.org/x/net v0.47.0 // indirect
|
golang.org/x/net v0.47.0 // indirect
|
||||||
golang.org/x/sync v0.1.0 // indirect
|
golang.org/x/sys v0.39.0 // indirect
|
||||||
golang.org/x/sys v0.38.0 // indirect
|
|
||||||
golang.zx2c4.com/wireguard v0.0.0-20230325221338-052af4a8072b // indirect
|
golang.zx2c4.com/wireguard v0.0.0-20230325221338-052af4a8072b // indirect
|
||||||
)
|
)
|
||||||
|
|||||||
8
go.sum
8
go.sum
@@ -16,16 +16,16 @@ github.com/vishvananda/netlink v1.3.1 h1:3AEMt62VKqz90r0tmNhog0r/PpWKmrEShJU0wJW
|
|||||||
github.com/vishvananda/netlink v1.3.1/go.mod h1:ARtKouGSTGchR8aMwmkzC0qiNPrrWO5JS/XMVl45+b4=
|
github.com/vishvananda/netlink v1.3.1/go.mod h1:ARtKouGSTGchR8aMwmkzC0qiNPrrWO5JS/XMVl45+b4=
|
||||||
github.com/vishvananda/netns v0.0.5 h1:DfiHV+j8bA32MFM7bfEunvT8IAqQ/NzSJHtcmW5zdEY=
|
github.com/vishvananda/netns v0.0.5 h1:DfiHV+j8bA32MFM7bfEunvT8IAqQ/NzSJHtcmW5zdEY=
|
||||||
github.com/vishvananda/netns v0.0.5/go.mod h1:SpkAiCQRtJ6TvvxPnOSyH3BMl6unz3xZlaprSwhNNJM=
|
github.com/vishvananda/netns v0.0.5/go.mod h1:SpkAiCQRtJ6TvvxPnOSyH3BMl6unz3xZlaprSwhNNJM=
|
||||||
golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q=
|
golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU=
|
||||||
golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4=
|
golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0=
|
||||||
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
|
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
|
||||||
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
|
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
|
||||||
golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=
|
golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=
|
||||||
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
|
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
|
||||||
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||||
golang.zx2c4.com/wireguard v0.0.0-20230325221338-052af4a8072b h1:J1CaxgLerRR5lgx3wnr6L04cJFbWoceSK9JWBdglINo=
|
golang.zx2c4.com/wireguard v0.0.0-20230325221338-052af4a8072b h1:J1CaxgLerRR5lgx3wnr6L04cJFbWoceSK9JWBdglINo=
|
||||||
golang.zx2c4.com/wireguard v0.0.0-20230325221338-052af4a8072b/go.mod h1:tqur9LnfstdR9ep2LaJT4lFUl0EjlHtge+gAjmsHUG4=
|
golang.zx2c4.com/wireguard v0.0.0-20230325221338-052af4a8072b/go.mod h1:tqur9LnfstdR9ep2LaJT4lFUl0EjlHtge+gAjmsHUG4=
|
||||||
golang.zx2c4.com/wireguard/wgctrl v0.0.0-20230429144221-925a1e7659e6 h1:CawjfCvYQH2OU3/TnxLx97WDSUDRABfT18pCOYwc2GE=
|
golang.zx2c4.com/wireguard/wgctrl v0.0.0-20230429144221-925a1e7659e6 h1:CawjfCvYQH2OU3/TnxLx97WDSUDRABfT18pCOYwc2GE=
|
||||||
|
|||||||
156
main.go
156
main.go
@@ -8,11 +8,15 @@ import (
|
|||||||
"flag"
|
"flag"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
"log"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
_ "net/http/pprof"
|
||||||
"os"
|
"os"
|
||||||
"os/exec"
|
"os/exec"
|
||||||
"os/signal"
|
"os/signal"
|
||||||
|
"runtime"
|
||||||
|
"runtime/pprof"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
@@ -43,6 +47,7 @@ var (
|
|||||||
type WgConfig struct {
|
type WgConfig struct {
|
||||||
PrivateKey string `json:"privateKey"`
|
PrivateKey string `json:"privateKey"`
|
||||||
ListenPort int `json:"listenPort"`
|
ListenPort int `json:"listenPort"`
|
||||||
|
RelayPort int `json:"relayPort"`
|
||||||
IpAddress string `json:"ipAddress"`
|
IpAddress string `json:"ipAddress"`
|
||||||
Peers []Peer `json:"peers"`
|
Peers []Peer `json:"peers"`
|
||||||
}
|
}
|
||||||
@@ -111,6 +116,8 @@ func parseLogLevel(level string) logger.LogLevel {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
go monitorMemory(1024 * 1024 * 512) // trigger if memory usage exceeds 512MB
|
||||||
|
|
||||||
var (
|
var (
|
||||||
err error
|
err error
|
||||||
wgconfig WgConfig
|
wgconfig WgConfig
|
||||||
@@ -340,7 +347,11 @@ func main() {
|
|||||||
})
|
})
|
||||||
|
|
||||||
// Start the UDP proxy server
|
// Start the UDP proxy server
|
||||||
proxyRelay = relay.NewUDPProxyServer(groupCtx, ":21820", remoteConfigURL, key, reachableAt)
|
relayPort := wgconfig.RelayPort
|
||||||
|
if relayPort == 0 {
|
||||||
|
relayPort = 21820 // in case there is no relay port set, use 21820
|
||||||
|
}
|
||||||
|
proxyRelay = relay.NewUDPProxyServer(groupCtx, fmt.Sprintf(":%d", relayPort), remoteConfigURL, key, reachableAt)
|
||||||
err = proxyRelay.Start()
|
err = proxyRelay.Start()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Fatal("Failed to start UDP proxy server: %v", err)
|
logger.Fatal("Failed to start UDP proxy server: %v", err)
|
||||||
@@ -382,6 +393,7 @@ func main() {
|
|||||||
http.HandleFunc("/update-proxy-mapping", handleUpdateProxyMapping)
|
http.HandleFunc("/update-proxy-mapping", handleUpdateProxyMapping)
|
||||||
http.HandleFunc("/update-destinations", handleUpdateDestinations)
|
http.HandleFunc("/update-destinations", handleUpdateDestinations)
|
||||||
http.HandleFunc("/update-local-snis", handleUpdateLocalSNIs)
|
http.HandleFunc("/update-local-snis", handleUpdateLocalSNIs)
|
||||||
|
http.HandleFunc("/healthz", handleHealthz)
|
||||||
logger.Info("Starting HTTP server on %s", listenAddr)
|
logger.Info("Starting HTTP server on %s", listenAddr)
|
||||||
|
|
||||||
// HTTP server with graceful shutdown on context cancel
|
// HTTP server with graceful shutdown on context cancel
|
||||||
@@ -543,6 +555,10 @@ func ensureWireguardInterface(wgconfig WgConfig) error {
|
|||||||
logger.Warn("Failed to ensure MSS clamping: %v", err)
|
logger.Warn("Failed to ensure MSS clamping: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if err := ensureWireguardFirewall(); err != nil {
|
||||||
|
logger.Warn("Failed to ensure WireGuard firewall rules: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
logger.Info("WireGuard interface %s created and configured", interfaceName)
|
logger.Info("WireGuard interface %s created and configured", interfaceName)
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
@@ -711,6 +727,113 @@ func ensureMSSClamping() error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func ensureWireguardFirewall() error {
|
||||||
|
// Rules to enforce:
|
||||||
|
// 1. Allow established/related connections (responses to our outbound traffic)
|
||||||
|
// 2. Allow ICMP ping packets
|
||||||
|
// 3. Drop all other inbound traffic from peers
|
||||||
|
|
||||||
|
// Define the rules we want to ensure exist
|
||||||
|
rules := [][]string{
|
||||||
|
// Allow established and related connections (responses to outbound traffic)
|
||||||
|
{
|
||||||
|
"-A", "INPUT",
|
||||||
|
"-i", interfaceName,
|
||||||
|
"-m", "conntrack",
|
||||||
|
"--ctstate", "ESTABLISHED,RELATED",
|
||||||
|
"-j", "ACCEPT",
|
||||||
|
},
|
||||||
|
// Allow ICMP ping requests
|
||||||
|
{
|
||||||
|
"-A", "INPUT",
|
||||||
|
"-i", interfaceName,
|
||||||
|
"-p", "icmp",
|
||||||
|
"--icmp-type", "8",
|
||||||
|
"-j", "ACCEPT",
|
||||||
|
},
|
||||||
|
// Drop all other inbound traffic from WireGuard interface
|
||||||
|
{
|
||||||
|
"-A", "INPUT",
|
||||||
|
"-i", interfaceName,
|
||||||
|
"-j", "DROP",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
// First, try to delete any existing rules for this interface
|
||||||
|
for _, rule := range rules {
|
||||||
|
deleteArgs := make([]string, len(rule))
|
||||||
|
copy(deleteArgs, rule)
|
||||||
|
// Change -A to -D for deletion
|
||||||
|
for i, arg := range deleteArgs {
|
||||||
|
if arg == "-A" {
|
||||||
|
deleteArgs[i] = "-D"
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
deleteCmd := exec.Command("/usr/sbin/iptables", deleteArgs...)
|
||||||
|
logger.Debug("Attempting to delete existing firewall rule: %v", deleteArgs)
|
||||||
|
|
||||||
|
// Try deletion multiple times to handle multiple existing rules
|
||||||
|
for i := 0; i < 5; i++ {
|
||||||
|
out, err := deleteCmd.CombinedOutput()
|
||||||
|
if err != nil {
|
||||||
|
if exitErr, ok := err.(*exec.ExitError); ok {
|
||||||
|
logger.Debug("Deletion stopped: %v (output: %s)", exitErr.String(), string(out))
|
||||||
|
}
|
||||||
|
break // No more rules to delete
|
||||||
|
}
|
||||||
|
logger.Info("Deleted existing firewall rule (attempt %d)", i+1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Now add the rules
|
||||||
|
var errors []error
|
||||||
|
for i, rule := range rules {
|
||||||
|
addCmd := exec.Command("/usr/sbin/iptables", rule...)
|
||||||
|
logger.Info("Adding WireGuard firewall rule %d: %v", i+1, rule)
|
||||||
|
|
||||||
|
if out, err := addCmd.CombinedOutput(); err != nil {
|
||||||
|
errMsg := fmt.Sprintf("Failed to add firewall rule %d: %v (output: %s)", i+1, err, string(out))
|
||||||
|
logger.Error("%s", errMsg)
|
||||||
|
errors = append(errors, fmt.Errorf("%s", errMsg))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify the rule was added by checking
|
||||||
|
checkArgs := make([]string, len(rule))
|
||||||
|
copy(checkArgs, rule)
|
||||||
|
// Change -A to -C for check
|
||||||
|
for j, arg := range checkArgs {
|
||||||
|
if arg == "-A" {
|
||||||
|
checkArgs[j] = "-C"
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
checkCmd := exec.Command("/usr/sbin/iptables", checkArgs...)
|
||||||
|
if out, err := checkCmd.CombinedOutput(); err != nil {
|
||||||
|
errMsg := fmt.Sprintf("Rule verification failed for rule %d: %v (output: %s)", i+1, err, string(out))
|
||||||
|
logger.Error("%s", errMsg)
|
||||||
|
errors = append(errors, fmt.Errorf("%s", errMsg))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.Info("Successfully added and verified WireGuard firewall rule %d", i+1)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(errors) > 0 {
|
||||||
|
var errMsgs []string
|
||||||
|
for _, err := range errors {
|
||||||
|
errMsgs = append(errMsgs, err.Error())
|
||||||
|
}
|
||||||
|
return fmt.Errorf("WireGuard firewall setup encountered errors:\n%s", strings.Join(errMsgs, "\n"))
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.Info("WireGuard firewall rules successfully configured for interface %s", interfaceName)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func handlePeer(w http.ResponseWriter, r *http.Request) {
|
func handlePeer(w http.ResponseWriter, r *http.Request) {
|
||||||
switch r.Method {
|
switch r.Method {
|
||||||
case http.MethodPost:
|
case http.MethodPost:
|
||||||
@@ -722,6 +845,15 @@ func handlePeer(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func handleHealthz(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method != http.MethodGet {
|
||||||
|
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
_, _ = w.Write([]byte("ok"))
|
||||||
|
}
|
||||||
|
|
||||||
func handleAddPeer(w http.ResponseWriter, r *http.Request) {
|
func handleAddPeer(w http.ResponseWriter, r *http.Request) {
|
||||||
var peer Peer
|
var peer Peer
|
||||||
if err := json.NewDecoder(r.Body).Decode(&peer); err != nil {
|
if err := json.NewDecoder(r.Body).Decode(&peer); err != nil {
|
||||||
@@ -1161,3 +1293,25 @@ func notifyPeerChange(action, publicKey string) {
|
|||||||
logger.Warn("Notify server returned non-OK: %s", resp.Status)
|
logger.Warn("Notify server returned non-OK: %s", resp.Status)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func monitorMemory(limit uint64) {
|
||||||
|
var m runtime.MemStats
|
||||||
|
for {
|
||||||
|
runtime.ReadMemStats(&m)
|
||||||
|
if m.Alloc > limit {
|
||||||
|
fmt.Printf("Memory spike detected (%d bytes). Dumping profile...\n", m.Alloc)
|
||||||
|
|
||||||
|
f, err := os.Create(fmt.Sprintf("/var/config/heap/heap-spike-%d.pprof", time.Now().Unix()))
|
||||||
|
if err != nil {
|
||||||
|
log.Println("could not create profile:", err)
|
||||||
|
} else {
|
||||||
|
pprof.WriteHeapProfile(f)
|
||||||
|
f.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait a while before checking again to avoid spamming profiles
|
||||||
|
time.Sleep(5 * time.Minute)
|
||||||
|
}
|
||||||
|
time.Sleep(5 * time.Second)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -758,14 +758,20 @@ func (p *SNIProxy) pipe(clientConn, targetConn net.Conn, clientReader io.Reader)
|
|||||||
var wg sync.WaitGroup
|
var wg sync.WaitGroup
|
||||||
wg.Add(2)
|
wg.Add(2)
|
||||||
|
|
||||||
|
// closeOnce ensures we only close connections once
|
||||||
|
var closeOnce sync.Once
|
||||||
|
closeConns := func() {
|
||||||
|
closeOnce.Do(func() {
|
||||||
|
// Close both connections to unblock any pending reads
|
||||||
|
clientConn.Close()
|
||||||
|
targetConn.Close()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
// Copy data from client to target (using the buffered reader)
|
// Copy data from client to target (using the buffered reader)
|
||||||
go func() {
|
go func() {
|
||||||
defer wg.Done()
|
defer wg.Done()
|
||||||
defer func() {
|
defer closeConns()
|
||||||
if tcpConn, ok := targetConn.(*net.TCPConn); ok {
|
|
||||||
tcpConn.CloseWrite()
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
// Use a large buffer for better performance
|
// Use a large buffer for better performance
|
||||||
buf := make([]byte, 32*1024)
|
buf := make([]byte, 32*1024)
|
||||||
@@ -778,11 +784,7 @@ func (p *SNIProxy) pipe(clientConn, targetConn net.Conn, clientReader io.Reader)
|
|||||||
// Copy data from target to client
|
// Copy data from target to client
|
||||||
go func() {
|
go func() {
|
||||||
defer wg.Done()
|
defer wg.Done()
|
||||||
defer func() {
|
defer closeConns()
|
||||||
if tcpConn, ok := clientConn.(*net.TCPConn); ok {
|
|
||||||
tcpConn.CloseWrite()
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
// Use a large buffer for better performance
|
// Use a large buffer for better performance
|
||||||
buf := make([]byte, 32*1024)
|
buf := make([]byte, 32*1024)
|
||||||
|
|||||||
@@ -464,7 +464,7 @@ func (s *UDPProxyServer) handleWireGuardPacket(packet []byte, remoteAddr *net.UD
|
|||||||
|
|
||||||
_, err = conn.Write(packet)
|
_, err = conn.Write(packet)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Error("Failed to forward handshake initiation: %v", err)
|
logger.Debug("Failed to forward handshake initiation: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -839,7 +839,7 @@ func (s *UDPProxyServer) clearSessionsForIP(ip string) {
|
|||||||
s.wgSessions.Delete(key)
|
s.wgSessions.Delete(key)
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.Info("Cleared %d sessions for WG IP: %s", len(keysToDelete), ip)
|
logger.Debug("Cleared %d sessions for WG IP: %s", len(keysToDelete), ip)
|
||||||
}
|
}
|
||||||
|
|
||||||
// // clearProxyMappingsForWGIP removes all proxy mappings that have destinations pointing to a specific WireGuard IP
|
// // clearProxyMappingsForWGIP removes all proxy mappings that have destinations pointing to a specific WireGuard IP
|
||||||
|
|||||||
Reference in New Issue
Block a user