mirror of
https://github.com/qdm12/gluetun.git
synced 2026-07-03 09:09:50 +02:00
Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 00d944e713 | |||
| beda1764b1 |
@@ -4,12 +4,12 @@ Contributions are [released](https://help.github.com/articles/github-terms-of-se
|
||||
|
||||
## Submitting a pull request
|
||||
|
||||
1. [Fork](https://github.com/passteque/gluetun/fork) and clone the repository
|
||||
1. [Fork](https://github.com/qdm12/gluetun/fork) and clone the repository
|
||||
1. Create a new branch `git checkout -b my-branch-name`
|
||||
1. Modify the code
|
||||
1. Ensure the docker build succeeds `docker build .` (you might need `export DOCKER_BUILDKIT=1`)
|
||||
1. Commit your modifications
|
||||
1. Push to your fork and [submit a pull request](https://github.com/passteque/gluetun/compare)
|
||||
1. Push to your fork and [submit a pull request](https://github.com/qdm12/gluetun/compare)
|
||||
|
||||
## Resources
|
||||
|
||||
|
||||
@@ -56,7 +56,6 @@ body:
|
||||
- IVPN
|
||||
- Mullvad
|
||||
- NordVPN
|
||||
- OVPN
|
||||
- Privado
|
||||
- Private Internet Access
|
||||
- PrivateVPN
|
||||
|
||||
@@ -4,8 +4,8 @@ contact_links:
|
||||
url: https://github.com/qdm12/gluetun-wiki/issues/new/choose
|
||||
about: Please create an issue on the gluetun-wiki repository.
|
||||
- name: Configuration help?
|
||||
url: https://github.com/passteque/gluetun/discussions/new/choose
|
||||
url: https://github.com/qdm12/gluetun/discussions/new/choose
|
||||
about: Please create a Github discussion.
|
||||
- name: Unraid template issue
|
||||
url: https://github.com/passteque/gluetun/discussions/550
|
||||
url: https://github.com/qdm12/gluetun/discussions/550
|
||||
about: Please read the relevant Github discussion.
|
||||
|
||||
@@ -64,8 +64,6 @@
|
||||
color: "cfe8d4"
|
||||
- name: "☁️ NordVPN"
|
||||
color: "cfe8d4"
|
||||
- name: "☁️ OVPN"
|
||||
color: "cfe8d4"
|
||||
- name: "☁️ Perfect Privacy"
|
||||
color: "cfe8d4"
|
||||
- name: "☁️ PIA"
|
||||
@@ -142,8 +140,6 @@
|
||||
color: "ffc7ea"
|
||||
- name: "Category: Shadowsocks 🔁"
|
||||
color: "ffc7ea"
|
||||
- name: "Category: Socks5 proxy 🔁"
|
||||
color: "ffc7ea"
|
||||
- name: "Category: control server ⚙️"
|
||||
color: "ffc7ea"
|
||||
- name: "Category: kernel 🧠"
|
||||
|
||||
@@ -92,7 +92,7 @@ jobs:
|
||||
|
||||
verify-private:
|
||||
if: |
|
||||
github.repository == 'passteque/gluetun' &&
|
||||
github.repository == 'qdm12/gluetun' &&
|
||||
(
|
||||
github.event_name == 'push' ||
|
||||
github.event_name == 'release' ||
|
||||
@@ -163,7 +163,7 @@ jobs:
|
||||
|
||||
publish:
|
||||
if: |
|
||||
github.repository == 'passteque/gluetun' &&
|
||||
github.repository == 'qdm12/gluetun' &&
|
||||
(
|
||||
github.event_name == 'push' ||
|
||||
github.event_name == 'release' ||
|
||||
@@ -175,7 +175,6 @@ jobs:
|
||||
contents: read
|
||||
packages: write
|
||||
runs-on: ubuntu-latest
|
||||
environment: secrets
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
@@ -210,7 +209,7 @@ jobs:
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: qdm12
|
||||
password: ${{ secrets.GHCR_PAT }}
|
||||
password: ${{ github.token }}
|
||||
|
||||
- name: Short commit
|
||||
id: shortcommit
|
||||
|
||||
@@ -17,7 +17,6 @@ jobs:
|
||||
permissions:
|
||||
actions: read
|
||||
contents: read
|
||||
environment: secrets
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
@@ -39,7 +38,7 @@ jobs:
|
||||
config-file: .github/workflows/configs/mlc-config.json
|
||||
|
||||
- uses: peter-evans/dockerhub-description@v5
|
||||
if: github.repository == 'passteque/gluetun' && github.event_name == 'push'
|
||||
if: github.repository == 'qdm12/gluetun' && github.event_name == 'push'
|
||||
with:
|
||||
username: qmcgaw
|
||||
password: ${{ secrets.DOCKERHUB_PASSWORD }}
|
||||
|
||||
@@ -36,7 +36,7 @@ on:
|
||||
- cron: "11 3 1 */2 *" # Run at 03:11 on the 1st of every 2nd month
|
||||
jobs:
|
||||
update-servers-list:
|
||||
if: github.repository == 'passteque/gluetun'
|
||||
if: github.repository == 'qdm12/gluetun'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
actions: read
|
||||
|
||||
+5
-12
@@ -72,9 +72,9 @@ LABEL \
|
||||
org.opencontainers.image.created=$CREATED \
|
||||
org.opencontainers.image.version=$VERSION \
|
||||
org.opencontainers.image.revision=$COMMIT \
|
||||
org.opencontainers.image.url="https://github.com/passteque/gluetun" \
|
||||
org.opencontainers.image.documentation="https://github.com/passteque/gluetun" \
|
||||
org.opencontainers.image.source="https://github.com/passteque/gluetun" \
|
||||
org.opencontainers.image.url="https://github.com/qdm12/gluetun" \
|
||||
org.opencontainers.image.documentation="https://github.com/qdm12/gluetun" \
|
||||
org.opencontainers.image.source="https://github.com/qdm12/gluetun" \
|
||||
org.opencontainers.image.title="VPN swiss-knife like client for multiple VPN providers" \
|
||||
org.opencontainers.image.description="VPN swiss-knife like client to tunnel to multiple VPN servers using OpenVPN, IPtables, DNS over TLS, Shadowsocks, an HTTP proxy and Alpine Linux"
|
||||
ENV VPN_SERVICE_PROVIDER=pia \
|
||||
@@ -186,14 +186,12 @@ ENV VPN_SERVICE_PROVIDER=pia \
|
||||
# # ProtonVPN only:
|
||||
SECURE_CORE_ONLY= \
|
||||
TOR_ONLY= \
|
||||
# # Surfshark and ovpn only:
|
||||
# # Surfshark only:
|
||||
MULTIHOP_ONLY= \
|
||||
# # VPN Secure only:
|
||||
PREMIUM_ONLY= \
|
||||
# # PIA and ProtonVPN only:
|
||||
PORT_FORWARD_ONLY= \
|
||||
# # Ovpn only:
|
||||
SERVER_DEDICATED=no \
|
||||
# Firewall
|
||||
FIREWALL_ENABLED_DISABLING_IT_SHOOTS_YOU_IN_YOUR_FOOT=on \
|
||||
FIREWALL_VPN_INPUT_PORTS= \
|
||||
@@ -242,11 +240,6 @@ ENV VPN_SERVICE_PROVIDER=pia \
|
||||
SHADOWSOCKS_PASSWORD= \
|
||||
SHADOWSOCKS_PASSWORD_SECRETFILE=/run/secrets/shadowsocks_password \
|
||||
SHADOWSOCKS_CIPHER=chacha20-ietf-poly1305 \
|
||||
# Socks5
|
||||
SOCKS5_ENABLED=off \
|
||||
SOCKS5_LISTENING_ADDRESS=":1080" \
|
||||
SOCKS5_USER= \
|
||||
SOCKS5_PASSWORD= \
|
||||
# Control server
|
||||
HTTP_CONTROL_SERVER_LOG=on \
|
||||
HTTP_CONTROL_SERVER_ADDRESS=":8000" \
|
||||
@@ -278,7 +271,7 @@ ENV VPN_SERVICE_PROVIDER=pia \
|
||||
PUID=1000 \
|
||||
PGID=1000
|
||||
ENTRYPOINT ["/gluetun-entrypoint"]
|
||||
EXPOSE 8000/tcp 8888/tcp 8388/tcp 8388/udp 1080/tcp
|
||||
EXPOSE 8000/tcp 8888/tcp 8388/tcp 8388/udp
|
||||
HEALTHCHECK --interval=5s --timeout=5s --start-period=10s --retries=3 CMD /gluetun-entrypoint healthcheck
|
||||
ARG TARGETPLATFORM
|
||||
RUN apk add --no-cache --update -l wget && \
|
||||
|
||||
@@ -6,9 +6,9 @@ Lightweight swiss-army-knife-like VPN client to multiple VPN service providers
|
||||
|
||||
🗯️ this repository will be migrated to [github.com/passteque/gluetun](https://github.com/passteque/gluetun) on 2026-05-21, which is a Github organization under my sole control, so don't get alarmed if you get redirected in the coming days 😉 Reason being migrating Github sponsors to the Open source collective due to my personal situation, basically annoying paperwork. On the plus side, it will be more transparent and funds donated will only be used for the project. The Docker image names will remain the same.
|
||||
|
||||

|
||||

|
||||
|
||||
[](https://github.com/passteque/gluetun/actions/workflows/ci.yml)
|
||||
[](https://github.com/qdm12/gluetun/actions/workflows/ci.yml)
|
||||
|
||||
[](https://hub.docker.com/r/qmcgaw/gluetun)
|
||||
[](https://hub.docker.com/r/qmcgaw/gluetun)
|
||||
@@ -16,23 +16,23 @@ Lightweight swiss-army-knife-like VPN client to multiple VPN service providers
|
||||
[](https://hub.docker.com/r/qmcgaw/gluetun)
|
||||
[](https://hub.docker.com/r/qmcgaw/gluetun)
|
||||
|
||||

|
||||

|
||||

|
||||
[](https://hub.docker.com/r/qmcgaw/gluetun/tags?page=1&ordering=last_updated)
|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
[](https://hub.docker.com/r/qmcgaw/gluetun/tags)
|
||||
|
||||
[](https://github.com/passteque/gluetun/commits/master)
|
||||
[](https://github.com/passteque/gluetun/graphs/contributors)
|
||||
[](https://github.com/passteque/gluetun/pulls?q=is%3Apr+is%3Aclosed)
|
||||
[](https://github.com/passteque/gluetun/issues)
|
||||
[](https://github.com/passteque/gluetun/issues?q=is%3Aissue+is%3Aclosed)
|
||||
[](https://github.com/qdm12/gluetun/commits/master)
|
||||
[](https://github.com/qdm12/gluetun/graphs/contributors)
|
||||
[](https://github.com/qdm12/gluetun/pulls?q=is%3Apr+is%3Aclosed)
|
||||
[](https://github.com/qdm12/gluetun/issues)
|
||||
[](https://github.com/qdm12/gluetun/issues?q=is%3Aissue+is%3Aclosed)
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
|
||||

|
||||
|
||||
@@ -42,10 +42,10 @@ Lightweight swiss-army-knife-like VPN client to multiple VPN service providers
|
||||
- [Features](#features)
|
||||
- Problem?
|
||||
- Check the Wiki [common errors](https://github.com/qdm12/gluetun-wiki/tree/main/errors) and [faq](https://github.com/qdm12/gluetun-wiki/tree/main/faq)
|
||||
- [Start a discussion](https://github.com/passteque/gluetun/discussions)
|
||||
- [Fix the Unraid template](https://github.com/passteque/gluetun/discussions/550)
|
||||
- [Start a discussion](https://github.com/qdm12/gluetun/discussions)
|
||||
- [Fix the Unraid template](https://github.com/qdm12/gluetun/discussions/550)
|
||||
- Suggestion?
|
||||
- [Create an issue](https://github.com/passteque/gluetun/issues)
|
||||
- [Create an issue](https://github.com/qdm12/gluetun/issues)
|
||||
- Happy?
|
||||
- Sponsor me on [github.com/sponsors/qdm12](https://github.com/sponsors/qdm12)
|
||||
- Donate to [paypal.me/qmcgaw](https://www.paypal.me/qmcgaw)
|
||||
@@ -60,20 +60,19 @@ Lightweight swiss-army-knife-like VPN client to multiple VPN service providers
|
||||
## Features
|
||||
|
||||
- Based on Alpine 3.23 for a small Docker image of 43.1MB
|
||||
- Supports: **AirVPN**, **Cyberghost**, **ExpressVPN**, **FastestVPN**, **Giganews**, **HideMyAss**, **IPVanish**, **IVPN**, **Mullvad** (Wireguard only), **NordVPN**, **Ovpn**, **Perfect Privacy**, **Privado**, **Private Internet Access**, **PrivateVPN**, **ProtonVPN**, **PureVPN**, **SlickVPN**, **Surfshark**, **TorGuard**, **VPNSecure.me**, **VPNUnlimited**, **Vyprvpn**, **Windscribe** servers
|
||||
- Supports: **AirVPN**, **Cyberghost**, **ExpressVPN**, **FastestVPN**, **Giganews**, **HideMyAss**, **IPVanish**, **IVPN**, **Mullvad** (Wireguard only), **NordVPN**, **Perfect Privacy**, **Privado**, **Private Internet Access**, **PrivateVPN**, **ProtonVPN**, **PureVPN**, **SlickVPN**, **Surfshark**, **TorGuard**, **VPNSecure.me**, **VPNUnlimited**, **Vyprvpn**, **Windscribe** servers
|
||||
- Supports OpenVPN for all providers listed
|
||||
- Supports Wireguard both kernelspace and userspace
|
||||
- For **AirVPN**, **FastestVPN**, **Ivpn**, **Mullvad**, **NordVPN**, **Ovpn**, **Perfect privacy**, **ProtonVPN**, **Surfshark** and **Windscribe**
|
||||
- For **AirVPN**, **FastestVPN**, **Ivpn**, **Mullvad**, **NordVPN**, **Perfect privacy**, **ProtonVPN**, **Surfshark** and **Windscribe**
|
||||
- For **Cyberghost**, **Private Internet Access**, **PrivateVPN**, **PureVPN**, **Torguard**, **VPN Unlimited** and **VyprVPN** using [the custom provider](https://github.com/qdm12/gluetun-wiki/blob/main/setup/providers/custom.md)
|
||||
- For custom Wireguard configurations using [the custom provider](https://github.com/qdm12/gluetun-wiki/blob/main/setup/providers/custom.md)
|
||||
- More in progress, see [#134](https://github.com/passteque/gluetun/issues/134)
|
||||
- More in progress, see [#134](https://github.com/qdm12/gluetun/issues/134)
|
||||
- Supports AmneziaWG only with the custom provider for now
|
||||
- DNS over TLS baked in with service provider(s) of your choice
|
||||
- DNS fine blocking of malicious/ads/surveillance hostnames and IP addresses, with live update every 24 hours
|
||||
- Choose the vpn network protocol, `udp` or `tcp`
|
||||
- Built in firewall kill switch to allow traffic only with needed the VPN servers and LAN devices
|
||||
- Built in Shadowsocks proxy server (protocol based on SOCKS5 with an encryption layer, tunnels TCP+UDP)
|
||||
- Built in Socks5 proxy server (tunnels TCP) - partial credits to @angelakis and @adjscent
|
||||
- Built in HTTP proxy (tunnels HTTP and HTTPS through TCP)
|
||||
- [Connect other containers to it](https://github.com/qdm12/gluetun-wiki/blob/main/setup/connect-a-container-to-gluetun.md)
|
||||
- [Connect LAN devices to it](https://github.com/qdm12/gluetun-wiki/blob/main/setup/connect-a-lan-device-to-gluetun.md)
|
||||
@@ -131,8 +130,8 @@ services:
|
||||
|
||||
## Fun graphs
|
||||
|
||||
[](https://www.star-history.com/#passteque/gluetun&type=date&legend=top-left)
|
||||
[](https://www.star-history.com/#qdm12/gluetun&type=date&legend=top-left)
|
||||
|
||||
## License
|
||||
|
||||
[](https://github.com/passteque/gluetun/blob/master/LICENSE)
|
||||
[](https://github.com/qdm12/gluetun/blob/master/LICENSE)
|
||||
|
||||
+1
-16
@@ -41,7 +41,6 @@ import (
|
||||
"github.com/qdm12/gluetun/internal/routing"
|
||||
"github.com/qdm12/gluetun/internal/server"
|
||||
"github.com/qdm12/gluetun/internal/shadowsocks"
|
||||
"github.com/qdm12/gluetun/internal/socks5"
|
||||
"github.com/qdm12/gluetun/internal/storage"
|
||||
updater "github.com/qdm12/gluetun/internal/updater/loop"
|
||||
"github.com/qdm12/gluetun/internal/updater/resolver"
|
||||
@@ -412,18 +411,6 @@ func _main(ctx context.Context, buildInfo models.BuildInformation,
|
||||
return fmt.Errorf("starting public ip loop: %w", err)
|
||||
}
|
||||
|
||||
socks5Loop := socks5.NewLoop(socks5.Settings{
|
||||
Enabled: *allSettings.Socks5.Enabled,
|
||||
Username: *allSettings.Socks5.Username,
|
||||
Password: *allSettings.Socks5.Password,
|
||||
Address: allSettings.Socks5.ListeningAddress,
|
||||
Logger: logger.New(log.SetComponent("socks5")),
|
||||
})
|
||||
socks5RunError, err := socks5Loop.Start(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("starting SOCKS5 server loop: %w", err)
|
||||
}
|
||||
|
||||
healthLogger := logger.New(log.SetComponent("healthcheck"))
|
||||
healthcheckServer := healthcheck.NewServer(allSettings.Health, healthLogger)
|
||||
healthServerHandler, healthServerCtx, healthServerDone := goshutdown.NewGoRoutineHandler(
|
||||
@@ -519,7 +506,7 @@ func _main(ctx context.Context, buildInfo models.BuildInformation,
|
||||
String() string
|
||||
Stop() error
|
||||
}{
|
||||
portForwardLooper, publicIPLooper, socks5Loop,
|
||||
portForwardLooper, publicIPLooper,
|
||||
}
|
||||
for _, stopper := range stoppers {
|
||||
err := stopper.Stop()
|
||||
@@ -531,8 +518,6 @@ func _main(ctx context.Context, buildInfo models.BuildInformation,
|
||||
logger.Errorf("port forwarding loop crashed: %s", err)
|
||||
case err := <-publicIPRunError:
|
||||
logger.Errorf("public IP loop crashed: %s", err)
|
||||
case err := <-socks5RunError:
|
||||
logger.Errorf("SOCKS5 server loop crashed: %s", err)
|
||||
}
|
||||
|
||||
return orderHandler.Shutdown(context.Background())
|
||||
|
||||
@@ -15,8 +15,7 @@ require (
|
||||
github.com/mdlayher/netlink v1.9.0
|
||||
github.com/pelletier/go-toml/v2 v2.2.4
|
||||
github.com/qdm12/dns/v2 v2.0.0-rc9.0.20260421173011-9de8e7fdbe3a
|
||||
github.com/qdm12/gluetun-servers v0.1.1-0.20260522005421-14277e92ce82
|
||||
github.com/qdm12/goservices v0.1.1-0.20251104135713-6bee97bd4978
|
||||
github.com/qdm12/gluetun-servers v0.1.0
|
||||
github.com/qdm12/gosettings v0.4.4
|
||||
github.com/qdm12/goshutdown v0.3.0
|
||||
github.com/qdm12/gosplash v0.2.1-0.20260305164749-b713de4fee6c
|
||||
@@ -28,6 +27,7 @@ require (
|
||||
github.com/ulikunitz/xz v0.5.15
|
||||
github.com/youmark/pkcs8 v0.0.0-20201027041543-1326539a0a0a
|
||||
golang.org/x/exp v0.0.0-20241009180824-f66d83c29e7c
|
||||
golang.org/x/mod v0.33.0
|
||||
golang.org/x/net v0.51.0
|
||||
golang.org/x/sys v0.42.0
|
||||
golang.org/x/text v0.35.0
|
||||
@@ -56,9 +56,9 @@ require (
|
||||
github.com/prometheus/client_model v0.6.1 // indirect
|
||||
github.com/prometheus/common v0.60.1 // indirect
|
||||
github.com/prometheus/procfs v0.15.1 // indirect
|
||||
github.com/qdm12/goservices v0.1.1-0.20251104135713-6bee97bd4978 // indirect
|
||||
github.com/riobard/go-bloom v0.0.0-20200614022211-cdc8013cb5b3 // indirect
|
||||
golang.org/x/crypto v0.48.0 // indirect
|
||||
golang.org/x/mod v0.33.0 // indirect
|
||||
golang.org/x/sync v0.20.0 // indirect
|
||||
golang.org/x/tools v0.42.0 // indirect
|
||||
golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 // indirect
|
||||
|
||||
@@ -76,8 +76,8 @@ github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0leargg
|
||||
github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk=
|
||||
github.com/qdm12/dns/v2 v2.0.0-rc9.0.20260421173011-9de8e7fdbe3a h1:TE157yPQmAbVruH0MWCQzs0vTT/6t96DkoWUXd6PVuc=
|
||||
github.com/qdm12/dns/v2 v2.0.0-rc9.0.20260421173011-9de8e7fdbe3a/go.mod h1:98foWgXJZ+g8gJIuO+fdO+oWpFei5WShMFTeN4Im2lE=
|
||||
github.com/qdm12/gluetun-servers v0.1.1-0.20260522005421-14277e92ce82 h1:tE44IEW7o9yPQaO8HBeoO9RxtTTxqhboIypegrQlVt8=
|
||||
github.com/qdm12/gluetun-servers v0.1.1-0.20260522005421-14277e92ce82/go.mod h1:acttuyHyoFDu6GTbf3kAV+QXeiX8oJeh0MBic67/9z8=
|
||||
github.com/qdm12/gluetun-servers v0.1.0 h1:w9JLghKZwI0Gzpp9p5rNANgEYUUZ1dxdxsG6NKIojaY=
|
||||
github.com/qdm12/gluetun-servers v0.1.0/go.mod h1:acttuyHyoFDu6GTbf3kAV+QXeiX8oJeh0MBic67/9z8=
|
||||
github.com/qdm12/goservices v0.1.1-0.20251104135713-6bee97bd4978 h1:TRGpCU1l0lNwtogEUSs5U+RFceYxkAJUmrGabno7J5c=
|
||||
github.com/qdm12/goservices v0.1.1-0.20251104135713-6bee97bd4978/go.mod h1:D1Po4CRQLYjccnAR2JsVlN1sBMgQrcNLONbvyuzcdTg=
|
||||
github.com/qdm12/gosettings v0.4.4 h1:SM6tOZDf6k8qbjWU8KWyBF4mWIixfsKCfh9DGRLHlj4=
|
||||
|
||||
@@ -70,7 +70,7 @@ func (o OpenVPNSelection) validate(vpnProvider string) (err error) {
|
||||
switch vpnProvider {
|
||||
// no restriction on port
|
||||
case providers.Custom, providers.Cyberghost, providers.HideMyAss,
|
||||
providers.Ovpn, providers.Privatevpn, providers.Torguard:
|
||||
providers.Privatevpn, providers.Torguard:
|
||||
// no custom port allowed
|
||||
case providers.Expressvpn, providers.Fastestvpn,
|
||||
providers.Giganews, providers.Ipvanish,
|
||||
|
||||
@@ -49,7 +49,6 @@ func (p *Provider) validate(vpnType string, filterChoicesGetter FilterChoicesGet
|
||||
providers.Ivpn,
|
||||
providers.Mullvad,
|
||||
providers.Nordvpn,
|
||||
providers.Ovpn,
|
||||
providers.Protonvpn,
|
||||
providers.Surfshark,
|
||||
providers.Windscribe,
|
||||
|
||||
@@ -63,9 +63,6 @@ type ServerSelection struct {
|
||||
// TorOnly is true if VPN servers without tor should
|
||||
// be filtered. This is used with ProtonVPN.
|
||||
TorOnly *bool `json:"tor_only"`
|
||||
// Dedicated is true if dedicated VPN servers should be chosen only.
|
||||
// This is used with OVPN.
|
||||
Dedicated *bool `json:"dedicated"`
|
||||
// OpenVPN contains settings to select OpenVPN servers
|
||||
// and the final connection.
|
||||
OpenVPN OpenVPNSelection `json:"openvpn"`
|
||||
@@ -275,8 +272,6 @@ func validateFeatureFilters(settings ServerSelection, vpnServiceProvider string)
|
||||
return errors.New("secure core only filter is not supported")
|
||||
case *settings.TorOnly && vpnServiceProvider != providers.Protonvpn:
|
||||
return errors.New("tor only filter is not supported")
|
||||
case *settings.Dedicated && vpnServiceProvider != providers.Ovpn:
|
||||
return errors.New("dedicated filter is not supported")
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
@@ -301,7 +296,6 @@ func (ss *ServerSelection) copy() (copied ServerSelection) {
|
||||
TorOnly: gosettings.CopyPointer(ss.TorOnly),
|
||||
PortForwardOnly: gosettings.CopyPointer(ss.PortForwardOnly),
|
||||
MultiHopOnly: gosettings.CopyPointer(ss.MultiHopOnly),
|
||||
Dedicated: gosettings.CopyPointer(ss.Dedicated),
|
||||
OpenVPN: ss.OpenVPN.copy(),
|
||||
Wireguard: ss.Wireguard.copy(),
|
||||
}
|
||||
@@ -325,7 +319,6 @@ func (ss *ServerSelection) overrideWith(other ServerSelection) {
|
||||
ss.TorOnly = gosettings.OverrideWithPointer(ss.TorOnly, other.TorOnly)
|
||||
ss.MultiHopOnly = gosettings.OverrideWithPointer(ss.MultiHopOnly, other.MultiHopOnly)
|
||||
ss.PortForwardOnly = gosettings.OverrideWithPointer(ss.PortForwardOnly, other.PortForwardOnly)
|
||||
ss.Dedicated = gosettings.OverrideWithPointer(ss.Dedicated, other.Dedicated)
|
||||
ss.OpenVPN.overrideWith(other.OpenVPN)
|
||||
ss.Wireguard.overrideWith(other.Wireguard)
|
||||
}
|
||||
@@ -342,7 +335,6 @@ func (ss *ServerSelection) setDefaults(vpnProvider string, portForwardingEnabled
|
||||
defaultPortForwardOnly := portForwardingEnabled &&
|
||||
helpers.IsOneOf(vpnProvider, providers.PrivateInternetAccess, providers.Protonvpn)
|
||||
ss.PortForwardOnly = gosettings.DefaultPointer(ss.PortForwardOnly, defaultPortForwardOnly)
|
||||
ss.Dedicated = gosettings.DefaultPointer(ss.Dedicated, false)
|
||||
ss.OpenVPN.setDefaults(vpnProvider)
|
||||
ss.Wireguard.setDefaults()
|
||||
}
|
||||
@@ -418,10 +410,6 @@ func (ss ServerSelection) toLinesNode() (node *gotree.Node) {
|
||||
node.Appendf("Multi-hop only servers: yes")
|
||||
}
|
||||
|
||||
if *ss.Dedicated {
|
||||
node.Appendf("Dedicated servers: yes")
|
||||
}
|
||||
|
||||
if *ss.PortForwardOnly {
|
||||
node.Appendf("Port forwarding only servers: yes")
|
||||
}
|
||||
@@ -513,12 +501,6 @@ func (ss *ServerSelection) read(r *reader.Reader,
|
||||
return err
|
||||
}
|
||||
|
||||
// Ovpn only
|
||||
ss.Dedicated, err = r.BoolPtr("SERVER_DEDICATED")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = ss.OpenVPN.read(r)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -20,7 +20,6 @@ type Settings struct {
|
||||
HTTPProxy HTTPProxy
|
||||
Log Log
|
||||
PublicIP PublicIP
|
||||
Socks5 Socks5
|
||||
Shadowsocks Shadowsocks
|
||||
Storage Storage
|
||||
System System
|
||||
@@ -50,7 +49,6 @@ func (s *Settings) Validate(filterChoicesGetter FilterChoicesGetter, ipv6Support
|
||||
"http proxy": s.HTTPProxy.validate,
|
||||
"log": s.Log.validate,
|
||||
"public ip check": s.PublicIP.validate,
|
||||
"socks5": s.Socks5.validate,
|
||||
"shadowsocks": s.Shadowsocks.validate,
|
||||
"storage": s.Storage.validate,
|
||||
"system": s.System.validate,
|
||||
@@ -83,7 +81,6 @@ func (s *Settings) copy() (copied Settings) {
|
||||
HTTPProxy: s.HTTPProxy.copy(),
|
||||
Log: s.Log.copy(),
|
||||
PublicIP: s.PublicIP.copy(),
|
||||
Socks5: s.Socks5.copy(),
|
||||
Shadowsocks: s.Shadowsocks.copy(),
|
||||
Storage: s.Storage.copy(),
|
||||
System: s.System.copy(),
|
||||
@@ -107,7 +104,6 @@ func (s *Settings) OverrideWith(other Settings,
|
||||
patchedSettings.HTTPProxy.overrideWith(other.HTTPProxy)
|
||||
patchedSettings.Log.overrideWith(other.Log)
|
||||
patchedSettings.PublicIP.overrideWith(other.PublicIP)
|
||||
patchedSettings.Socks5.overrideWith(other.Socks5)
|
||||
patchedSettings.Shadowsocks.overrideWith(other.Shadowsocks)
|
||||
patchedSettings.Storage.overrideWith(other.Storage)
|
||||
patchedSettings.System.overrideWith(other.System)
|
||||
@@ -135,7 +131,6 @@ func (s *Settings) SetDefaults() {
|
||||
s.Log.setDefaults()
|
||||
s.IPv6.setDefaults()
|
||||
s.PublicIP.setDefaults()
|
||||
s.Socks5.setDefaults()
|
||||
s.Shadowsocks.setDefaults()
|
||||
s.Storage.SetDefaults()
|
||||
s.System.setDefaults()
|
||||
@@ -159,7 +154,6 @@ func (s Settings) toLinesNode() (node *gotree.Node) {
|
||||
node.AppendNode(s.Log.toLinesNode())
|
||||
node.AppendNode(s.IPv6.toLinesNode())
|
||||
node.AppendNode(s.Health.toLinesNode())
|
||||
node.AppendNode(s.Socks5.toLinesNode())
|
||||
node.AppendNode(s.Shadowsocks.toLinesNode())
|
||||
node.AppendNode(s.HTTPProxy.toLinesNode())
|
||||
node.AppendNode(s.ControlServer.toLinesNode())
|
||||
@@ -218,7 +212,6 @@ func (s *Settings) Read(r *reader.Reader, warner Warner) (err error) {
|
||||
"public ip": func(r *reader.Reader) error {
|
||||
return s.PublicIP.read(r, warner)
|
||||
},
|
||||
"socks5": s.Socks5.read,
|
||||
"shadowsocks": s.Shadowsocks.read,
|
||||
"storage": s.Storage.Read,
|
||||
"system": s.System.read,
|
||||
|
||||
@@ -81,8 +81,6 @@ func Test_Settings_String(t *testing.T) {
|
||||
| | ├── 1.1.1.1
|
||||
| | └── 8.8.8.8
|
||||
| └── Restart VPN on healthcheck failure: yes
|
||||
├── SOCKS5 proxy server settings:
|
||||
| └── Enabled: no
|
||||
├── Shadowsocks server settings:
|
||||
| └── Enabled: no
|
||||
├── HTTP proxy settings:
|
||||
|
||||
@@ -1,91 +0,0 @@
|
||||
package settings
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/qdm12/gosettings"
|
||||
"github.com/qdm12/gosettings/reader"
|
||||
"github.com/qdm12/gosettings/validate"
|
||||
"github.com/qdm12/gotree"
|
||||
)
|
||||
|
||||
// Socks5 contains settings to configure the Socks5 proxy server.
|
||||
type Socks5 struct {
|
||||
Enabled *bool
|
||||
ListeningAddress string
|
||||
Username *string
|
||||
Password *string
|
||||
}
|
||||
|
||||
func (s Socks5) validate() (err error) {
|
||||
err = validate.ListeningAddress(s.ListeningAddress, os.Getuid())
|
||||
if err != nil {
|
||||
return fmt.Errorf("server listening address is not valid: %w", err)
|
||||
}
|
||||
|
||||
switch {
|
||||
case *s.Username != "" && *s.Password == "":
|
||||
return errors.New("password must be set if username is set")
|
||||
case *s.Username == "" && *s.Password != "":
|
||||
return errors.New("username must be set if password is set")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Socks5) copy() (copied Socks5) {
|
||||
return Socks5{
|
||||
Enabled: gosettings.CopyPointer(s.Enabled),
|
||||
ListeningAddress: s.ListeningAddress,
|
||||
Username: gosettings.CopyPointer(s.Username),
|
||||
Password: gosettings.CopyPointer(s.Password),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Socks5) overrideWith(other Socks5) {
|
||||
s.Enabled = gosettings.OverrideWithPointer(s.Enabled, other.Enabled)
|
||||
s.ListeningAddress = gosettings.OverrideWithComparable(s.ListeningAddress, other.ListeningAddress)
|
||||
s.Username = gosettings.OverrideWithPointer(s.Username, other.Username)
|
||||
s.Password = gosettings.OverrideWithPointer(s.Password, other.Password)
|
||||
}
|
||||
|
||||
func (s *Socks5) setDefaults() {
|
||||
s.Enabled = gosettings.DefaultPointer(s.Enabled, false)
|
||||
s.ListeningAddress = gosettings.DefaultComparable(s.ListeningAddress, ":1080")
|
||||
s.Username = gosettings.DefaultPointer(s.Username, "")
|
||||
s.Password = gosettings.DefaultPointer(s.Password, "")
|
||||
}
|
||||
|
||||
func (s Socks5) String() string {
|
||||
return s.toLinesNode().String()
|
||||
}
|
||||
|
||||
func (s Socks5) toLinesNode() (node *gotree.Node) {
|
||||
node = gotree.New("SOCKS5 proxy server settings:")
|
||||
node.Appendf("Enabled: %s", gosettings.BoolToYesNo(s.Enabled))
|
||||
if !*s.Enabled {
|
||||
return node
|
||||
}
|
||||
|
||||
node.Appendf("Listening address: %s", s.ListeningAddress)
|
||||
if *s.Username != "" || *s.Password != "" {
|
||||
node.Appendf("Username: %s", *s.Username)
|
||||
node.Appendf("Password: %s", gosettings.ObfuscateKey(*s.Password))
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
func (s *Socks5) read(r *reader.Reader) (err error) {
|
||||
s.Enabled, err = r.BoolPtr("SOCKS5_ENABLED")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
s.ListeningAddress = r.String("SOCKS5_LISTENING_ADDRESS")
|
||||
s.Username = r.Get("SOCKS5_USER", reader.ForceLowercase(false))
|
||||
s.Password = r.Get("SOCKS5_PASSWORD", reader.ForceLowercase(false))
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
"fmt"
|
||||
"net/netip"
|
||||
|
||||
"github.com/qdm12/gluetun/internal/configuration/settings/helpers"
|
||||
"github.com/qdm12/gluetun/internal/constants/providers"
|
||||
"github.com/qdm12/gosettings"
|
||||
"github.com/qdm12/gosettings/reader"
|
||||
@@ -23,7 +22,7 @@ type WireguardSelection struct {
|
||||
// It can never be the zero value in the internal state.
|
||||
EndpointIP netip.Addr `json:"endpoint_ip"`
|
||||
// EndpointPort is a the server port to use for the VPN server.
|
||||
// It is optional for VPN providers IVPN, Mullvad, Ovpn, Surfshark
|
||||
// It is optional for VPN providers IVPN, Mullvad, Surfshark
|
||||
// and Windscribe, and compulsory for the others.
|
||||
// When optional, it can be set to 0 to indicate not use
|
||||
// a custom endpoint port. It cannot be nil in the internal
|
||||
@@ -41,9 +40,8 @@ func (w WireguardSelection) validate(vpnProvider string) (err error) {
|
||||
// Validate EndpointIP
|
||||
switch vpnProvider {
|
||||
case providers.Airvpn, providers.Fastestvpn, providers.Ivpn,
|
||||
providers.Mullvad, providers.Nordvpn, providers.Ovpn,
|
||||
providers.Protonvpn, providers.Surfshark,
|
||||
providers.Windscribe:
|
||||
providers.Mullvad, providers.Nordvpn, providers.Protonvpn,
|
||||
providers.Surfshark, providers.Windscribe:
|
||||
// endpoint IP addresses are baked in
|
||||
case providers.Custom:
|
||||
if !w.EndpointIP.IsValid() || w.EndpointIP.IsUnspecified() {
|
||||
@@ -65,16 +63,12 @@ func (w WireguardSelection) validate(vpnProvider string) (err error) {
|
||||
if *w.EndpointPort != 0 {
|
||||
return errors.New("endpoint port is set")
|
||||
}
|
||||
case providers.Airvpn, providers.Ivpn, providers.Mullvad,
|
||||
providers.Ovpn, providers.Windscribe:
|
||||
case providers.Airvpn, providers.Ivpn, providers.Mullvad, providers.Windscribe:
|
||||
// EndpointPort is optional and can be 0
|
||||
if *w.EndpointPort == 0 {
|
||||
break // no custom endpoint port set
|
||||
}
|
||||
if helpers.IsOneOf(vpnProvider,
|
||||
providers.Mullvad,
|
||||
providers.Ovpn,
|
||||
) {
|
||||
if vpnProvider == providers.Mullvad {
|
||||
break // no restriction on custom endpoint port value
|
||||
}
|
||||
var allowed []uint16
|
||||
@@ -98,7 +92,7 @@ func (w WireguardSelection) validate(vpnProvider string) (err error) {
|
||||
// Validate PublicKey
|
||||
switch vpnProvider {
|
||||
case providers.Fastestvpn, providers.Ivpn, providers.Mullvad,
|
||||
providers.Ovpn, providers.Surfshark, providers.Windscribe:
|
||||
providers.Surfshark, providers.Windscribe:
|
||||
// public keys are baked in
|
||||
case providers.Custom:
|
||||
if w.PublicKey == "" {
|
||||
|
||||
@@ -15,7 +15,6 @@ const (
|
||||
Ivpn = "ivpn"
|
||||
Mullvad = "mullvad"
|
||||
Nordvpn = "nordvpn"
|
||||
Ovpn = "ovpn"
|
||||
Perfectprivacy = "perfect privacy"
|
||||
Privado = "privado"
|
||||
PrivateInternetAccess = "private internet access"
|
||||
@@ -44,7 +43,6 @@ func All() []string {
|
||||
Ivpn,
|
||||
Mullvad,
|
||||
Nordvpn,
|
||||
Ovpn,
|
||||
Perfectprivacy,
|
||||
Privado,
|
||||
PrivateInternetAccess,
|
||||
|
||||
@@ -34,11 +34,8 @@ type Server struct {
|
||||
SecureCore bool `json:"secure_core,omitempty"`
|
||||
Tor bool `json:"tor,omitempty"`
|
||||
PortForward bool `json:"port_forward,omitempty"`
|
||||
Dedicated bool `json:"dedicated,omitempty"`
|
||||
Keep bool `json:"keep,omitempty"`
|
||||
IPs []netip.Addr `json:"ips,omitempty"`
|
||||
PortsTCP []uint16 `json:"ports_tcp,omitempty"`
|
||||
PortsUDP []uint16 `json:"ports_udp,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Server) HasMinimumInformation() (err error) {
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
package ovpn
|
||||
|
||||
import (
|
||||
"github.com/qdm12/gluetun/internal/configuration/settings"
|
||||
"github.com/qdm12/gluetun/internal/models"
|
||||
"github.com/qdm12/gluetun/internal/provider/utils"
|
||||
)
|
||||
|
||||
func (p *Provider) GetConnection(selection settings.ServerSelection, ipv6Supported bool) (
|
||||
connection models.Connection, err error,
|
||||
) {
|
||||
defaults := utils.NewConnectionDefaults(443, 1194, 9929) //nolint:mnd
|
||||
return utils.GetConnection(p.Name(),
|
||||
p.storage, selection, defaults, ipv6Supported, p.connPicker)
|
||||
}
|
||||
@@ -1,126 +0,0 @@
|
||||
package ovpn
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"testing"
|
||||
|
||||
"github.com/golang/mock/gomock"
|
||||
"github.com/qdm12/gluetun/internal/configuration/settings"
|
||||
"github.com/qdm12/gluetun/internal/constants"
|
||||
"github.com/qdm12/gluetun/internal/constants/providers"
|
||||
"github.com/qdm12/gluetun/internal/constants/vpn"
|
||||
"github.com/qdm12/gluetun/internal/models"
|
||||
"github.com/qdm12/gluetun/internal/provider/common"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func Test_Provider_GetConnection(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
const provider = providers.Ovpn
|
||||
|
||||
errTest := errors.New("test error")
|
||||
|
||||
testCases := map[string]struct {
|
||||
filteredServers []models.Server
|
||||
storageErr error
|
||||
selection settings.ServerSelection
|
||||
ipv6Supported bool
|
||||
connection models.Connection
|
||||
errWrapped error
|
||||
errMessage string
|
||||
}{
|
||||
"error": {
|
||||
storageErr: errTest,
|
||||
errWrapped: errTest,
|
||||
errMessage: "filtering servers: test error",
|
||||
},
|
||||
"default_openvpn_tcp_port": {
|
||||
filteredServers: []models.Server{
|
||||
{IPs: []netip.Addr{netip.AddrFrom4([4]byte{1, 1, 1, 1})}},
|
||||
},
|
||||
selection: settings.ServerSelection{
|
||||
OpenVPN: settings.OpenVPNSelection{
|
||||
Protocol: constants.TCP,
|
||||
},
|
||||
}.WithDefaults(provider),
|
||||
connection: models.Connection{
|
||||
Type: vpn.OpenVPN,
|
||||
IP: netip.AddrFrom4([4]byte{1, 1, 1, 1}),
|
||||
Port: 443,
|
||||
Protocol: constants.TCP,
|
||||
},
|
||||
},
|
||||
"default_openvpn_udp_port": {
|
||||
filteredServers: []models.Server{
|
||||
{IPs: []netip.Addr{netip.AddrFrom4([4]byte{1, 1, 1, 1})}},
|
||||
},
|
||||
selection: settings.ServerSelection{
|
||||
OpenVPN: settings.OpenVPNSelection{
|
||||
Protocol: constants.UDP,
|
||||
},
|
||||
}.WithDefaults(provider),
|
||||
connection: models.Connection{
|
||||
Type: vpn.OpenVPN,
|
||||
IP: netip.AddrFrom4([4]byte{1, 1, 1, 1}),
|
||||
Port: 1194,
|
||||
Protocol: constants.UDP,
|
||||
},
|
||||
},
|
||||
"default_wireguard_port": {
|
||||
filteredServers: []models.Server{
|
||||
{IPs: []netip.Addr{netip.AddrFrom4([4]byte{1, 1, 1, 1})}, WgPubKey: "x"},
|
||||
},
|
||||
selection: settings.ServerSelection{
|
||||
VPN: vpn.Wireguard,
|
||||
}.WithDefaults(provider),
|
||||
connection: models.Connection{
|
||||
Type: vpn.Wireguard,
|
||||
IP: netip.AddrFrom4([4]byte{1, 1, 1, 1}),
|
||||
Port: 9929,
|
||||
Protocol: constants.UDP,
|
||||
PubKey: "x",
|
||||
},
|
||||
},
|
||||
"default_multihop_port": {
|
||||
filteredServers: []models.Server{
|
||||
{IPs: []netip.Addr{netip.AddrFrom4([4]byte{1, 1, 1, 1})}, WgPubKey: "x", PortsUDP: []uint16{30044}},
|
||||
},
|
||||
selection: settings.ServerSelection{
|
||||
VPN: vpn.Wireguard,
|
||||
}.WithDefaults(provider),
|
||||
connection: models.Connection{
|
||||
Type: vpn.Wireguard,
|
||||
IP: netip.AddrFrom4([4]byte{1, 1, 1, 1}),
|
||||
Port: 30044,
|
||||
Protocol: constants.UDP,
|
||||
PubKey: "x",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for name, testCase := range testCases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
ctrl := gomock.NewController(t)
|
||||
|
||||
storage := common.NewMockStorage(ctrl)
|
||||
storage.EXPECT().FilterServers(provider, testCase.selection).
|
||||
Return(testCase.filteredServers, testCase.storageErr)
|
||||
|
||||
client := (*http.Client)(nil)
|
||||
provider := New(storage, client)
|
||||
|
||||
connection, err := provider.GetConnection(testCase.selection, testCase.ipv6Supported)
|
||||
|
||||
assert.ErrorIs(t, err, testCase.errWrapped)
|
||||
if testCase.errWrapped != nil {
|
||||
assert.EqualError(t, err, testCase.errMessage)
|
||||
}
|
||||
|
||||
assert.Equal(t, testCase.connection, connection)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
package ovpn
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/qdm12/gluetun/internal/configuration/settings"
|
||||
"github.com/qdm12/gluetun/internal/constants/openvpn"
|
||||
"github.com/qdm12/gluetun/internal/models"
|
||||
"github.com/qdm12/gluetun/internal/provider/utils"
|
||||
)
|
||||
|
||||
func (p *Provider) OpenVPNConfig(connection models.Connection,
|
||||
settings settings.OpenVPN, ipv6Supported bool,
|
||||
) (lines []string) {
|
||||
providerSettings := utils.OpenVPNProviderSettings{
|
||||
AuthUserPass: true,
|
||||
RemoteCertTLS: true,
|
||||
Ciphers: []string{
|
||||
openvpn.AES256gcm,
|
||||
openvpn.AES256cbc,
|
||||
openvpn.AES128gcm,
|
||||
openvpn.Chacha20Poly1305,
|
||||
},
|
||||
CAs: []string{
|
||||
"MIIEfTCCA2WgAwIBAgIJAK2aIWqpLj1/MA0GCSqGSIb3DQEBBQUAMIGFMQswCQYDVQQGEwJTRTESMBAGA1UECBMJU3RvY2tob2xtMRIwEAYDVQQHEwlTdG9ja2hvbG0xHDAaBgNVBAsTE0Zpcm1hIERhdmlkIFdpYmVyZ2gxEzARBgNVBAMTCm92cG4uc2UgY2ExGzAZBgkqhkiG9w0BCQEWDGluZm9Ab3Zwbi5zZTAeFw0xNDA4MTcxODIxMjlaFw0zNDA4MTIxODIxMjlaMIGFMQswCQYDVQQGEwJTRTESMBAGA1UECBMJU3RvY2tob2xtMRIwEAYDVQQHEwlTdG9ja2hvbG0xHDAaBgNVBAsTE0Zpcm1hIERhdmlkIFdpYmVyZ2gxEzARBgNVBAMTCm92cG4uc2UgY2ExGzAZBgkqhkiG9w0BCQEWDGluZm9Ab3Zwbi5zZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMR+aP4GTuZwurZuOA2NYzMfqKyZi/TJcLEPlGTB/b4CWA9bTd8f0pHPrDAZsXIEayxxB58BIFNDNiybnbO15JN/QwlsqmA+aZX6mCSkScs/rRwasM6LDo8iGx+KmYEqAgzziONGbCMnlO+OaarXte7LhZ9X6Z/bryu4xq/i1v3raak13kXsrogtu4iDzxqJE/QhbNOi0yhCdlm5RYQjmlKGdPB9pNTgcakVI4HcngRYMzBlrGin0YkvWCdpx5FrDNeld7BSWrJMNYyvd+buaid0Fu1T9/P/Srj/8AiabKoaDyiGFbZdTnGfK+04lWRvwAmvazpqbUt5Omw634jJDuMCAwEAAaOB7TCB6jAdBgNVHQ4EFgQUEvJcHHcTiDtu7bAyZw+xaqg+xdIwgboGA1UdIwSBsjCBr4AUEvJcHHcTiDtu7bAyZw+xaqg+xdKhgYukgYgwgYUxCzAJBgNVBAYTAlNFMRIwEAYDVQQIEwlTdG9ja2hvbG0xEjAQBgNVBAcTCVN0b2NraG9sbTEcMBoGA1UECxMTRmlybWEgRGF2aWQgV2liZXJnaDETMBEGA1UEAxMKb3Zwbi5zZSBjYTEbMBkGCSqGSIb3DQEJARYMaW5mb0BvdnBuLnNlggkArZohaqkuPX8wDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUFAAOCAQEAJmID6OyBJbV7ayPPgquojF+FICuDdOfGVKP828cyISxcbVA04VpD0QLYVb0k9pFUx0NbgX2SvRTiFhP7LcyS1HV9s+XLCb2WItPPsrdRTwtqU2n3TlCEzWA3WOcOCtT6JSkv1eelmx1JnP0gYJrDvDvRYBFctwWhtE0bineSQkZwN6980zkknADLAiHpeZSu/AMx7CGTwA6SmoFvpNBmHXDcfe/9ZqbbYfUfyPNe+0JbMrcv1elKi+6wlEkHFaEBphiZwGEbOX1CjUMcQFgW/cIp3n50Eiyx6ktuqimhyb59P4Nw8gqH452tTtE4MM/brA5y0Q0WFBRBojfZIbGWWQ==", //nolint:lll
|
||||
},
|
||||
TLSAuth: "81782767e4d59c4464cc5d1896f1cf6015017d53ac62e2e3b94b889e00b2c69ddc01944fe1c6d895b4d80540502eb71910b8d785c9efa9e3182343532adffe1cfbb7bb6eae39c502da2748edf0fb89b8a20b0a1085cc1f06135037881bc0c4ad8f2c0f4f72d2ab466fb54af3d8264c5fddeb0f21aa0ca41863678f5fc4c44de4ca0926b36dfddc42c6f2fabd1694bdc8215b2d223b9c21dc6734c2c778093187afb8c33403b228b9af68b540c284f6d183bcc88bd41d47bd717996e499ce1cbbfa768a9723c19c58314c4d19cfed82e543ee92e73d38ad26d4fbec231c0f9f3b30773a5c87792e9bc7c34e8d7611002ebedd044e48a0f1f96527bfdcc940aa09", //nolint:lll
|
||||
KeyDirection: "1",
|
||||
}
|
||||
|
||||
if strings.HasSuffix(connection.Hostname, "singapore.ovpn.com") {
|
||||
providerSettings.TLSCrypt = providerSettings.TLSAuth
|
||||
providerSettings.TLSAuth = ""
|
||||
providerSettings.KeyDirection = ""
|
||||
}
|
||||
|
||||
return utils.OpenVPNConfig(providerSettings, connection, settings, ipv6Supported)
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
package ovpn
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/qdm12/gluetun/internal/constants/providers"
|
||||
"github.com/qdm12/gluetun/internal/provider/common"
|
||||
"github.com/qdm12/gluetun/internal/provider/ovpn/updater"
|
||||
"github.com/qdm12/gluetun/internal/provider/utils"
|
||||
)
|
||||
|
||||
type Provider struct {
|
||||
storage common.Storage
|
||||
connPicker *utils.ConnectionPicker
|
||||
common.Fetcher
|
||||
}
|
||||
|
||||
func New(storage common.Storage, client *http.Client) *Provider {
|
||||
return &Provider{
|
||||
storage: storage,
|
||||
connPicker: utils.NewConnectionPicker(),
|
||||
Fetcher: updater.New(client),
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Provider) Name() string {
|
||||
return providers.Ovpn
|
||||
}
|
||||
@@ -1,153 +0,0 @@
|
||||
package updater
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type apiData struct {
|
||||
Success bool `json:"success"`
|
||||
DataCenters []apiDataCenter `json:"datacenters"`
|
||||
}
|
||||
|
||||
type apiDataCenter struct {
|
||||
City string `json:"city"`
|
||||
CountryName string `json:"country_name"`
|
||||
Servers []apiServer `json:"servers"`
|
||||
}
|
||||
|
||||
type apiServer struct {
|
||||
IP netip.Addr `json:"ip"`
|
||||
Ptr string `json:"ptr"` // hostname
|
||||
Online bool `json:"online"`
|
||||
// PublicKey is for the Standard Shared Entry Point
|
||||
PublicKey string `json:"public_key"`
|
||||
// PublicKeyIPv4 is for the Public / Dedicated IP Entry Point
|
||||
PublicKeyIPv4 string `json:"public_key_ipv4"`
|
||||
WireguardPorts []uint16 `json:"wireguard_ports"`
|
||||
MultiHopOpenvpnPort uint16 `json:"multihop_openvpn_port"`
|
||||
MultiHopWireguardPort uint16 `json:"multihop_wireguard_port"`
|
||||
}
|
||||
|
||||
func fetchAPI(ctx context.Context, client *http.Client) (
|
||||
data apiData, err error,
|
||||
) {
|
||||
const url = "https://www.ovpn.com/v2/api/client/entry"
|
||||
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||
if err != nil {
|
||||
return data, err
|
||||
}
|
||||
|
||||
response, err := client.Do(request)
|
||||
if err != nil {
|
||||
return data, err
|
||||
}
|
||||
|
||||
if response.StatusCode != http.StatusOK {
|
||||
_ = response.Body.Close()
|
||||
return data, fmt.Errorf("HTTP response status code is not OK: %d %s",
|
||||
response.StatusCode, response.Status)
|
||||
}
|
||||
|
||||
decoder := json.NewDecoder(response.Body)
|
||||
err = decoder.Decode(&data)
|
||||
if err != nil {
|
||||
_ = response.Body.Close()
|
||||
return data, fmt.Errorf("decoding response body: %w", err)
|
||||
}
|
||||
|
||||
err = response.Body.Close()
|
||||
if err != nil {
|
||||
return data, fmt.Errorf("closing response body: %w", err)
|
||||
}
|
||||
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func (a *apiDataCenter) validate() (err error) {
|
||||
conditionalErrors := []conditionalError{
|
||||
{err: "city is not set", condition: a.City == ""},
|
||||
{err: "country name is not set", condition: a.CountryName == ""},
|
||||
{err: "servers array is not set", condition: len(a.Servers) == 0},
|
||||
}
|
||||
err = collectErrors(conditionalErrors)
|
||||
if err != nil {
|
||||
var dataCenterSetFields []string
|
||||
if a.CountryName != "" {
|
||||
dataCenterSetFields = append(dataCenterSetFields, a.CountryName)
|
||||
}
|
||||
if a.City != "" {
|
||||
dataCenterSetFields = append(dataCenterSetFields, a.City)
|
||||
}
|
||||
if len(dataCenterSetFields) == 0 {
|
||||
return err
|
||||
}
|
||||
return fmt.Errorf("data center %s: %w",
|
||||
strings.Join(dataCenterSetFields, ", "), err)
|
||||
}
|
||||
|
||||
for i, server := range a.Servers {
|
||||
err = server.validate()
|
||||
if err != nil {
|
||||
return fmt.Errorf("datacenter %s, %s: server %d of %d: %w",
|
||||
a.CountryName, a.City, i+1, len(a.Servers), err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *apiServer) validate() (err error) {
|
||||
const defaultWireguardPort = 9929
|
||||
conditionalErrors := []conditionalError{
|
||||
{err: "ip address is not set", condition: !a.IP.IsValid()},
|
||||
{err: "hostname field is not set", condition: a.Ptr == ""},
|
||||
{err: "public key field is not set", condition: a.PublicKey == ""},
|
||||
{err: "public key IPv4 field is not set", condition: a.PublicKeyIPv4 == ""},
|
||||
{err: "wireguard ports array is not set", condition: len(a.WireguardPorts) == 0},
|
||||
{
|
||||
err: "wireguard port is not the default 9929",
|
||||
condition: len(a.WireguardPorts) != 1 || a.WireguardPorts[0] != defaultWireguardPort,
|
||||
},
|
||||
{err: "multihop OpenVPN port is not set", condition: a.MultiHopOpenvpnPort == 0},
|
||||
{err: "multihop WireGuard port is not set", condition: a.MultiHopWireguardPort == 0},
|
||||
}
|
||||
err = collectErrors(conditionalErrors)
|
||||
switch {
|
||||
case err == nil:
|
||||
return nil
|
||||
case a.Ptr != "":
|
||||
return fmt.Errorf("server %s: %w", a.Ptr, err)
|
||||
case a.IP.IsValid():
|
||||
return fmt.Errorf("server %s: %w", a.IP.String(), err)
|
||||
default:
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
type conditionalError struct {
|
||||
err string
|
||||
condition bool
|
||||
}
|
||||
|
||||
func collectErrors(conditionalErrors []conditionalError) (err error) {
|
||||
errs := make([]string, 0, len(conditionalErrors))
|
||||
for _, conditionalError := range conditionalErrors {
|
||||
if !conditionalError.condition {
|
||||
continue
|
||||
}
|
||||
errs = append(errs, conditionalError.err)
|
||||
}
|
||||
|
||||
if len(errs) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
return errors.New(strings.Join(errs, "; "))
|
||||
}
|
||||
@@ -1,118 +0,0 @@
|
||||
package updater
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func Test_fetchAPI(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
testCases := map[string]struct {
|
||||
responseStatus int
|
||||
responseBody io.ReadCloser
|
||||
data apiData
|
||||
err error
|
||||
}{
|
||||
"http response status not ok": {
|
||||
responseStatus: http.StatusNoContent,
|
||||
err: errors.New("HTTP response status code is not OK: 204 No Content"),
|
||||
},
|
||||
"nil body": {
|
||||
responseStatus: http.StatusOK,
|
||||
err: errors.New("decoding response body: EOF"),
|
||||
},
|
||||
"no server": {
|
||||
responseStatus: http.StatusOK,
|
||||
responseBody: io.NopCloser(strings.NewReader(`{}`)),
|
||||
},
|
||||
"success": {
|
||||
responseStatus: http.StatusOK,
|
||||
responseBody: io.NopCloser(strings.NewReader(`{
|
||||
"success": true,
|
||||
"datacenters": [
|
||||
{
|
||||
"slug": "vienna",
|
||||
"city": "Vienna",
|
||||
"country": "AT",
|
||||
"country_name": "Austria",
|
||||
"pools": [
|
||||
"pool-1.prd.at.vienna.ovpn.com"
|
||||
],
|
||||
"ping_address": "37.120.212.227",
|
||||
"servers": [
|
||||
{
|
||||
"ip": "37.120.212.227",
|
||||
"ptr": "vpn44.prd.vienna.ovpn.com",
|
||||
"name": "VPN44 - Vienna",
|
||||
"online": true,
|
||||
"load": 8,
|
||||
"public_key": "r83LIc0Q2F8s3dY9x5y17Yz8wTADJc7giW1t5eSmoXc=",
|
||||
"public_key_ipv4": "wFbSRyjSXBmkjJodlqz7DoYn3WNDPYFUIXyIUS2QU2A=",
|
||||
"wireguard_ports": [
|
||||
9929
|
||||
],
|
||||
"multihop_openvpn_port": 20044,
|
||||
"multihop_wireguard_port": 30044
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}`)),
|
||||
data: apiData{
|
||||
Success: true,
|
||||
DataCenters: []apiDataCenter{
|
||||
{CountryName: "Austria", City: "Vienna", Servers: []apiServer{
|
||||
{
|
||||
IP: netip.MustParseAddr("37.120.212.227"),
|
||||
Ptr: "vpn44.prd.vienna.ovpn.com",
|
||||
Online: true,
|
||||
PublicKey: "r83LIc0Q2F8s3dY9x5y17Yz8wTADJc7giW1t5eSmoXc=",
|
||||
PublicKeyIPv4: "wFbSRyjSXBmkjJodlqz7DoYn3WNDPYFUIXyIUS2QU2A=",
|
||||
WireguardPorts: []uint16{9929},
|
||||
MultiHopOpenvpnPort: 20044,
|
||||
MultiHopWireguardPort: 30044,
|
||||
},
|
||||
}},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for name, testCase := range testCases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
client := &http.Client{
|
||||
Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
assert.Equal(t, http.MethodGet, r.Method)
|
||||
assert.Equal(t, r.URL.String(), "https://www.ovpn.com/v2/api/client/entry")
|
||||
return &http.Response{
|
||||
StatusCode: testCase.responseStatus,
|
||||
Status: http.StatusText(testCase.responseStatus),
|
||||
Body: testCase.responseBody,
|
||||
}, nil
|
||||
}),
|
||||
}
|
||||
|
||||
data, err := fetchAPI(ctx, client)
|
||||
|
||||
assert.Equal(t, testCase.data, data)
|
||||
if testCase.err != nil {
|
||||
require.Error(t, err)
|
||||
assert.Equal(t, testCase.err.Error(), err.Error())
|
||||
} else {
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
package updater
|
||||
|
||||
import "net/http"
|
||||
|
||||
type roundTripFunc func(r *http.Request) (*http.Response, error)
|
||||
|
||||
func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) {
|
||||
return f(r)
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
package updater
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/netip"
|
||||
"sort"
|
||||
|
||||
"github.com/qdm12/gluetun/internal/constants/vpn"
|
||||
"github.com/qdm12/gluetun/internal/models"
|
||||
"github.com/qdm12/gluetun/internal/provider/common"
|
||||
)
|
||||
|
||||
func (u *Updater) FetchServers(ctx context.Context, minServers int) (
|
||||
servers []models.Server, err error,
|
||||
) {
|
||||
data, err := fetchAPI(ctx, u.client)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("fetching API: %w", err)
|
||||
} else if !data.Success {
|
||||
return nil, errors.New("response success field is false")
|
||||
}
|
||||
|
||||
for dataCenterIndex, dataCenter := range data.DataCenters {
|
||||
err = dataCenter.validate()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("validating data center %d of %d: %w",
|
||||
dataCenterIndex+1, len(data.DataCenters), err)
|
||||
}
|
||||
|
||||
for _, apiServer := range dataCenter.Servers {
|
||||
if !apiServer.Online {
|
||||
continue
|
||||
}
|
||||
|
||||
baseServer := models.Server{
|
||||
Country: dataCenter.CountryName,
|
||||
City: dataCenter.City,
|
||||
Hostname: apiServer.Ptr,
|
||||
IPs: []netip.Addr{apiServer.IP},
|
||||
}
|
||||
openVPNServer := baseServer
|
||||
openVPNServer.VPN = vpn.OpenVPN
|
||||
openVPNServer.TCP = true
|
||||
openVPNServer.UDP = true
|
||||
multiHopOpenVPNServer := openVPNServer
|
||||
multiHopOpenVPNServer.MultiHop = true
|
||||
multiHopOpenVPNServer.PortsTCP = []uint16{apiServer.MultiHopOpenvpnPort}
|
||||
multiHopOpenVPNServer.PortsUDP = []uint16{apiServer.MultiHopOpenvpnPort}
|
||||
servers = append(servers, openVPNServer, multiHopOpenVPNServer)
|
||||
|
||||
wireguardServer := baseServer
|
||||
wireguardServer.VPN = vpn.Wireguard
|
||||
wireguardServer.WgPubKey = apiServer.PublicKey
|
||||
multiHopWireguardServer := wireguardServer
|
||||
multiHopWireguardServer.MultiHop = true
|
||||
multiHopWireguardServer.PortsUDP = []uint16{apiServer.MultiHopWireguardPort}
|
||||
dedicatedWireguardServer := wireguardServer
|
||||
dedicatedWireguardServer.WgPubKey = apiServer.PublicKeyIPv4
|
||||
dedicatedWireguardServer.Dedicated = true
|
||||
dedicatedMultiHopWireguardServer := multiHopWireguardServer
|
||||
dedicatedMultiHopWireguardServer.WgPubKey = apiServer.PublicKeyIPv4
|
||||
dedicatedMultiHopWireguardServer.Dedicated = true
|
||||
servers = append(servers,
|
||||
wireguardServer,
|
||||
multiHopWireguardServer,
|
||||
dedicatedWireguardServer,
|
||||
dedicatedMultiHopWireguardServer,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if len(servers) < minServers {
|
||||
return nil, fmt.Errorf("%w: %d and expected at least %d",
|
||||
common.ErrNotEnoughServers, len(servers), minServers)
|
||||
}
|
||||
|
||||
sort.Sort(models.SortableServers(servers))
|
||||
|
||||
return servers, nil
|
||||
}
|
||||
@@ -1,228 +0,0 @@
|
||||
package updater
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/qdm12/gluetun/internal/constants/vpn"
|
||||
"github.com/qdm12/gluetun/internal/models"
|
||||
"github.com/qdm12/gluetun/internal/provider/common"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func Test_Updater_FetchServers(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
testCases := map[string]struct {
|
||||
// Inputs
|
||||
minServers int
|
||||
|
||||
// From API
|
||||
responseStatus int
|
||||
responseBody string
|
||||
|
||||
// Output
|
||||
servers []models.Server
|
||||
errWrapped error
|
||||
errMessage string
|
||||
}{
|
||||
"http_response_error": {
|
||||
responseStatus: http.StatusNoContent,
|
||||
errMessage: "fetching API: HTTP response status code is not OK: 204 No Content",
|
||||
},
|
||||
"success_field_false": {
|
||||
responseStatus: http.StatusOK,
|
||||
responseBody: `{"success": false}`,
|
||||
errMessage: "response success field is false",
|
||||
},
|
||||
"validation_failed": {
|
||||
responseStatus: http.StatusOK,
|
||||
responseBody: `{
|
||||
"success": true,
|
||||
"datacenters": [
|
||||
{
|
||||
"city": "Vienna",
|
||||
"servers": [
|
||||
{}
|
||||
]
|
||||
}
|
||||
]
|
||||
}`,
|
||||
errMessage: "validating data center 1 of 1: data center Vienna: country name is not set",
|
||||
},
|
||||
"not_enough_servers": {
|
||||
minServers: 7,
|
||||
responseStatus: http.StatusOK,
|
||||
responseBody: `{
|
||||
"success": true,
|
||||
"datacenters": [
|
||||
{
|
||||
"city": "Vienna",
|
||||
"country_name": "Austria",
|
||||
"servers": [
|
||||
{
|
||||
"ip": "37.120.212.227",
|
||||
"ptr": "vpn44.prd.vienna.ovpn.com",
|
||||
"online": true,
|
||||
"public_key": "r83LIc0Q2F8s3dY9x5y17Yz8wTADJc7giW1t5eSmoXc=",
|
||||
"public_key_ipv4": "wFbSRyjSXBmkjJodlqz7DoYn3WNDPYFUIXyIUS2QU2A=",
|
||||
"wireguard_ports": [9929],
|
||||
"multihop_openvpn_port": 20044,
|
||||
"multihop_wireguard_port": 30044
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}`,
|
||||
errWrapped: common.ErrNotEnoughServers,
|
||||
// Wireguard + dedicated Wireguard + Wireguard multi-hop +
|
||||
// dedicated Wireguard multi-hop + OpenVPN + OpenVPN multi-hop
|
||||
errMessage: "not enough servers found: 6 and expected at least 7",
|
||||
},
|
||||
"success": {
|
||||
minServers: 4,
|
||||
responseBody: `{
|
||||
"success": true,
|
||||
"datacenters": [
|
||||
{
|
||||
"slug": "vienna",
|
||||
"city": "Vienna",
|
||||
"country": "AT",
|
||||
"country_name": "Austria",
|
||||
"pools": [
|
||||
"pool-1.prd.at.vienna.ovpn.com"
|
||||
],
|
||||
"ping_address": "37.120.212.227",
|
||||
"servers": [
|
||||
{
|
||||
"ip": "37.120.212.227",
|
||||
"ptr": "vpn44.prd.vienna.ovpn.com",
|
||||
"name": "VPN44 - Vienna",
|
||||
"online": true,
|
||||
"load": 8,
|
||||
"public_key": "r83LIc0Q2F8s3dY9x5y17Yz8wTADJc7giW1t5eSmoXc=",
|
||||
"public_key_ipv4": "wFbSRyjSXBmkjJodlqz7DoYn3WNDPYFUIXyIUS2QU2A=",
|
||||
"wireguard_ports": [
|
||||
9929
|
||||
],
|
||||
"multihop_openvpn_port": 20044,
|
||||
"multihop_wireguard_port": 30044
|
||||
},
|
||||
{
|
||||
"ip": "37.120.212.228",
|
||||
"ptr": "vpn45.prd.vienna.ovpn.com",
|
||||
"online": false,
|
||||
"public_key": "r93LIc0Q2F8s3dY9x5y17Yz8wTADJc7giW1t5eSmoXc=",
|
||||
"public_key_ipv4": "wGbSRyjSXBmkjJodlqz7DoYn3WNDPYFUIXyIUS2QU2A=",
|
||||
"wireguard_ports": [9929],
|
||||
"multihop_openvpn_port": 20045,
|
||||
"multihop_wireguard_port": 30045
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}`,
|
||||
responseStatus: http.StatusOK,
|
||||
servers: []models.Server{
|
||||
{
|
||||
Country: "Austria",
|
||||
City: "Vienna",
|
||||
Hostname: "vpn44.prd.vienna.ovpn.com",
|
||||
IPs: []netip.Addr{netip.MustParseAddr("37.120.212.227")},
|
||||
VPN: vpn.OpenVPN,
|
||||
UDP: true,
|
||||
TCP: true,
|
||||
},
|
||||
{
|
||||
Country: "Austria",
|
||||
City: "Vienna",
|
||||
Hostname: "vpn44.prd.vienna.ovpn.com",
|
||||
IPs: []netip.Addr{netip.MustParseAddr("37.120.212.227")},
|
||||
VPN: vpn.OpenVPN,
|
||||
UDP: true,
|
||||
TCP: true,
|
||||
MultiHop: true,
|
||||
PortsTCP: []uint16{20044},
|
||||
PortsUDP: []uint16{20044},
|
||||
},
|
||||
{
|
||||
Country: "Austria",
|
||||
City: "Vienna",
|
||||
Hostname: "vpn44.prd.vienna.ovpn.com",
|
||||
IPs: []netip.Addr{netip.MustParseAddr("37.120.212.227")},
|
||||
VPN: vpn.Wireguard,
|
||||
WgPubKey: "r83LIc0Q2F8s3dY9x5y17Yz8wTADJc7giW1t5eSmoXc=",
|
||||
},
|
||||
{
|
||||
Country: "Austria",
|
||||
City: "Vienna",
|
||||
Hostname: "vpn44.prd.vienna.ovpn.com",
|
||||
IPs: []netip.Addr{netip.MustParseAddr("37.120.212.227")},
|
||||
VPN: vpn.Wireguard,
|
||||
WgPubKey: "r83LIc0Q2F8s3dY9x5y17Yz8wTADJc7giW1t5eSmoXc=",
|
||||
MultiHop: true,
|
||||
PortsUDP: []uint16{30044},
|
||||
},
|
||||
{
|
||||
Country: "Austria",
|
||||
City: "Vienna",
|
||||
Hostname: "vpn44.prd.vienna.ovpn.com",
|
||||
IPs: []netip.Addr{netip.MustParseAddr("37.120.212.227")},
|
||||
VPN: vpn.Wireguard,
|
||||
WgPubKey: "wFbSRyjSXBmkjJodlqz7DoYn3WNDPYFUIXyIUS2QU2A=",
|
||||
Dedicated: true,
|
||||
},
|
||||
{
|
||||
Country: "Austria",
|
||||
City: "Vienna",
|
||||
Hostname: "vpn44.prd.vienna.ovpn.com",
|
||||
IPs: []netip.Addr{netip.MustParseAddr("37.120.212.227")},
|
||||
VPN: vpn.Wireguard,
|
||||
WgPubKey: "wFbSRyjSXBmkjJodlqz7DoYn3WNDPYFUIXyIUS2QU2A=",
|
||||
MultiHop: true,
|
||||
Dedicated: true,
|
||||
PortsUDP: []uint16{30044},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for name, testCase := range testCases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
client := &http.Client{
|
||||
Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
assert.Equal(t, http.MethodGet, r.Method)
|
||||
assert.Equal(t, r.URL.String(), "https://www.ovpn.com/v2/api/client/entry")
|
||||
return &http.Response{
|
||||
StatusCode: testCase.responseStatus,
|
||||
Status: http.StatusText(testCase.responseStatus),
|
||||
Body: io.NopCloser(strings.NewReader(testCase.responseBody)),
|
||||
}, nil
|
||||
}),
|
||||
}
|
||||
|
||||
updater := &Updater{
|
||||
client: client,
|
||||
}
|
||||
|
||||
servers, err := updater.FetchServers(ctx, testCase.minServers)
|
||||
|
||||
assert.Equal(t, testCase.servers, servers)
|
||||
if testCase.errMessage == "" {
|
||||
assert.NoError(t, err)
|
||||
} else {
|
||||
assert.Contains(t, err.Error(), testCase.errMessage)
|
||||
}
|
||||
if testCase.errWrapped != nil {
|
||||
assert.ErrorIs(t, err, testCase.errWrapped)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
package updater
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type Updater struct {
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
func New(client *http.Client) *Updater {
|
||||
return &Updater{
|
||||
client: client,
|
||||
}
|
||||
}
|
||||
@@ -16,22 +16,25 @@ import (
|
||||
"strings"
|
||||
|
||||
srp "github.com/ProtonMail/go-srp"
|
||||
"github.com/qdm12/gluetun/internal/provider/common"
|
||||
)
|
||||
|
||||
// apiClient is a minimal Proton v4 API client which can handle all the
|
||||
// oddities of Proton's authentication flow they want to keep hidden
|
||||
// from the public.
|
||||
type apiClient struct {
|
||||
apiURLBase string
|
||||
httpClient *http.Client
|
||||
appVersion string
|
||||
userAgent string
|
||||
generator *rand.ChaCha8
|
||||
apiURLBase string
|
||||
httpClient *http.Client
|
||||
appVersion string
|
||||
vpnGtkAppVersion string
|
||||
userAgent string
|
||||
generator *rand.ChaCha8
|
||||
warner common.Warner
|
||||
}
|
||||
|
||||
// newAPIClient returns an [apiClient] with sane defaults matching Proton's
|
||||
// insane expectations.
|
||||
func newAPIClient(ctx context.Context, httpClient *http.Client) (client *apiClient, err error) {
|
||||
func newAPIClient(ctx context.Context, httpClient *http.Client, warner common.Warner) (client *apiClient, err error) {
|
||||
var seed [32]byte
|
||||
_, _ = crand.Read(seed[:])
|
||||
generator := rand.NewChaCha8(seed)
|
||||
@@ -46,17 +49,23 @@ func newAPIClient(ctx context.Context, httpClient *http.Client) (client *apiClie
|
||||
}
|
||||
userAgent := userAgents[generator.Uint64()%uint64(len(userAgents))]
|
||||
|
||||
appVersion, err := getMostRecentStableTag(ctx, httpClient)
|
||||
appVersion, err := getMostRecentStableWebAccountTag(ctx, httpClient)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("getting most recent version for proton app: %w", err)
|
||||
return nil, fmt.Errorf("getting most recent version for web-account: %w", err)
|
||||
}
|
||||
vpnGtkAppVersion, err := getMostRecentStableVPNGtkAppTag(ctx, httpClient)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("getting most recent version for linux VPN GTK app: %w", err)
|
||||
}
|
||||
|
||||
return &apiClient{
|
||||
apiURLBase: "https://account.proton.me/api",
|
||||
httpClient: httpClient,
|
||||
appVersion: appVersion,
|
||||
userAgent: userAgent,
|
||||
generator: generator,
|
||||
apiURLBase: "https://account.proton.me/api",
|
||||
httpClient: httpClient,
|
||||
appVersion: appVersion,
|
||||
vpnGtkAppVersion: vpnGtkAppVersion,
|
||||
userAgent: userAgent,
|
||||
generator: generator,
|
||||
warner: warner,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -64,10 +73,10 @@ func newAPIClient(ctx context.Context, httpClient *http.Client) (client *apiClie
|
||||
// to succeed without being blocked by their "security" measures.
|
||||
// See for example [getMostRecentStableTag] on how the app version must
|
||||
// be set to a recent version or they block your request. "SeCuRiTy"...
|
||||
func (c *apiClient) setHeaders(request *http.Request, cookie cookie) {
|
||||
func (c *apiClient) setHeaders(request *http.Request, cookie cookie, appVersion string) {
|
||||
request.Header.Set("Cookie", cookie.String())
|
||||
request.Header.Set("User-Agent", c.userAgent)
|
||||
request.Header.Set("x-pm-appversion", c.appVersion)
|
||||
request.Header.Set("x-pm-appversion", appVersion)
|
||||
request.Header.Set("x-pm-locale", "en_US")
|
||||
request.Header.Set("x-pm-uid", cookie.uid)
|
||||
}
|
||||
@@ -98,7 +107,11 @@ func (c *apiClient) authenticate(ctx context.Context, email, password string,
|
||||
}
|
||||
username, modulusPGPClearSigned, serverEphemeralBase64, saltBase64,
|
||||
srpSessionHex, version, err := c.authInfo(ctx, email, unauthCookie)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, errUsernameEmpty):
|
||||
c.warner.Warn("Username is empty in auth info response, trying with email address instead")
|
||||
username = email
|
||||
case err != nil:
|
||||
return cookie{}, fmt.Errorf("getting auth information: %w", err)
|
||||
}
|
||||
|
||||
@@ -159,7 +172,7 @@ func (c *apiClient) getUnauthSession(ctx context.Context, sessionID string) (
|
||||
unauthCookie := cookie{
|
||||
sessionID: sessionID,
|
||||
}
|
||||
c.setHeaders(request, unauthCookie)
|
||||
c.setHeaders(request, unauthCookie, c.appVersion)
|
||||
|
||||
response, err := c.httpClient.Do(request)
|
||||
if err != nil {
|
||||
@@ -244,7 +257,7 @@ func (c *apiClient) cookieToken(ctx context.Context, sessionID, tokenType, acces
|
||||
uid: uid,
|
||||
sessionID: sessionID,
|
||||
}
|
||||
c.setHeaders(request, unauthCookie)
|
||||
c.setHeaders(request, unauthCookie, c.appVersion)
|
||||
request.Header.Set("Authorization", tokenType+" "+accessToken)
|
||||
|
||||
response, err := c.httpClient.Do(request)
|
||||
@@ -291,6 +304,8 @@ func (c *apiClient) cookieToken(ctx context.Context, sessionID, tokenType, acces
|
||||
return "", errors.New("auth cookie not found")
|
||||
}
|
||||
|
||||
var errUsernameEmpty = errors.New("username is empty in response")
|
||||
|
||||
// authInfo fetches SRP parameters for the account.
|
||||
func (c *apiClient) authInfo(ctx context.Context, email string, unauthCookie cookie) (
|
||||
username, modulusPGPClearSigned, serverEphemeralBase64, saltBase64, srpSessionHex string,
|
||||
@@ -315,7 +330,7 @@ func (c *apiClient) authInfo(ctx context.Context, email string, unauthCookie coo
|
||||
if err != nil {
|
||||
return "", "", "", "", "", 0, fmt.Errorf("creating request: %w", err)
|
||||
}
|
||||
c.setHeaders(request, unauthCookie)
|
||||
c.setHeaders(request, unauthCookie, c.appVersion)
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
response, err := c.httpClient.Do(request)
|
||||
@@ -358,15 +373,17 @@ func (c *apiClient) authInfo(ctx context.Context, email string, unauthCookie coo
|
||||
return "", "", "", "", "", 0, errors.New("salt is empty in response")
|
||||
case info.SRPSession == "":
|
||||
return "", "", "", "", "", 0, errors.New("SRP session is empty in response")
|
||||
case info.Username == "":
|
||||
return "", "", "", "", "", 0, errors.New("username is empty in response")
|
||||
case info.Version == nil:
|
||||
return "", "", "", "", "", 0, errors.New("version is missing in response")
|
||||
case info.Username == "":
|
||||
// Return a sentinel error the caller can handle to try with the email address instead of the username.
|
||||
// Some accounts seem to have no username.
|
||||
err = fmt.Errorf("%w", errUsernameEmpty)
|
||||
}
|
||||
|
||||
version = int(*info.Version) //nolint:gosec
|
||||
return info.Username, info.Modulus, info.ServerEphemeral, info.Salt,
|
||||
info.SRPSession, version, nil
|
||||
info.SRPSession, version, err
|
||||
}
|
||||
|
||||
type cookie struct {
|
||||
@@ -422,7 +439,7 @@ func (c *apiClient) auth(ctx context.Context, unauthCookie cookie,
|
||||
if err != nil {
|
||||
return cookie{}, fmt.Errorf("creating request: %w", err)
|
||||
}
|
||||
c.setHeaders(request, unauthCookie)
|
||||
c.setHeaders(request, unauthCookie, c.appVersion)
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
response, err := c.httpClient.Do(request)
|
||||
@@ -573,7 +590,9 @@ func (c *apiClient) fetchServers(ctx context.Context, cookie cookie) (
|
||||
if err != nil {
|
||||
return data, err
|
||||
}
|
||||
c.setHeaders(request, cookie)
|
||||
// Note we use the vpnGtkAppVersion field given it produces an output of more servers
|
||||
c.setHeaders(request, cookie, c.vpnGtkAppVersion)
|
||||
request.Header.Set("x-pm-appversion", "linux-vpn@4.15.2")
|
||||
|
||||
response, err := c.httpClient.Do(request)
|
||||
if err != nil {
|
||||
|
||||
@@ -20,7 +20,7 @@ func (u *Updater) FetchServers(ctx context.Context, minServers int) (
|
||||
return nil, fmt.Errorf("%w: password is empty", common.ErrCredentialsMissing)
|
||||
}
|
||||
|
||||
apiClient, err := newAPIClient(ctx, u.client)
|
||||
apiClient, err := newAPIClient(ctx, u.client, u.warner)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("creating API client: %w", err)
|
||||
}
|
||||
|
||||
@@ -7,15 +7,18 @@ import (
|
||||
"io"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/mod/semver"
|
||||
)
|
||||
|
||||
// getMostRecentStableTag finds the most recent proton-account stable tag version,
|
||||
// getMostRecentStableWebAccountTag finds the most recent proton-account stable tag version,
|
||||
// in order to use it in the x-pm-appversion http request header. Because if we do
|
||||
// fall behind on versioning, Proton doesn't like it because they like to create
|
||||
// complications where there is no need for it. Hence this function.
|
||||
func getMostRecentStableTag(ctx context.Context, client *http.Client) (version string, err error) {
|
||||
func getMostRecentStableWebAccountTag(ctx context.Context, client *http.Client) (version string, err error) {
|
||||
page := 1
|
||||
regexVersion := regexp.MustCompile(`^proton-account@(\d+\.\d+\.\d+\.\d+)$`)
|
||||
for ctx.Err() == nil {
|
||||
@@ -69,3 +72,45 @@ func getMostRecentStableTag(ctx context.Context, client *http.Client) (version s
|
||||
|
||||
return "", fmt.Errorf("%w (queried %d pages)", context.Canceled, page)
|
||||
}
|
||||
|
||||
// getMostRecentStableVPNGtkAppTag finds the latest proton-vpn-gtk-app semver tag,
|
||||
// in order to use it in the x-pm-appversion http request header ONLY to fetch servers
|
||||
// data. Because if we do fall behind on versioning, Proton doesn't like it because they like
|
||||
// to create complications where there is no need for it. Hence this function.
|
||||
func getMostRecentStableVPNGtkAppTag(ctx context.Context, client *http.Client) (version string, err error) {
|
||||
const url = "https://api.github.com/repos/ProtonVPN/proton-vpn-gtk-app/tags?per_page=30"
|
||||
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("creating request: %w", err)
|
||||
}
|
||||
request.Header.Set("Accept", "application/vnd.github.v3+json")
|
||||
|
||||
response, err := client.Do(request)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return "", fmt.Errorf("HTTP status code not OK: %s", response.Status)
|
||||
}
|
||||
|
||||
decoder := json.NewDecoder(response.Body)
|
||||
var data []struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
err = decoder.Decode(&data)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("decoding JSON response: %w", err)
|
||||
}
|
||||
|
||||
// Sort tags by semver. Invalid tags are placed at the end and we ignore them.
|
||||
// Yes, proton does push invalid semver tag names sometimes. Good job yet again.
|
||||
sort.Slice(data, func(i, j int) bool {
|
||||
return semver.Compare(data[i].Name, data[j].Name) > 0
|
||||
})
|
||||
|
||||
version = "linux-vpn@" + data[0].Name[1:] // remove leading v
|
||||
return version, nil
|
||||
}
|
||||
|
||||
@@ -20,7 +20,6 @@ import (
|
||||
"github.com/qdm12/gluetun/internal/provider/ivpn"
|
||||
"github.com/qdm12/gluetun/internal/provider/mullvad"
|
||||
"github.com/qdm12/gluetun/internal/provider/nordvpn"
|
||||
"github.com/qdm12/gluetun/internal/provider/ovpn"
|
||||
"github.com/qdm12/gluetun/internal/provider/perfectprivacy"
|
||||
"github.com/qdm12/gluetun/internal/provider/privado"
|
||||
"github.com/qdm12/gluetun/internal/provider/privateinternetaccess"
|
||||
@@ -68,7 +67,6 @@ func NewProviders(storage Storage, timeNow func() time.Time,
|
||||
providers.Ivpn: ivpn.New(storage, client, updaterWarner, parallelResolver),
|
||||
providers.Mullvad: mullvad.New(storage, client),
|
||||
providers.Nordvpn: nordvpn.New(storage, client, updaterWarner),
|
||||
providers.Ovpn: ovpn.New(storage, client),
|
||||
providers.Perfectprivacy: perfectprivacy.New(storage, unzipper, updaterWarner),
|
||||
providers.Privado: privado.New(storage, client, updaterWarner),
|
||||
providers.PrivateInternetAccess: privateinternetaccess.New(storage, timeNow, client),
|
||||
|
||||
@@ -52,6 +52,8 @@ func GetConnection(provider string,
|
||||
})
|
||||
|
||||
protocol := getProtocol(selection)
|
||||
port := getPort(selection, defaults.OpenVPNTCPPort,
|
||||
defaults.OpenVPNUDPPort, defaults.WireguardPort)
|
||||
|
||||
connections := make([]models.Connection, 0, len(servers))
|
||||
for _, server := range servers {
|
||||
@@ -67,9 +69,6 @@ func GetConnection(provider string,
|
||||
hostname = server.OvpnX509
|
||||
}
|
||||
|
||||
port := getPort(selection, server, defaults.OpenVPNTCPPort,
|
||||
defaults.OpenVPNUDPPort, defaults.WireguardPort)
|
||||
|
||||
connection := models.Connection{
|
||||
Type: selection.VPN,
|
||||
IP: ip,
|
||||
|
||||
@@ -6,44 +6,29 @@ import (
|
||||
"github.com/qdm12/gluetun/internal/configuration/settings"
|
||||
"github.com/qdm12/gluetun/internal/constants"
|
||||
"github.com/qdm12/gluetun/internal/constants/vpn"
|
||||
"github.com/qdm12/gluetun/internal/models"
|
||||
)
|
||||
|
||||
func getPort(selection settings.ServerSelection, server models.Server,
|
||||
func getPort(selection settings.ServerSelection,
|
||||
defaultOpenVPNTCP, defaultOpenVPNUDP, defaultWireguard uint16,
|
||||
) (port uint16) {
|
||||
switch selection.VPN {
|
||||
case vpn.Wireguard:
|
||||
customPort := *selection.Wireguard.EndpointPort
|
||||
if customPort > 0 {
|
||||
// Note: servers filtering ensures the custom port is within the
|
||||
// server ports defined if any is set.
|
||||
return customPort
|
||||
}
|
||||
|
||||
if len(server.PortsUDP) > 0 {
|
||||
defaultWireguard = server.PortsUDP[0]
|
||||
}
|
||||
checkDefined("Wireguard", defaultWireguard)
|
||||
return defaultWireguard
|
||||
default: // OpenVPN
|
||||
customPort := *selection.OpenVPN.CustomPort
|
||||
if customPort > 0 {
|
||||
// Note: servers filtering ensures the custom port is within the
|
||||
// server ports defined if any is set.
|
||||
return customPort
|
||||
}
|
||||
if selection.OpenVPN.Protocol == constants.TCP {
|
||||
if len(server.PortsTCP) > 0 {
|
||||
defaultOpenVPNTCP = server.PortsTCP[0]
|
||||
}
|
||||
checkDefined("OpenVPN TCP", defaultOpenVPNTCP)
|
||||
return defaultOpenVPNTCP
|
||||
}
|
||||
|
||||
if len(server.PortsUDP) > 0 {
|
||||
defaultOpenVPNUDP = server.PortsUDP[0]
|
||||
}
|
||||
checkDefined("OpenVPN UDP", defaultOpenVPNUDP)
|
||||
return defaultOpenVPNUDP
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
"github.com/qdm12/gluetun/internal/configuration/settings"
|
||||
"github.com/qdm12/gluetun/internal/constants"
|
||||
"github.com/qdm12/gluetun/internal/constants/vpn"
|
||||
"github.com/qdm12/gluetun/internal/models"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
@@ -23,7 +22,6 @@ func Test_GetPort(t *testing.T) {
|
||||
|
||||
testCases := map[string]struct {
|
||||
selection settings.ServerSelection
|
||||
server models.Server
|
||||
defaultOpenVPNTCP uint16
|
||||
defaultOpenVPNUDP uint16
|
||||
defaultWireguard uint16
|
||||
@@ -50,20 +48,6 @@ func Test_GetPort(t *testing.T) {
|
||||
defaultWireguard: defaultWireguard,
|
||||
port: defaultOpenVPNUDP,
|
||||
},
|
||||
"OpenVPN_server_port_udp": {
|
||||
selection: settings.ServerSelection{
|
||||
VPN: vpn.OpenVPN,
|
||||
OpenVPN: settings.OpenVPNSelection{
|
||||
CustomPort: uint16Ptr(0),
|
||||
Protocol: constants.UDP,
|
||||
},
|
||||
},
|
||||
server: models.Server{
|
||||
PortsUDP: []uint16{1234},
|
||||
},
|
||||
defaultOpenVPNUDP: defaultOpenVPNUDP,
|
||||
port: 1234,
|
||||
},
|
||||
"OpenVPN UDP no default port defined": {
|
||||
selection: settings.ServerSelection{
|
||||
VPN: vpn.OpenVPN,
|
||||
@@ -104,20 +88,6 @@ func Test_GetPort(t *testing.T) {
|
||||
},
|
||||
port: 1234,
|
||||
},
|
||||
"OpenVPN_server_port_tcp": {
|
||||
selection: settings.ServerSelection{
|
||||
VPN: vpn.OpenVPN,
|
||||
OpenVPN: settings.OpenVPNSelection{
|
||||
CustomPort: uint16Ptr(0),
|
||||
Protocol: constants.TCP,
|
||||
},
|
||||
},
|
||||
server: models.Server{
|
||||
PortsTCP: []uint16{1234},
|
||||
},
|
||||
defaultOpenVPNTCP: defaultOpenVPNTCP,
|
||||
port: 1234,
|
||||
},
|
||||
"Wireguard": {
|
||||
selection: settings.ServerSelection{
|
||||
VPN: vpn.Wireguard,
|
||||
@@ -135,19 +105,6 @@ func Test_GetPort(t *testing.T) {
|
||||
defaultWireguard: defaultWireguard,
|
||||
port: 1234,
|
||||
},
|
||||
"Wireguard_server_port": {
|
||||
selection: settings.ServerSelection{
|
||||
VPN: vpn.Wireguard,
|
||||
Wireguard: settings.WireguardSelection{
|
||||
EndpointPort: uint16Ptr(0),
|
||||
},
|
||||
},
|
||||
server: models.Server{
|
||||
PortsUDP: []uint16{1234},
|
||||
},
|
||||
defaultWireguard: defaultWireguard,
|
||||
port: 1234,
|
||||
},
|
||||
"Wireguard no default port defined": {
|
||||
selection: settings.ServerSelection{
|
||||
VPN: vpn.Wireguard,
|
||||
@@ -163,7 +120,6 @@ func Test_GetPort(t *testing.T) {
|
||||
if testCase.panics != "" {
|
||||
assert.PanicsWithValue(t, testCase.panics, func() {
|
||||
_ = getPort(testCase.selection,
|
||||
testCase.server,
|
||||
testCase.defaultOpenVPNTCP,
|
||||
testCase.defaultOpenVPNUDP,
|
||||
testCase.defaultWireguard)
|
||||
@@ -172,7 +128,6 @@ func Test_GetPort(t *testing.T) {
|
||||
}
|
||||
|
||||
port := getPort(testCase.selection,
|
||||
testCase.server,
|
||||
testCase.defaultOpenVPNTCP,
|
||||
testCase.defaultOpenVPNUDP,
|
||||
testCase.defaultWireguard)
|
||||
|
||||
@@ -1,86 +0,0 @@
|
||||
package socks5
|
||||
|
||||
import "fmt"
|
||||
|
||||
// See https://datatracker.ietf.org/doc/html/rfc1928#section-3
|
||||
type authMethod byte
|
||||
|
||||
const (
|
||||
authNotRequired authMethod = 0
|
||||
authGssapi authMethod = 1
|
||||
authUsernamePassword authMethod = 2
|
||||
authNotAcceptable authMethod = 255
|
||||
)
|
||||
|
||||
func (a authMethod) String() string {
|
||||
switch a {
|
||||
case authNotRequired:
|
||||
return "no authentication required"
|
||||
case authGssapi:
|
||||
return "GSSAPI"
|
||||
case authUsernamePassword:
|
||||
return "username/password"
|
||||
case authNotAcceptable:
|
||||
return "no acceptable methods"
|
||||
default:
|
||||
return fmt.Sprintf("unknown method (%d)", a)
|
||||
}
|
||||
}
|
||||
|
||||
// Subnegotiation version
|
||||
// See https://datatracker.ietf.org/doc/html/rfc1929#section-2
|
||||
const (
|
||||
authUsernamePasswordSubNegotiation1 byte = 1
|
||||
)
|
||||
|
||||
// SOCKS versions.
|
||||
const (
|
||||
socks5Version byte = 5
|
||||
)
|
||||
|
||||
// See https://datatracker.ietf.org/doc/html/rfc1928#section-4
|
||||
type cmdType byte
|
||||
|
||||
const (
|
||||
connect cmdType = 1
|
||||
bind cmdType = 2
|
||||
udpAssociate cmdType = 3
|
||||
)
|
||||
|
||||
func (c cmdType) String() string {
|
||||
switch c {
|
||||
case connect:
|
||||
return "connect"
|
||||
case bind:
|
||||
return "bind"
|
||||
case udpAssociate:
|
||||
return "UDP associate"
|
||||
default:
|
||||
return fmt.Sprintf("unknown command (%d)", c)
|
||||
}
|
||||
}
|
||||
|
||||
// See https://datatracker.ietf.org/doc/html/rfc1928#section-4 and
|
||||
// https://datatracker.ietf.org/doc/html/rfc1928#section-5
|
||||
type addrType byte
|
||||
|
||||
const (
|
||||
ipv4 addrType = 1
|
||||
domainName addrType = 3
|
||||
ipv6 addrType = 4
|
||||
)
|
||||
|
||||
// See https://datatracker.ietf.org/doc/html/rfc1928#section-6
|
||||
type replyCode byte
|
||||
|
||||
const (
|
||||
succeeded replyCode = iota
|
||||
generalServerFailure
|
||||
connectionNotAllowedByRuleset
|
||||
networkUnreachable
|
||||
hostUnreachable
|
||||
connectionRefused
|
||||
ttlExpired
|
||||
commandNotSupported
|
||||
addressTypeNotSupported
|
||||
)
|
||||
@@ -1,6 +0,0 @@
|
||||
package socks5
|
||||
|
||||
type Logger interface {
|
||||
Infof(format string, a ...interface{})
|
||||
Warnf(format string, a ...interface{})
|
||||
}
|
||||
@@ -1,106 +0,0 @@
|
||||
package socks5
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/qdm12/goservices"
|
||||
)
|
||||
|
||||
type Loop struct {
|
||||
settings Settings
|
||||
|
||||
mutex sync.Mutex
|
||||
runCancel context.CancelFunc
|
||||
runDone <-chan error
|
||||
}
|
||||
|
||||
func NewLoop(settings Settings) *Loop {
|
||||
return &Loop{
|
||||
settings: settings,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *Loop) String() string {
|
||||
return "SOCKS5 server loop"
|
||||
}
|
||||
|
||||
func (l *Loop) Start(_ context.Context) (runError <-chan error, err error) {
|
||||
l.mutex.Lock()
|
||||
defer l.mutex.Unlock()
|
||||
|
||||
var runCtx context.Context
|
||||
runCtx, l.runCancel = context.WithCancel(context.Background())
|
||||
|
||||
runDone := make(chan error)
|
||||
l.runDone = runDone
|
||||
|
||||
go run(runCtx, runDone, l.settings)
|
||||
|
||||
return nil, nil //nolint:nilnil
|
||||
}
|
||||
|
||||
func run(ctx context.Context, done chan<- error, settings Settings) {
|
||||
defer close(done)
|
||||
logger := settings.Logger
|
||||
|
||||
for ctx.Err() == nil {
|
||||
var server goservices.Service
|
||||
if settings.Enabled {
|
||||
server = newServer(settings)
|
||||
} else {
|
||||
server = new(noopService)
|
||||
}
|
||||
|
||||
errorCh, err := server.Start(ctx)
|
||||
if err != nil {
|
||||
logger.Warnf("failed starting SOCKS5 server: %s", err)
|
||||
waitBeforeRetry(ctx)
|
||||
continue
|
||||
}
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
done <- server.Stop()
|
||||
return
|
||||
case err := <-errorCh:
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
logger.Warnf("SOCKS5 server crashed: %s", err)
|
||||
waitBeforeRetry(ctx)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (l *Loop) Stop() (err error) {
|
||||
l.mutex.Lock()
|
||||
defer l.mutex.Unlock()
|
||||
|
||||
l.runCancel()
|
||||
return <-l.runDone
|
||||
}
|
||||
|
||||
func waitBeforeRetry(ctx context.Context) {
|
||||
const retryDelay = 10 * time.Second
|
||||
timer := time.NewTimer(retryDelay)
|
||||
select {
|
||||
case <-timer.C:
|
||||
case <-ctx.Done():
|
||||
}
|
||||
}
|
||||
|
||||
type noopService struct{}
|
||||
|
||||
func (s noopService) Start(_ context.Context) (runErr <-chan error, err error) {
|
||||
return nil, nil //nolint:nilnil
|
||||
}
|
||||
|
||||
func (s noopService) Stop() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s noopService) String() string {
|
||||
return "noop service"
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
package socks5
|
||||
|
||||
//go:generate mockgen -destination=mocks_test.go -package=$GOPACKAGE . Logger
|
||||
@@ -1,68 +0,0 @@
|
||||
// Code generated by MockGen. DO NOT EDIT.
|
||||
// Source: github.com/qdm12/gluetun/internal/socks5 (interfaces: Logger)
|
||||
|
||||
// Package socks5 is a generated GoMock package.
|
||||
package socks5
|
||||
|
||||
import (
|
||||
reflect "reflect"
|
||||
|
||||
gomock "github.com/golang/mock/gomock"
|
||||
)
|
||||
|
||||
// MockLogger is a mock of Logger interface.
|
||||
type MockLogger struct {
|
||||
ctrl *gomock.Controller
|
||||
recorder *MockLoggerMockRecorder
|
||||
}
|
||||
|
||||
// MockLoggerMockRecorder is the mock recorder for MockLogger.
|
||||
type MockLoggerMockRecorder struct {
|
||||
mock *MockLogger
|
||||
}
|
||||
|
||||
// NewMockLogger creates a new mock instance.
|
||||
func NewMockLogger(ctrl *gomock.Controller) *MockLogger {
|
||||
mock := &MockLogger{ctrl: ctrl}
|
||||
mock.recorder = &MockLoggerMockRecorder{mock}
|
||||
return mock
|
||||
}
|
||||
|
||||
// EXPECT returns an object that allows the caller to indicate expected use.
|
||||
func (m *MockLogger) EXPECT() *MockLoggerMockRecorder {
|
||||
return m.recorder
|
||||
}
|
||||
|
||||
// Infof mocks base method.
|
||||
func (m *MockLogger) Infof(arg0 string, arg1 ...interface{}) {
|
||||
m.ctrl.T.Helper()
|
||||
varargs := []interface{}{arg0}
|
||||
for _, a := range arg1 {
|
||||
varargs = append(varargs, a)
|
||||
}
|
||||
m.ctrl.Call(m, "Infof", varargs...)
|
||||
}
|
||||
|
||||
// Infof indicates an expected call of Infof.
|
||||
func (mr *MockLoggerMockRecorder) Infof(arg0 interface{}, arg1 ...interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
varargs := append([]interface{}{arg0}, arg1...)
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Infof", reflect.TypeOf((*MockLogger)(nil).Infof), varargs...)
|
||||
}
|
||||
|
||||
// Warnf mocks base method.
|
||||
func (m *MockLogger) Warnf(arg0 string, arg1 ...interface{}) {
|
||||
m.ctrl.T.Helper()
|
||||
varargs := []interface{}{arg0}
|
||||
for _, a := range arg1 {
|
||||
varargs = append(varargs, a)
|
||||
}
|
||||
m.ctrl.Call(m, "Warnf", varargs...)
|
||||
}
|
||||
|
||||
// Warnf indicates an expected call of Warnf.
|
||||
func (mr *MockLoggerMockRecorder) Warnf(arg0 interface{}, arg1 ...interface{}) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
varargs := append([]interface{}{arg0}, arg1...)
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Warnf", reflect.TypeOf((*MockLogger)(nil).Warnf), varargs...)
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
package socks5
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/netip"
|
||||
)
|
||||
|
||||
// See https://datatracker.ietf.org/doc/html/rfc1928#section-6
|
||||
func (c *socksConn) encodeFailedResponse(writer io.Writer, socksVersion byte, reply replyCode) { //nolint:unparam
|
||||
_, err := writer.Write([]byte{
|
||||
socksVersion,
|
||||
byte(reply),
|
||||
0, // RSV byte
|
||||
// The RFC requires a full response frame even for failures.
|
||||
// Use IPv4 address type with zeroed address and port.
|
||||
byte(ipv4), // ATYP
|
||||
0, 0, 0, 0, // BND.ADDR (zeroed)
|
||||
0, 0, // BND.PORT (zeroed)
|
||||
})
|
||||
if err != nil {
|
||||
c.logger.Warnf("failed writing failed response: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
// See https://datatracker.ietf.org/doc/html/rfc1928#section-6
|
||||
func (c *socksConn) encodeSuccessResponse(writer io.Writer, socksVersion byte,
|
||||
reply replyCode, bindAddrType addrType, bindAddress string,
|
||||
bindPort uint16,
|
||||
) (err error) {
|
||||
bindData, err := encodeBindData(bindAddrType, bindAddress, bindPort)
|
||||
if err != nil {
|
||||
return fmt.Errorf("encoding bind data: %w", err)
|
||||
}
|
||||
|
||||
const initialPacketLength = 3
|
||||
capacity := initialPacketLength + len(bindData)
|
||||
packet := make([]byte, initialPacketLength, capacity)
|
||||
packet[0] = socksVersion
|
||||
packet[1] = byte(reply)
|
||||
packet[2] = 0 // RSV byte
|
||||
packet = append(packet, bindData...)
|
||||
|
||||
_, err = writer.Write(packet)
|
||||
if err != nil {
|
||||
return fmt.Errorf("writing packet: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var (
|
||||
ErrIPVersionUnexpected = errors.New("ip version is unexpected")
|
||||
ErrDomainNameTooLong = errors.New("domain name is too long")
|
||||
)
|
||||
|
||||
func encodeBindData(addrType addrType, address string, port uint16) (
|
||||
data []byte, err error,
|
||||
) {
|
||||
capacity := bindDataLength(addrType, address)
|
||||
data = make([]byte, 0, capacity)
|
||||
|
||||
data = append(data, byte(addrType))
|
||||
switch addrType {
|
||||
case ipv4, ipv6:
|
||||
ip, err := netip.ParseAddr(address)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parsing IP address: %w", err)
|
||||
}
|
||||
|
||||
switch {
|
||||
case addrType == ipv4 && !ip.Is4():
|
||||
return nil, fmt.Errorf("%w: expected IPv4 for %s", ErrIPVersionUnexpected, ip)
|
||||
case addrType == ipv6 && !ip.Is6():
|
||||
return nil, fmt.Errorf("%w: expected IPv6 for %s", ErrIPVersionUnexpected, ip)
|
||||
}
|
||||
data = append(data, ip.AsSlice()...)
|
||||
case domainName:
|
||||
const maxDomainNameLength = 255
|
||||
if len(address) > maxDomainNameLength {
|
||||
return nil, fmt.Errorf("%w: %s", ErrDomainNameTooLong, address)
|
||||
}
|
||||
data = append(data, byte(len(address)))
|
||||
data = append(data, []byte(address)...)
|
||||
default:
|
||||
panic(fmt.Sprintf("unsupported address type %d", addrType))
|
||||
}
|
||||
data = binary.BigEndian.AppendUint16(data, port)
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func bindDataLength(addrType addrType, address string) (maxLength uint) {
|
||||
maxLength++ // address type
|
||||
switch addrType {
|
||||
case ipv4:
|
||||
maxLength += net.IPv4len
|
||||
case domainName:
|
||||
maxLength++ // domain name length
|
||||
maxLength += uint(len([]byte(address)))
|
||||
case ipv6:
|
||||
maxLength += net.IPv6len
|
||||
default:
|
||||
panic("unsupported address type: " + fmt.Sprint(addrType))
|
||||
}
|
||||
maxLength += 2 // port
|
||||
return maxLength
|
||||
}
|
||||
@@ -1,122 +0,0 @@
|
||||
package socks5
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
)
|
||||
|
||||
type server struct {
|
||||
username string
|
||||
password string
|
||||
address string
|
||||
logger Logger
|
||||
|
||||
// internal fields
|
||||
listener net.Listener
|
||||
listening atomic.Bool
|
||||
socksConnCtx context.Context //nolint:containedctx
|
||||
socksConnCancel context.CancelFunc
|
||||
done <-chan struct{}
|
||||
stopping atomic.Bool
|
||||
}
|
||||
|
||||
func newServer(settings Settings) *server {
|
||||
return &server{
|
||||
username: settings.Username,
|
||||
password: settings.Password,
|
||||
address: settings.Address,
|
||||
logger: settings.Logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *server) String() string {
|
||||
return "SOCKS5 server"
|
||||
}
|
||||
|
||||
func (s *server) Start(ctx context.Context) (runErr <-chan error, err error) {
|
||||
s.socksConnCtx, s.socksConnCancel = context.WithCancel(context.Background())
|
||||
config := &net.ListenConfig{}
|
||||
s.listener, err = config.Listen(ctx, "tcp", s.address)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("listening on %s: %w", s.address, err)
|
||||
}
|
||||
s.listening.Store(true)
|
||||
s.logger.Infof("SOCKS5 server listening on %s", s.listener.Addr())
|
||||
|
||||
ready := make(chan struct{})
|
||||
runErrCh := make(chan error)
|
||||
runErr = runErrCh
|
||||
done := make(chan struct{})
|
||||
s.done = done
|
||||
go s.runServer(ready, runErrCh, done)
|
||||
select {
|
||||
case <-ready:
|
||||
case <-ctx.Done():
|
||||
_ = s.Stop()
|
||||
return nil, fmt.Errorf("starting server: %w", ctx.Err())
|
||||
}
|
||||
return runErr, nil
|
||||
}
|
||||
|
||||
func (s *server) runServer(ready chan<- struct{},
|
||||
runErrCh chan<- error, done chan<- struct{},
|
||||
) {
|
||||
close(ready)
|
||||
defer close(done)
|
||||
wg := new(sync.WaitGroup)
|
||||
defer wg.Wait()
|
||||
|
||||
dialer := &net.Dialer{}
|
||||
for {
|
||||
connection, err := s.listener.Accept()
|
||||
if err != nil {
|
||||
if !s.stopping.Load() {
|
||||
_ = s.stop()
|
||||
runErrCh <- fmt.Errorf("accepting connection: %w", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
wg.Add(1)
|
||||
go func(ctx context.Context, connection net.Conn,
|
||||
dialer *net.Dialer, wg *sync.WaitGroup,
|
||||
) {
|
||||
defer wg.Done()
|
||||
socksConn := &socksConn{
|
||||
dialer: dialer,
|
||||
username: s.username,
|
||||
password: s.password,
|
||||
clientConn: connection,
|
||||
logger: s.logger,
|
||||
}
|
||||
err := socksConn.run(ctx)
|
||||
if err != nil {
|
||||
s.logger.Infof("running socks connection: %s", err)
|
||||
}
|
||||
}(s.socksConnCtx, connection, dialer, wg)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *server) Stop() (err error) {
|
||||
s.stopping.Store(true)
|
||||
err = s.stop()
|
||||
<-s.done // wait for run goroutine to finish
|
||||
s.stopping.Store(false)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *server) stop() error {
|
||||
s.listening.Store(false)
|
||||
err := s.listener.Close()
|
||||
s.socksConnCancel() // stop ongoing socks connections
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *server) listeningAddress() net.Addr {
|
||||
if s.listening.Load() {
|
||||
return s.listener.Addr()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
package socks5
|
||||
|
||||
type Settings struct {
|
||||
Enabled bool
|
||||
Username string
|
||||
Password string
|
||||
Address string
|
||||
Logger Logger
|
||||
}
|
||||
@@ -1,290 +0,0 @@
|
||||
package socks5
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/netip"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
errNoMethodIdentifiers = errors.New("no method identifiers")
|
||||
errNoValidMethodIdentifier = errors.New("no valid method identifier")
|
||||
)
|
||||
|
||||
type socksConn struct {
|
||||
// Injected fields
|
||||
dialer *net.Dialer
|
||||
username string
|
||||
password string
|
||||
clientConn net.Conn
|
||||
logger Logger
|
||||
}
|
||||
|
||||
func (c *socksConn) closeClientConn(ctxErr error) {
|
||||
err := c.clientConn.Close()
|
||||
if err != nil && ctxErr == nil {
|
||||
c.logger.Warnf("closing client connection: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *socksConn) run(ctx context.Context) error {
|
||||
// Monitoring context cancellation to close the connection and stop
|
||||
// reading operations on clientConn.
|
||||
done := make(chan struct{})
|
||||
ctxWatcherDone := make(chan struct{})
|
||||
go func() {
|
||||
defer close(ctxWatcherDone)
|
||||
select {
|
||||
case <-done:
|
||||
case <-ctx.Done():
|
||||
// unblock read operations
|
||||
c.closeClientConn(ctx.Err())
|
||||
}
|
||||
}()
|
||||
defer func() {
|
||||
close(done)
|
||||
<-ctxWatcherDone
|
||||
}()
|
||||
|
||||
authMethod := authNotRequired
|
||||
if c.username != "" || c.password != "" {
|
||||
authMethod = authUsernamePassword
|
||||
}
|
||||
|
||||
err := verifyFirstNegotiation(c.clientConn, authMethod)
|
||||
if err != nil {
|
||||
replyMethod := authMethod
|
||||
if errors.Is(err, errNoMethodIdentifiers) || errors.Is(err, errNoValidMethodIdentifier) {
|
||||
replyMethod = authNotAcceptable
|
||||
}
|
||||
_, writeErr := c.clientConn.Write([]byte{socks5Version, byte(replyMethod)})
|
||||
if writeErr != nil {
|
||||
c.logger.Warnf("failed writing first negotiation reply: %s", writeErr)
|
||||
}
|
||||
c.closeClientConn(ctx.Err())
|
||||
return fmt.Errorf("verifying first negotiation: %w", err)
|
||||
}
|
||||
|
||||
_, err = c.clientConn.Write([]byte{socks5Version, byte(authMethod)})
|
||||
if err != nil {
|
||||
c.closeClientConn(ctx.Err())
|
||||
return fmt.Errorf("writing first negotiation reply: %w", err)
|
||||
}
|
||||
|
||||
switch authMethod {
|
||||
case authNotRequired, authNotAcceptable:
|
||||
case authGssapi:
|
||||
panic("not implemented")
|
||||
case authUsernamePassword:
|
||||
// See https://datatracker.ietf.org/doc/html/rfc1929#section-2
|
||||
err = usernamePasswordSubnegotiate(c.clientConn, c.username, c.password)
|
||||
if err != nil {
|
||||
// If the server returns a `failure' (STATUS value other than X'00') status,
|
||||
// it MUST close the connection.
|
||||
c.closeClientConn(ctx.Err())
|
||||
return fmt.Errorf("subnegotiating username and password: %w", err)
|
||||
}
|
||||
default:
|
||||
panic(fmt.Sprintf("unimplemented auth method %d", authMethod))
|
||||
}
|
||||
|
||||
err = c.handleRequest(ctx)
|
||||
c.closeClientConn(ctx.Err())
|
||||
if err != nil {
|
||||
return fmt.Errorf("handling request: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *socksConn) handleRequest(ctx context.Context) error {
|
||||
const socksVersion = socks5Version
|
||||
request, err := decodeRequest(c.clientConn, socksVersion)
|
||||
if err != nil {
|
||||
c.encodeFailedResponse(c.clientConn, socksVersion, generalServerFailure)
|
||||
return err
|
||||
}
|
||||
if request.command != connect {
|
||||
c.encodeFailedResponse(c.clientConn, socksVersion, commandNotSupported)
|
||||
return fmt.Errorf("command %s is not supported", request.command)
|
||||
}
|
||||
|
||||
destinationAddress := net.JoinHostPort(request.destination, fmt.Sprint(request.port))
|
||||
destinationConn, err := c.dialer.DialContext(ctx, "tcp", destinationAddress)
|
||||
if err != nil {
|
||||
c.encodeFailedResponse(c.clientConn, socksVersion, generalServerFailure)
|
||||
return err
|
||||
}
|
||||
defer destinationConn.Close()
|
||||
|
||||
destinationServerAddress := destinationConn.LocalAddr().String()
|
||||
destinationAddr, destinationPortStr, err := net.SplitHostPort(destinationServerAddress)
|
||||
if err != nil {
|
||||
return fmt.Errorf("splitting destination address: %w", err)
|
||||
}
|
||||
destinationPort, err := strconv.ParseUint(destinationPortStr, 10, 16)
|
||||
if err != nil {
|
||||
return fmt.Errorf("port is malformed: %q", destinationPortStr)
|
||||
}
|
||||
|
||||
var bindAddrType addrType
|
||||
if ip := net.ParseIP(destinationAddr); ip != nil {
|
||||
if ip.To4() != nil {
|
||||
bindAddrType = ipv4
|
||||
} else {
|
||||
bindAddrType = ipv6
|
||||
}
|
||||
} else {
|
||||
bindAddrType = domainName
|
||||
}
|
||||
|
||||
err = c.encodeSuccessResponse(c.clientConn, socksVersion, succeeded, bindAddrType,
|
||||
destinationAddr, uint16(destinationPort))
|
||||
if err != nil {
|
||||
c.encodeFailedResponse(c.clientConn, socksVersion, generalServerFailure)
|
||||
return fmt.Errorf("writing successful %s response: %w", request.command, err)
|
||||
}
|
||||
|
||||
const capacity = 2 // if one goroutine fails, we don't want to leak the other one
|
||||
errc := make(chan error, capacity)
|
||||
go func() {
|
||||
_, err := io.Copy(c.clientConn, destinationConn)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("from backend to client: %w", err)
|
||||
}
|
||||
errc <- err
|
||||
}()
|
||||
go func() {
|
||||
_, err := io.Copy(destinationConn, c.clientConn)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("from client to backend: %w", err)
|
||||
}
|
||||
errc <- err
|
||||
}()
|
||||
select {
|
||||
case err := <-errc:
|
||||
return err
|
||||
case <-ctx.Done():
|
||||
_ = destinationConn.Close()
|
||||
_ = c.clientConn.Close()
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// See https://datatracker.ietf.org/doc/html/rfc1928#section-3
|
||||
func verifyFirstNegotiation(reader io.Reader, requiredMethod authMethod) error {
|
||||
const headerLength = 2 // version + nMethods bytes
|
||||
header := make([]byte, headerLength)
|
||||
_, err := io.ReadFull(reader, header)
|
||||
if err != nil {
|
||||
return fmt.Errorf("reading header: %w", err)
|
||||
}
|
||||
|
||||
if header[0] != socks5Version {
|
||||
return fmt.Errorf("version is not supported: %d", header[0])
|
||||
}
|
||||
|
||||
nMethods := header[1]
|
||||
if nMethods == 0 {
|
||||
return fmt.Errorf("%w", errNoMethodIdentifiers)
|
||||
}
|
||||
|
||||
methodIdentifiers := make([]byte, nMethods)
|
||||
_, err = io.ReadFull(reader, methodIdentifiers)
|
||||
if err != nil {
|
||||
return fmt.Errorf("reading method identifiers: %w", err)
|
||||
}
|
||||
for _, methodIdentifier := range methodIdentifiers {
|
||||
if methodIdentifier == byte(requiredMethod) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
return makeNoAcceptableMethodError(requiredMethod, methodIdentifiers)
|
||||
}
|
||||
|
||||
func makeNoAcceptableMethodError(requiredAuthMethod authMethod, methodIdentifiers []byte) error {
|
||||
methodNames := make([]string, len(methodIdentifiers))
|
||||
for i, methodIdentifier := range methodIdentifiers {
|
||||
methodNames[i] = fmt.Sprintf("%q", authMethod(methodIdentifier))
|
||||
}
|
||||
|
||||
return fmt.Errorf("%w: none of %s matches %s",
|
||||
errNoValidMethodIdentifier, strings.Join(methodNames, ", "),
|
||||
requiredAuthMethod)
|
||||
}
|
||||
|
||||
// See https://datatracker.ietf.org/doc/html/rfc1928#section-4
|
||||
type request struct {
|
||||
command cmdType
|
||||
destination string
|
||||
port uint16
|
||||
addressType addrType
|
||||
}
|
||||
|
||||
func decodeRequest(reader io.Reader, expectedVersion byte) (req request, err error) {
|
||||
const headerLength = 4
|
||||
header := [headerLength]byte{}
|
||||
_, err = io.ReadFull(reader, header[:])
|
||||
if err != nil {
|
||||
return request{}, fmt.Errorf("reading header: %w", err)
|
||||
}
|
||||
|
||||
version := header[0]
|
||||
switch {
|
||||
case version != expectedVersion:
|
||||
return request{}, fmt.Errorf("version is not supported: expected %d and got %d",
|
||||
expectedVersion, version)
|
||||
case header[2] != 0:
|
||||
return request{}, fmt.Errorf("reserved header byte must be 0 but got %d", header[2])
|
||||
}
|
||||
|
||||
req.command = cmdType(header[1])
|
||||
// header[2] is RSV byte
|
||||
req.addressType = addrType(header[3])
|
||||
|
||||
switch req.addressType {
|
||||
case ipv4:
|
||||
var ip [4]byte
|
||||
_, err = io.ReadFull(reader, ip[:])
|
||||
if err != nil {
|
||||
return request{}, fmt.Errorf("reading IPv4 address: %w", err)
|
||||
}
|
||||
req.destination = netip.AddrFrom4(ip).String()
|
||||
case ipv6:
|
||||
var ip [16]byte
|
||||
_, err = io.ReadFull(reader, ip[:])
|
||||
if err != nil {
|
||||
return request{}, fmt.Errorf("reading IPv6 address: %w", err)
|
||||
}
|
||||
req.destination = netip.AddrFrom16(ip).String()
|
||||
case domainName:
|
||||
var header [1]byte
|
||||
_, err = io.ReadFull(reader, header[:])
|
||||
if err != nil {
|
||||
return request{}, fmt.Errorf("reading domain name header: %w", err)
|
||||
}
|
||||
domainName := make([]byte, header[0])
|
||||
_, err = io.ReadFull(reader, domainName)
|
||||
if err != nil {
|
||||
return request{}, fmt.Errorf("reading domain name bytes: %w", err)
|
||||
}
|
||||
req.destination = string(domainName)
|
||||
default:
|
||||
return request{}, fmt.Errorf("address type is not supported: %d", req.addressType)
|
||||
}
|
||||
|
||||
var portBytes [2]byte
|
||||
_, err = io.ReadFull(reader, portBytes[:])
|
||||
if err != nil {
|
||||
return request{}, fmt.Errorf("reading port: %w", err)
|
||||
}
|
||||
req.port = binary.BigEndian.Uint16(portBytes[:])
|
||||
|
||||
return req, nil
|
||||
}
|
||||
@@ -1,622 +0,0 @@
|
||||
package socks5
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"io"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/golang/mock/gomock"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type noopLogger struct{}
|
||||
|
||||
func (noopLogger) Infof(string, ...any) {}
|
||||
func (noopLogger) Warnf(string, ...any) {}
|
||||
|
||||
func TestServerProxy(t *testing.T) {
|
||||
t.Parallel()
|
||||
testCases := map[string]struct {
|
||||
username string
|
||||
password string
|
||||
}{
|
||||
"no_auth": {},
|
||||
"with_auth": {
|
||||
username: "user",
|
||||
password: "pass",
|
||||
},
|
||||
}
|
||||
|
||||
for name, testCase := range testCases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
// Backend TCP server: accepts one connection for the proxy to forward to.
|
||||
backendListener, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp", "127.0.0.1:0")
|
||||
require.NoError(t, err)
|
||||
|
||||
backendConnCh := make(chan net.Conn)
|
||||
go func() {
|
||||
conn, err := backendListener.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
backendConnCh <- conn
|
||||
}()
|
||||
|
||||
server := newServer(Settings{
|
||||
Username: testCase.username,
|
||||
Password: testCase.password,
|
||||
Address: "127.0.0.1:0",
|
||||
Logger: noopLogger{},
|
||||
})
|
||||
_, err = server.Start(t.Context())
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() {
|
||||
_ = server.Stop()
|
||||
_ = backendListener.Close()
|
||||
})
|
||||
|
||||
// Dial through the SOCKS5 proxy to the backend.
|
||||
// By the time dialSOCKS5 returns, the SOCKS5 server has already
|
||||
// established the TCP connection to the backend, so backendConnCh
|
||||
// is guaranteed to be populated.
|
||||
clientConn := dialSOCKS5(t, server.listeningAddress().String(),
|
||||
backendListener.Addr().String(), testCase.username, testCase.password)
|
||||
defer clientConn.Close()
|
||||
|
||||
backendConn := <-backendConnCh
|
||||
defer backendConn.Close()
|
||||
|
||||
// Verify client → backend direction.
|
||||
clientMessage := []byte("hello from client")
|
||||
_, err = clientConn.Write(clientMessage)
|
||||
require.NoError(t, err)
|
||||
|
||||
received := make([]byte, len(clientMessage))
|
||||
_, err = io.ReadFull(backendConn, received)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, clientMessage, received)
|
||||
|
||||
// Verify backend → client direction.
|
||||
backendMessage := []byte("hello from backend")
|
||||
_, err = backendConn.Write(backendMessage)
|
||||
require.NoError(t, err)
|
||||
|
||||
receivedByClient := make([]byte, len(backendMessage))
|
||||
_, err = io.ReadFull(clientConn, receivedByClient)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, backendMessage, receivedByClient)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// dialSOCKS5 performs the full SOCKS5 handshake (with optional username/password
|
||||
// subnegotiation) and returns a connected net.Conn ready for data exchange.
|
||||
func dialSOCKS5(t *testing.T, proxyAddr, targetAddr, username, password string) net.Conn {
|
||||
t.Helper()
|
||||
|
||||
host, portStr, err := net.SplitHostPort(targetAddr)
|
||||
require.NoError(t, err)
|
||||
targetPort, err := strconv.Atoi(portStr)
|
||||
require.NoError(t, err)
|
||||
|
||||
conn, err := (&net.Dialer{}).DialContext(t.Context(), "tcp", proxyAddr)
|
||||
require.NoError(t, err)
|
||||
|
||||
var method authMethod
|
||||
if username != "" || password != "" {
|
||||
method = authUsernamePassword
|
||||
} else {
|
||||
method = authNotRequired
|
||||
}
|
||||
_, err = conn.Write([]byte{socks5Version, 1, byte(method)})
|
||||
require.NoError(t, err)
|
||||
|
||||
var methodResp [2]byte
|
||||
_, err = io.ReadFull(conn, methodResp[:])
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, socks5Version, methodResp[0])
|
||||
require.Equal(t, byte(method), methodResp[1])
|
||||
|
||||
if method == authUsernamePassword {
|
||||
packet := []byte{authUsernamePasswordSubNegotiation1, byte(len(username))}
|
||||
packet = append(packet, []byte(username)...)
|
||||
packet = append(packet, byte(len(password)))
|
||||
packet = append(packet, []byte(password)...)
|
||||
_, err = conn.Write(packet)
|
||||
require.NoError(t, err)
|
||||
|
||||
var subnegResp [2]byte
|
||||
_, err = io.ReadFull(conn, subnegResp[:])
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, authUsernamePasswordSubNegotiation1, subnegResp[0])
|
||||
require.Equal(t, byte(0), subnegResp[1])
|
||||
}
|
||||
|
||||
var connectRequest []byte
|
||||
if ip := net.ParseIP(host).To4(); ip != nil {
|
||||
connectRequest = []byte{socks5Version, byte(connect), 0, byte(ipv4)}
|
||||
connectRequest = append(connectRequest, ip...)
|
||||
} else {
|
||||
connectRequest = []byte{socks5Version, byte(connect), 0, byte(domainName), byte(len(host))}
|
||||
connectRequest = append(connectRequest, []byte(host)...)
|
||||
}
|
||||
connectRequest = binary.BigEndian.AppendUint16(connectRequest, uint16(targetPort)) //nolint:gosec
|
||||
_, err = conn.Write(connectRequest)
|
||||
require.NoError(t, err)
|
||||
|
||||
var responseHeader [4]byte
|
||||
_, err = io.ReadFull(conn, responseHeader[:])
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, socks5Version, responseHeader[0])
|
||||
require.Equal(t, byte(succeeded), responseHeader[1])
|
||||
|
||||
// Consume BND.ADDR and BND.PORT (their values are irrelevant to the caller).
|
||||
switch addrType(responseHeader[3]) {
|
||||
case ipv4:
|
||||
var addrPort [net.IPv4len + 2]byte
|
||||
_, err = io.ReadFull(conn, addrPort[:])
|
||||
require.NoError(t, err)
|
||||
case ipv6:
|
||||
var addrPort [net.IPv6len + 2]byte
|
||||
_, err = io.ReadFull(conn, addrPort[:])
|
||||
require.NoError(t, err)
|
||||
case domainName:
|
||||
var lenBuf [1]byte
|
||||
_, err = io.ReadFull(conn, lenBuf[:])
|
||||
require.NoError(t, err)
|
||||
addrPort := make([]byte, int(lenBuf[0])+2)
|
||||
_, err = io.ReadFull(conn, addrPort)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
return conn
|
||||
}
|
||||
|
||||
func Test_newServer(t *testing.T) {
|
||||
t.Parallel()
|
||||
testCases := map[string]struct {
|
||||
settings Settings
|
||||
expected *server
|
||||
}{
|
||||
"with_auth": {
|
||||
settings: Settings{
|
||||
Username: "user",
|
||||
Password: "pass",
|
||||
Address: "127.0.0.1:1080",
|
||||
},
|
||||
expected: &server{
|
||||
username: "user",
|
||||
password: "pass",
|
||||
address: "127.0.0.1:1080",
|
||||
},
|
||||
},
|
||||
"without_auth": {
|
||||
settings: Settings{
|
||||
Address: "127.0.0.1:1080",
|
||||
},
|
||||
expected: &server{
|
||||
address: "127.0.0.1:1080",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for name, testCase := range testCases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
result := newServer(testCase.settings)
|
||||
assert.Equal(t, testCase.expected.username, result.username)
|
||||
assert.Equal(t, testCase.expected.password, result.password)
|
||||
assert.Equal(t, testCase.expected.address, result.address)
|
||||
assert.Equal(t, testCase.expected.logger, result.logger)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func Test_Server_StartStop(t *testing.T) {
|
||||
t.Parallel()
|
||||
ctrl := gomock.NewController(t)
|
||||
|
||||
logger := NewMockLogger(ctrl)
|
||||
logger.EXPECT().Infof("SOCKS5 server listening on %s", gomock.Any())
|
||||
|
||||
server := newServer(Settings{
|
||||
Address: "127.0.0.1:0",
|
||||
Logger: logger,
|
||||
})
|
||||
|
||||
runErr, startErr := server.Start(t.Context())
|
||||
require.NoError(t, startErr)
|
||||
|
||||
select {
|
||||
case err := <-runErr:
|
||||
t.Fatalf("unexpected error on start: %v", err)
|
||||
default:
|
||||
}
|
||||
|
||||
address := server.listeningAddress()
|
||||
assert.NotNil(t, address)
|
||||
|
||||
err := server.Stop()
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
func Test_encodeBindData(t *testing.T) {
|
||||
t.Parallel()
|
||||
testCases := map[string]struct {
|
||||
addrType addrType
|
||||
address string
|
||||
port uint16
|
||||
expectedErr string
|
||||
}{
|
||||
"ipv4_valid": {
|
||||
addrType: ipv4,
|
||||
address: "127.0.0.1",
|
||||
port: 8080,
|
||||
},
|
||||
"ipv6_valid": {
|
||||
addrType: ipv6,
|
||||
address: "::1",
|
||||
port: 8080,
|
||||
},
|
||||
"domain_name_valid": {
|
||||
addrType: domainName,
|
||||
address: "example.com",
|
||||
port: 8080,
|
||||
},
|
||||
"ipv4_invalid": {
|
||||
addrType: ipv4,
|
||||
address: "invalid",
|
||||
expectedErr: "parsing IP address",
|
||||
},
|
||||
"ipv4_actual_ipv6": {
|
||||
addrType: ipv4,
|
||||
address: "::1",
|
||||
expectedErr: "ip version is unexpected",
|
||||
},
|
||||
"ipv6_actual_ipv4": {
|
||||
addrType: ipv6,
|
||||
address: "127.0.0.1",
|
||||
expectedErr: "ip version is unexpected",
|
||||
},
|
||||
"domain_too_long": {
|
||||
addrType: domainName,
|
||||
address: strings.Repeat("a", 256),
|
||||
expectedErr: "domain name is too long",
|
||||
},
|
||||
}
|
||||
|
||||
for name, testCase := range testCases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
data, err := encodeBindData(testCase.addrType, testCase.address, testCase.port)
|
||||
|
||||
if testCase.expectedErr != "" {
|
||||
assert.ErrorContains(t, err, testCase.expectedErr)
|
||||
assert.Nil(t, data)
|
||||
} else {
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, data)
|
||||
|
||||
assert.Equal(t, byte(testCase.addrType), data[0])
|
||||
|
||||
portOffset := len(data) - 2
|
||||
decodedPort := binary.BigEndian.Uint16(data[portOffset:])
|
||||
assert.Equal(t, testCase.port, decodedPort)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func Test_decodeRequest(t *testing.T) {
|
||||
t.Parallel()
|
||||
testCases := map[string]struct {
|
||||
packet []byte
|
||||
expectedErr string
|
||||
validate func(*testing.T, request)
|
||||
}{
|
||||
"ipv4_valid": {
|
||||
packet: []byte{socks5Version, byte(connect), 0, byte(ipv4), 127, 0, 0, 1, byte(0x1f), byte(0x90)},
|
||||
validate: func(t *testing.T, request request) {
|
||||
t.Helper()
|
||||
assert.Equal(t, connect, request.command)
|
||||
assert.Equal(t, "127.0.0.1", request.destination)
|
||||
assert.Equal(t, uint16(8080), request.port)
|
||||
assert.Equal(t, ipv4, request.addressType)
|
||||
},
|
||||
},
|
||||
"domain_name_valid": {
|
||||
packet: concatBytes(
|
||||
[]byte{socks5Version, byte(connect), 0, byte(domainName)},
|
||||
[]byte{byte(len("example.com"))},
|
||||
[]byte("example.com"),
|
||||
[]byte{0x00, 0x50},
|
||||
),
|
||||
validate: func(t *testing.T, request request) {
|
||||
t.Helper()
|
||||
assert.Equal(t, "example.com", request.destination)
|
||||
assert.Equal(t, uint16(80), request.port)
|
||||
assert.Equal(t, domainName, request.addressType)
|
||||
},
|
||||
},
|
||||
"version_mismatch": {
|
||||
packet: []byte{4, byte(connect), 0, byte(ipv4), 127, 0, 0, 1, 0, 0},
|
||||
expectedErr: "version is not supported",
|
||||
},
|
||||
"truncated_header": {
|
||||
packet: []byte{socks5Version, byte(connect)},
|
||||
expectedErr: "reading header",
|
||||
},
|
||||
"unsupported_address_type": {
|
||||
packet: []byte{socks5Version, byte(connect), 0, byte(255)},
|
||||
expectedErr: "address type is not supported",
|
||||
},
|
||||
}
|
||||
|
||||
for name, testCase := range testCases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
reader := bytes.NewReader(testCase.packet)
|
||||
|
||||
request, err := decodeRequest(reader, socks5Version)
|
||||
|
||||
if testCase.expectedErr != "" {
|
||||
assert.ErrorContains(t, err, testCase.expectedErr)
|
||||
} else {
|
||||
assert.NoError(t, err)
|
||||
testCase.validate(t, request)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func Test_verifyFirstNegotiation(t *testing.T) {
|
||||
t.Parallel()
|
||||
testCases := map[string]struct {
|
||||
packet []byte
|
||||
requiredAuth authMethod
|
||||
expectedErr string
|
||||
}{
|
||||
"version_mismatch": {
|
||||
packet: []byte{4, 2, byte(authNotRequired), byte(authUsernamePassword)},
|
||||
requiredAuth: authNotRequired,
|
||||
expectedErr: "version is not supported",
|
||||
},
|
||||
"no_methods": {
|
||||
packet: []byte{socks5Version, 0},
|
||||
requiredAuth: authNotRequired,
|
||||
expectedErr: "no method identifiers",
|
||||
},
|
||||
"required_method_not_present": {
|
||||
packet: []byte{socks5Version, 2, byte(authNotRequired), byte(authGssapi)},
|
||||
requiredAuth: authUsernamePassword,
|
||||
expectedErr: "no valid method identifier",
|
||||
},
|
||||
"required_method_present": {
|
||||
packet: []byte{socks5Version, 3, byte(authNotRequired), byte(authUsernamePassword), byte(authGssapi)},
|
||||
requiredAuth: authUsernamePassword,
|
||||
},
|
||||
"no_auth_required": {
|
||||
packet: []byte{socks5Version, 1, byte(authNotRequired)},
|
||||
requiredAuth: authNotRequired,
|
||||
},
|
||||
}
|
||||
|
||||
for name, testCase := range testCases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
reader := bytes.NewReader(testCase.packet)
|
||||
|
||||
err := verifyFirstNegotiation(reader, testCase.requiredAuth)
|
||||
|
||||
if testCase.expectedErr != "" {
|
||||
assert.ErrorContains(t, err, testCase.expectedErr)
|
||||
} else {
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func Test_usernamePasswordSubnegotiate(t *testing.T) {
|
||||
t.Parallel()
|
||||
testCases := map[string]struct {
|
||||
packet []byte
|
||||
username string
|
||||
password string
|
||||
expectedErr string
|
||||
}{
|
||||
"valid_credentials": {
|
||||
packet: concatBytes(
|
||||
[]byte{authUsernamePasswordSubNegotiation1, 4},
|
||||
[]byte("user"),
|
||||
[]byte{4},
|
||||
[]byte("pass"),
|
||||
),
|
||||
username: "user",
|
||||
password: "pass",
|
||||
},
|
||||
"version_mismatch": {
|
||||
packet: []byte{2, 4, 'u', 's', 'e', 'r'},
|
||||
username: "user",
|
||||
password: "pass",
|
||||
expectedErr: "subnegotiation version not supported",
|
||||
},
|
||||
"wrong_username": {
|
||||
packet: concatBytes(
|
||||
[]byte{authUsernamePasswordSubNegotiation1, 4},
|
||||
[]byte("fake"),
|
||||
[]byte{4},
|
||||
[]byte("pass"),
|
||||
),
|
||||
username: "user",
|
||||
password: "pass",
|
||||
expectedErr: "username received is not valid",
|
||||
},
|
||||
"wrong_password": {
|
||||
packet: concatBytes(
|
||||
[]byte{authUsernamePasswordSubNegotiation1, 4},
|
||||
[]byte("user"),
|
||||
[]byte{4},
|
||||
[]byte("fake"),
|
||||
),
|
||||
username: "user",
|
||||
password: "pass",
|
||||
expectedErr: "password not valid",
|
||||
},
|
||||
"truncated_header": {
|
||||
packet: []byte{authUsernamePasswordSubNegotiation1},
|
||||
username: "user",
|
||||
password: "pass",
|
||||
expectedErr: "reading header",
|
||||
},
|
||||
}
|
||||
|
||||
for name, testCase := range testCases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
buffer := bytes.NewBuffer(testCase.packet)
|
||||
|
||||
readWriter := struct {
|
||||
io.Reader
|
||||
io.Writer
|
||||
}{
|
||||
Reader: buffer,
|
||||
Writer: io.Discard,
|
||||
}
|
||||
|
||||
err := usernamePasswordSubnegotiate(readWriter, testCase.username, testCase.password)
|
||||
|
||||
if testCase.expectedErr != "" {
|
||||
assert.ErrorContains(t, err, testCase.expectedErr)
|
||||
} else {
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func concatBytes(slices ...[]byte) []byte {
|
||||
var result []byte
|
||||
for _, slice := range slices {
|
||||
result = append(result, slice...)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func Test_bindDataLength(t *testing.T) {
|
||||
t.Parallel()
|
||||
testCases := map[string]struct {
|
||||
addrType addrType
|
||||
address string
|
||||
wantMaxLength uint
|
||||
}{
|
||||
"ipv4": {
|
||||
addrType: ipv4,
|
||||
address: "127.0.0.1",
|
||||
wantMaxLength: 1 + 4 + 2,
|
||||
},
|
||||
"ipv6": {
|
||||
addrType: ipv6,
|
||||
address: "::1",
|
||||
wantMaxLength: 1 + 16 + 2,
|
||||
},
|
||||
"domain_short": {
|
||||
addrType: domainName,
|
||||
address: "example.com",
|
||||
wantMaxLength: 1 + 1 + uint(len("example.com")) + 2,
|
||||
},
|
||||
"domain_long": {
|
||||
addrType: domainName,
|
||||
address: strings.Repeat("a", 100),
|
||||
wantMaxLength: 1 + 1 + 100 + 2,
|
||||
},
|
||||
}
|
||||
|
||||
for name, testCase := range testCases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
length := bindDataLength(testCase.addrType, testCase.address)
|
||||
assert.Equal(t, testCase.wantMaxLength, length)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func Test_authMethod_String(t *testing.T) {
|
||||
t.Parallel()
|
||||
testCases := map[string]struct {
|
||||
method authMethod
|
||||
expectedName string
|
||||
}{
|
||||
"no_auth": {
|
||||
method: authNotRequired,
|
||||
expectedName: "no authentication required",
|
||||
},
|
||||
"gssapi": {
|
||||
method: authGssapi,
|
||||
expectedName: "GSSAPI",
|
||||
},
|
||||
"username_password": {
|
||||
method: authUsernamePassword,
|
||||
expectedName: "username/password",
|
||||
},
|
||||
"not_acceptable": {
|
||||
method: authNotAcceptable,
|
||||
expectedName: "no acceptable methods",
|
||||
},
|
||||
"unknown": {
|
||||
method: authMethod(99),
|
||||
expectedName: "unknown method (99)",
|
||||
},
|
||||
}
|
||||
|
||||
for name, testCase := range testCases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
result := testCase.method.String()
|
||||
assert.Equal(t, testCase.expectedName, result)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func Test_cmdType_String(t *testing.T) {
|
||||
t.Parallel()
|
||||
testCases := map[string]struct {
|
||||
cmd cmdType
|
||||
expectedName string
|
||||
}{
|
||||
"connect": {
|
||||
cmd: connect,
|
||||
expectedName: "connect",
|
||||
},
|
||||
"bind": {
|
||||
cmd: bind,
|
||||
expectedName: "bind",
|
||||
},
|
||||
"udp_associate": {
|
||||
cmd: udpAssociate,
|
||||
expectedName: "UDP associate",
|
||||
},
|
||||
"unknown": {
|
||||
cmd: cmdType(99),
|
||||
expectedName: "unknown command (99)",
|
||||
},
|
||||
}
|
||||
|
||||
for name, testCase := range testCases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
result := testCase.cmd.String()
|
||||
assert.Equal(t, testCase.expectedName, result)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
package socks5
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
)
|
||||
|
||||
// See https://datatracker.ietf.org/doc/html/rfc1929#section-2
|
||||
func usernamePasswordSubnegotiate(conn io.ReadWriter, username, password string) (err error) {
|
||||
status := byte(1)
|
||||
const defaultVersion = byte(1)
|
||||
|
||||
const headerLength = 2
|
||||
var header [headerLength]byte
|
||||
_, err = io.ReadFull(conn, header[:])
|
||||
if err != nil {
|
||||
_, _ = conn.Write([]byte{defaultVersion, status})
|
||||
return fmt.Errorf("reading header: %w", err)
|
||||
}
|
||||
|
||||
if header[0] != authUsernamePasswordSubNegotiation1 {
|
||||
_, _ = conn.Write([]byte{defaultVersion, status})
|
||||
return fmt.Errorf("subnegotiation version not supported: %d", header[0])
|
||||
}
|
||||
version := header[0]
|
||||
|
||||
usernameBytes := make([]byte, header[1])
|
||||
_, err = io.ReadFull(conn, usernameBytes)
|
||||
if err != nil {
|
||||
_, _ = conn.Write([]byte{version, status})
|
||||
return fmt.Errorf("reading username bytes: %w", err)
|
||||
} else if username != string(usernameBytes) {
|
||||
_, _ = conn.Write([]byte{version, status})
|
||||
return fmt.Errorf("username received is not valid")
|
||||
}
|
||||
|
||||
const passwordHeaderLength = 1
|
||||
passwordHeader := make([]byte, passwordHeaderLength)
|
||||
_, err = io.ReadFull(conn, passwordHeader)
|
||||
if err != nil {
|
||||
_, _ = conn.Write([]byte{version, status})
|
||||
return fmt.Errorf("reading password length: %w", err)
|
||||
}
|
||||
|
||||
passwordBytes := make([]byte, passwordHeader[0])
|
||||
_, err = io.ReadFull(conn, passwordBytes)
|
||||
if err != nil {
|
||||
_, _ = conn.Write([]byte{version, status})
|
||||
return fmt.Errorf("reading password bytes: %w", err)
|
||||
} else if password != string(passwordBytes) {
|
||||
_, _ = conn.Write([]byte{version, status})
|
||||
return fmt.Errorf("password not valid for username %q", string(usernameBytes))
|
||||
}
|
||||
|
||||
status = 0
|
||||
_, err = conn.Write([]byte{version, status})
|
||||
if err != nil {
|
||||
return fmt.Errorf("writing success status: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,15 +1,23 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"net/netip"
|
||||
|
||||
"github.com/qdm12/gluetun/internal/models"
|
||||
)
|
||||
|
||||
func copyServer(server models.Server) (serverCopy models.Server) {
|
||||
serverCopy = server
|
||||
serverCopy.IPs = slices.Clone(server.IPs)
|
||||
serverCopy.PortsTCP = slices.Clone(server.PortsTCP)
|
||||
serverCopy.PortsUDP = slices.Clone(server.PortsUDP)
|
||||
serverCopy.IPs = copyIPs(server.IPs)
|
||||
return serverCopy
|
||||
}
|
||||
|
||||
func copyIPs(toCopy []netip.Addr) (copied []netip.Addr) {
|
||||
if toCopy == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
copied = make([]netip.Addr, len(toCopy))
|
||||
copy(copied, toCopy)
|
||||
return copied
|
||||
}
|
||||
|
||||
@@ -21,9 +21,43 @@ func Test_copyServer(t *testing.T) {
|
||||
assert.Equal(t, server, serverCopy)
|
||||
// Check for mutation
|
||||
serverCopy.IPs[0] = netip.AddrFrom4([4]byte{9, 9, 9, 9})
|
||||
serverCopy.PortsTCP = []uint16{80}
|
||||
serverCopy.PortsUDP = []uint16{53}
|
||||
assert.NotEqual(t, server.IPs, serverCopy.IPs)
|
||||
assert.NotEqual(t, server.PortsTCP, serverCopy.PortsTCP)
|
||||
assert.NotEqual(t, server.PortsUDP, serverCopy.PortsUDP)
|
||||
assert.NotEqual(t, server, serverCopy)
|
||||
}
|
||||
|
||||
func Test_copyIPs(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
testCases := map[string]struct {
|
||||
toCopy []netip.Addr
|
||||
copied []netip.Addr
|
||||
}{
|
||||
"nil": {},
|
||||
"empty": {
|
||||
toCopy: []netip.Addr{},
|
||||
copied: []netip.Addr{},
|
||||
},
|
||||
"single IP": {
|
||||
toCopy: []netip.Addr{netip.AddrFrom4([4]byte{1, 1, 1, 1})},
|
||||
copied: []netip.Addr{netip.AddrFrom4([4]byte{1, 1, 1, 1})},
|
||||
},
|
||||
"two IPs": {
|
||||
toCopy: []netip.Addr{netip.AddrFrom4([4]byte{1, 1, 1, 1}), netip.AddrFrom4([4]byte{2, 2, 2, 2})},
|
||||
copied: []netip.Addr{netip.AddrFrom4([4]byte{1, 1, 1, 1}), netip.AddrFrom4([4]byte{2, 2, 2, 2})},
|
||||
},
|
||||
}
|
||||
|
||||
for name, testCase := range testCases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
copied := copyIPs(testCase.toCopy)
|
||||
|
||||
assert.Equal(t, testCase.copied, copied)
|
||||
|
||||
if len(copied) > 0 {
|
||||
testCase.toCopy[0] = netip.AddrFrom4([4]byte{9, 9, 9, 9})
|
||||
assert.NotEqual(t, testCase.toCopy[0], testCase.copied[0])
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ package storage
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/qdm12/gluetun/internal/configuration/settings"
|
||||
@@ -49,7 +48,6 @@ func (s *Storage) FilterServers(provider string, selection settings.ServerSelect
|
||||
return servers, nil
|
||||
}
|
||||
|
||||
//nolint:gocognit,gocyclo
|
||||
func filterServer(server models.Server,
|
||||
selection settings.ServerSelection,
|
||||
) (filtered bool) {
|
||||
@@ -92,11 +90,6 @@ func filterServer(server models.Server,
|
||||
return true
|
||||
}
|
||||
|
||||
if (*selection.Dedicated && !server.Dedicated) ||
|
||||
(!*selection.Dedicated && server.Dedicated) {
|
||||
return false
|
||||
}
|
||||
|
||||
if filterByPossibilities(server.Country, selection.Countries) {
|
||||
return true
|
||||
}
|
||||
@@ -129,14 +122,6 @@ func filterServer(server models.Server,
|
||||
return true
|
||||
}
|
||||
|
||||
serverPorts := server.PortsUDP
|
||||
if server.VPN == vpn.OpenVPN && server.TCP {
|
||||
serverPorts = server.PortsTCP
|
||||
}
|
||||
if filterByPorts(selection, serverPorts) {
|
||||
return true
|
||||
}
|
||||
|
||||
// TODO filter port forward server for PIA
|
||||
|
||||
return false
|
||||
@@ -180,21 +165,3 @@ func filterByProtocol(selection settings.ServerSelection,
|
||||
return (wantTCP && !serverTCP) || (wantUDP && !serverUDP)
|
||||
}
|
||||
}
|
||||
|
||||
func filterByPorts(selection settings.ServerSelection,
|
||||
serverPorts []uint16,
|
||||
) (filtered bool) {
|
||||
if len(serverPorts) == 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
customPort := *selection.OpenVPN.CustomPort
|
||||
if selection.VPN == vpn.Wireguard {
|
||||
customPort = *selection.Wireguard.EndpointPort
|
||||
}
|
||||
if customPort == 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
return !slices.Contains(serverPorts, customPort)
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ func commaJoin(slice []string) string {
|
||||
return strings.Join(slice, ", ")
|
||||
}
|
||||
|
||||
func noServerFoundError(selection settings.ServerSelection) (err error) { //nolint:gocyclo
|
||||
func noServerFoundError(selection settings.ServerSelection) (err error) {
|
||||
var messageParts []string
|
||||
|
||||
messageParts = append(messageParts, "VPN "+selection.VPN)
|
||||
@@ -155,15 +155,6 @@ func noServerFoundError(selection settings.ServerSelection) (err error) { //noli
|
||||
"target ip address "+targetIP.String())
|
||||
}
|
||||
|
||||
customPort := *selection.OpenVPN.CustomPort
|
||||
if selection.VPN == vpn.Wireguard {
|
||||
customPort = *selection.Wireguard.EndpointPort
|
||||
}
|
||||
if customPort > 0 {
|
||||
messageParts = append(messageParts,
|
||||
fmt.Sprintf("%s endpoint port %d", selection.VPN, customPort))
|
||||
}
|
||||
|
||||
message := "for " + strings.Join(messageParts, "; ")
|
||||
|
||||
return fmt.Errorf("no server found: %s", message)
|
||||
|
||||
@@ -26,14 +26,10 @@ func parseHardcodedServers() (allServers models.AllServers) {
|
||||
}
|
||||
|
||||
for provider, metadata := range allServers.ProviderToServers {
|
||||
if metadata.Filepath == "" {
|
||||
panic(fmt.Sprintf("embedded manifest file servers.json should have the filepath field set for %s", provider))
|
||||
}
|
||||
filename := path.Base(metadata.Filepath)
|
||||
providerFile, err := serversmodule.Files.Open(filename)
|
||||
if err != nil {
|
||||
const rootURL = "https://github.com/qdm12/gluetun-servers/blob/main/pkg/servers"
|
||||
panic(fmt.Sprintf("reading embedded provider file defined at %s/%s: %s", rootURL, filename, err))
|
||||
panic(fmt.Sprintf("reading embedded provider file %s for %s: %s", filename, provider, err))
|
||||
}
|
||||
defer providerFile.Close() // no-op
|
||||
|
||||
|
||||
@@ -33,10 +33,7 @@ func Test_parseHardcodedServers(t *testing.T) {
|
||||
func Test_parseHardcodedServers_filepathsAndEmbeddedProviderFiles(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var hardcodedServers models.AllServers
|
||||
require.NotPanics(t, func() {
|
||||
hardcodedServers = parseHardcodedServers()
|
||||
})
|
||||
hardcodedServers := parseHardcodedServers()
|
||||
|
||||
allProviders := providers.All()
|
||||
for _, provider := range allProviders {
|
||||
|
||||
@@ -30,9 +30,6 @@
|
||||
"nordvpn": {
|
||||
"filepath": "/gluetun/servers/nordvpn.json"
|
||||
},
|
||||
"ovpn": {
|
||||
"filepath": "/gluetun/servers/ovpn.json"
|
||||
},
|
||||
"perfect privacy": {
|
||||
"filepath": "/gluetun/servers/perfect privacy.json"
|
||||
},
|
||||
@@ -72,4 +69,4 @@
|
||||
"windscribe": {
|
||||
"filepath": "/gluetun/servers/windscribe.json"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,7 +31,7 @@ func getGithubReleases(ctx context.Context, client *http.Client) (releases []git
|
||||
ctx, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
|
||||
const url = "https://api.github.com/repos/passteque/gluetun/releases"
|
||||
const url = "https://api.github.com/repos/qdm12/gluetun/releases"
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -62,7 +62,7 @@ func getGithubCommits(ctx context.Context, client *http.Client) (commits []githu
|
||||
ctx, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
|
||||
const url = "https://api.github.com/repos/passteque/gluetun/commits"
|
||||
const url = "https://api.github.com/repos/qdm12/gluetun/commits"
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
Reference in New Issue
Block a user