feat(proxy): select a vpn server by network or ip with @

On NordVPN, Windscribe and Surfshark, `@<name>` keeps and `@-<name>` skips a hosting network; `@<ip>` and `@-<ip>` pick or skip one server. The connect line names the server, IP and network. Surfshark pins an IP through a loopback TLS port.
This commit is contained in:
imSp4rky
2026-10-22 13:53:30 -06:00
parent b2dc70ff56
commit 4753fcd7bc
9 changed files with 689 additions and 35 deletions
+110
View File
@@ -0,0 +1,110 @@
"""Tell VPN servers apart by the network (AS) that hosts them, for the `@` proxy selector."""
from __future__ import annotations
import ipaddress
import re
import socket
from concurrent.futures import ThreadPoolExecutor
from typing import Iterable, Optional
from unidecode import unidecode
WHOIS = ("whois.cymru.com", 43)
TIMEOUT = 3
NETWORKS: dict[str, str] = {}
FAILED: Optional[str] = None
def split_selector(query: str) -> tuple[str, Optional[str]]:
"""Split "fr:paris@-datacamp" into the region query and the network selector after "@"."""
query, _, selector = query.partition("@")
return query, selector or None
def lookup(ips: Iterable[str]) -> dict[str, str]:
"""
Get the network (AS) name of each IP from Team Cymru's bulk whois. An IP it does not know is left out.
A failure is kept for the process, so a blocked port 43 costs one timeout, not one per proxy.
"""
global FAILED
ips = list(dict.fromkeys(ips))
wanted = [x for x in ips if x not in NETWORKS]
if wanted:
if FAILED:
raise ConnectionError(FAILED)
data = b""
try:
with socket.create_connection(WHOIS, timeout=TIMEOUT) as conn:
conn.sendall(("begin\n" + "\n".join(wanted) + "\nend\n").encode())
while chunk := conn.recv(65536):
data += chunk
except OSError as e:
FAILED = f"Could not get the networks of the VPN servers from {WHOIS[0]}: {e}"
raise ConnectionError(FAILED) from None
for line in data.decode("utf-8", "replace").splitlines():
fields = [x.strip() for x in line.split("|")]
if len(fields) == 3 and fields[0].isdigit():
NETWORKS[fields[1]] = fields[2]
return {x: NETWORKS[x] for x in ips if x in NETWORKS}
def fold(text: str) -> str:
"""Reduce a name to lowercase ASCII letters and digits, so "Frankfurt am Main" and "frankfurt-am-main" match."""
return re.sub(r"[^a-z0-9]", "", unidecode(text).lower())
def short_name(name: str) -> str:
"""Shorten an AS name such as "CDNEXT - Datacamp Limited, GB" to "Datacamp Limited"."""
return re.sub(r",\s*[A-Z]{2}$", "", name).split(" - ", 1)[-1]
def is_ip(selector: str) -> bool:
"""Whether a selector names one server IPv4 address, not a network."""
try:
ipaddress.IPv4Address(selector)
except ValueError:
return False
return True
def select(servers: dict[str, str], selector: str) -> list[str]:
"""
Get the servers (a server -> IP map) that match the selector, or with a leading "-", the servers that do not.
An IPv4 selector matches that server IP. Any other selector matches a network whose name contains it,
ignoring case, spaces and punctuation; a server whose network is not known is left out either way.
"""
exclude = selector.startswith("-")
if is_ip(address := selector.removeprefix("-")):
return [x for x, ip in servers.items() if (ip == address) != exclude]
selector = fold(address)
if not selector:
raise ValueError("A proxy network selector needs a network name after '@', for example @datacamp")
networks = lookup(servers.values())
return [x for x, ip in servers.items() if ip in networks and (selector in fold(networks[ip])) != exclude]
def resolve_all(hostnames: Iterable[str]) -> dict[str, str]:
"""Resolve hostnames to an IPv4 address each, in parallel. A hostname that does not resolve is left out."""
def resolve(hostname: str) -> Optional[str]:
try:
return socket.gethostbyname(hostname)
except OSError:
return None
hostnames = list(dict.fromkeys(hostnames))
with ThreadPoolExecutor(16) as pool:
return {x: ip for x, ip in zip(hostnames, pool.map(resolve, hostnames)) if ip}
def describe(hostname: str, ip: Optional[str] = None) -> str:
"""Name a server with its IP and network, for the line that says which proxy is in use. This never raises."""
try:
ip = ip or socket.gethostbyname(hostname)
network = lookup([ip]).get(ip)
except OSError:
return f"{hostname} ({ip})" if ip else hostname
return f"{hostname} ({ip}, {short_name(network)})" if network else f"{hostname} ({ip})"
+52 -6
View File
@@ -5,6 +5,7 @@ from typing import Optional
import requests
from unshackle.core.proxies.asn import describe, is_ip, select, split_selector
from unshackle.core.proxies.proxy import Proxy
from unshackle.core.utilities import COUNTRY_CODE_ALIASES
@@ -33,6 +34,7 @@ class NordVPN(Proxy):
self.username = username
self.password = password
self.server_map = server_map or {}
self.last_hostname: Optional[str] = None
self.countries = self.get_countries()
@@ -54,11 +56,13 @@ class NordVPN(Proxy):
- Country ID: "228"
- Specific server: "us1234"
- City selection: "us:seattle", "us:new-york", "ca:calgary"
- Network selection: "ca@datacamp", "ca:toronto@-datacamp" (a leading "-" excludes)
- One server IP: "fr@187.14.108.15"
Returns None for a query NordVPN cannot serve: an unrecognised form, a country it does not list,
or a country with no recommended servers. A city with no matching server raises ValueError.
"""
query = query.lower()
query, selector = split_selector(query.lower())
city = None
if ":" in query:
@@ -66,6 +70,8 @@ class NordVPN(Proxy):
city = city.strip()
if re.fullmatch(r"[a-z]{2}\d+", query):
if selector:
raise ValueError(f"'{query}' is already one NordVPN server, so it takes no '@' network selector.")
hostname = f"{query}.proxy.nordvpn.com"
else:
if query.isdigit():
@@ -82,7 +88,7 @@ class NordVPN(Proxy):
self.server_map.get(country["code"].lower()) if not city else None
)
if server_mapping:
if server_mapping and not selector:
hostname = f"{country['code'].lower()}{server_mapping}.proxy.nordvpn.com"
else:
city_id = None
@@ -97,11 +103,21 @@ class NordVPN(Proxy):
f"No servers found in city '{city}' for country '{country['name']}'. "
"Try a different city or check the city name spelling."
)
recommended_servers = self.get_recommended_servers(country["id"], city_id)
if selector and is_ip(selector):
recommended_servers = self.get_all_servers(country["id"])
else:
recommended_servers = self.get_recommended_servers(
country["id"], city_id, limit=0 if selector else None
)
if not recommended_servers:
return None
hostnames = [x["hostname"] for x in recommended_servers]
if selector:
hostnames = select({x["hostname"]: x["station"] for x in recommended_servers}, selector)
if not hostnames:
raise ValueError(f"No NordVPN server in {query} matches '@{selector}'.")
hostname = random.choice(recommended_servers)["hostname"]
hostname = random.choice(hostnames)
if hostname.startswith("gb"):
# NordVPN uses the alpha2 of 'GB' in API responses, but 'UK' in the hostname
@@ -110,8 +126,13 @@ class NordVPN(Proxy):
if hostname.endswith(".nordvpn.com") and not hostname.endswith(".proxy.nordvpn.com"):
hostname = hostname[: -len(".nordvpn.com")] + ".proxy.nordvpn.com"
self.last_hostname = hostname
return f"https://{self.username}:{self.password}@{hostname}:89"
def last_connection_display(self) -> Optional[str]:
"""Name the last server with its IP and network, so a blocked network can be excluded with '@-'."""
return describe(self.last_hostname) if self.last_hostname else None
def get_country(self, by_id: Optional[int] = None, by_code: Optional[str] = None) -> Optional[dict]:
"""Find a Country and its metadata."""
if all(x is None for x in (by_id, by_code)):
@@ -124,15 +145,40 @@ class NordVPN(Proxy):
return country
@staticmethod
def get_recommended_servers(country_id: int, city_id: Optional[int] = None) -> list[dict]:
def get_all_servers(country_id: int) -> list[dict]:
"""Get the hostname and IP of every server in a Country, recommended or not."""
res = requests.get(
url="https://api.nordvpn.com/v1/servers",
params={
"filters[country_id]": country_id,
"limit": 0,
"fields[servers.hostname]": 1,
"fields[servers.station]": 1,
},
timeout=10,
)
if not res.ok:
raise ValueError(f"Failed to get a list of NordVPN servers [{res.status_code}]")
try:
return res.json()
except json.JSONDecodeError:
raise ValueError("Could not decode list of NordVPN servers, not JSON data.")
@staticmethod
def get_recommended_servers(
country_id: int, city_id: Optional[int] = None, limit: Optional[int] = None
) -> list[dict]:
"""
Get the list of recommended Servers for a Country, or for one of its cities.
Note: There may not always be more than one recommended server.
Note: There may not always be more than one recommended server. A limit of 0 gets all of them.
"""
params = {"filters[country_id]": country_id}
if city_id is not None:
params["filters[country_city_id]"] = city_id
if limit is not None:
params.update({"limit": limit, "fields[servers.hostname]": 1, "fields[servers.station]": 1})
res = requests.get(url="https://api.nordvpn.com/v1/servers/recommendations", params=params, timeout=10)
if not res.ok:
raise ValueError(f"Failed to get a list of NordVPN countries [{res.status_code}]")
+1 -1
View File
@@ -16,7 +16,7 @@ from unshackle.core.utils.redact import mask_proxy
log = logging.getLogger("proxies")
REGION = r"[a-z]{2,4}(?:_[a-z0-9]{2,4})?(?:-[a-z0-9]+|:[a-z][a-z0-9]*)*\d*"
REGION = r"[a-z]{2,4}(?:_[a-z0-9]{2,4})?(?:-[a-z0-9]+|:[a-z][a-z0-9]*)*\d*(?:@-?[a-z0-9][a-z0-9._-]*)?"
class Unavailable(Proxy):
+133 -18
View File
@@ -1,17 +1,86 @@
import asyncio
import json
import logging
import random
import re
import socket
import ssl
import threading
from functools import cache, partial
from typing import Optional
import certifi
import requests
from unidecode import unidecode
from unshackle.core.proxies.asn import describe, fold, is_ip, select, split_selector
from unshackle.core.proxies.controld import build_query, parse_a_records
from unshackle.core.proxies.proxy import Proxy
from unshackle.core.utilities import COUNTRY_CODE_ALIASES
log = logging.getLogger("proxies.surfsharkvpn")
POOL_QUERIES = 48
PORT = 443
CONNECT_TIMEOUT = 30
CHUNK = 65536
TLS = ssl.create_default_context(cafile=certifi.where()) # the same CA bundle as requests
PINS: dict[tuple[str, str], int] = {}
LOOP: Optional[asyncio.AbstractEventLoop] = None
STATE = threading.Lock()
async def pipe(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
"""Copy bytes one way until the source closes, then close the sink."""
try:
while data := await reader.read(CHUNK):
writer.write(data)
await writer.drain()
except OSError:
pass
finally:
writer.close()
async def tunnel(ip: str, hostname: str, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
"""Carry one client connection over TLS to the server at `ip`, with its certificate checked against `hostname`."""
try:
upstream = await asyncio.wait_for(
asyncio.open_connection(ip, PORT, ssl=TLS, server_hostname=hostname), CONNECT_TIMEOUT
)
except OSError as e:
log.warning(f"Could not reach {hostname} at {ip}: {e}")
writer.close()
return
await asyncio.gather(pipe(reader, upstream[1]), pipe(upstream[0], writer))
@cache
def nameserver(zone: str) -> str:
"""Get the IPv4 address of a zone's first authoritative nameserver, through Google's DNS-over-HTTPS JSON API."""
res = requests.get("https://dns.google/resolve", params={"name": zone, "type": "NS"}, timeout=10)
res.raise_for_status()
return socket.gethostbyname([x["data"] for x in res.json().get("Answer", []) if x.get("type") == 2][0])
def pinned(ip: str, hostname: str) -> int:
"""
Get a loopback port that carries each connection over TLS to one server IP, starting it on first use.
The client still speaks the HTTP proxy protocol with the credentials itself: the port only fixes the IP,
which a proxy URI cannot do because the certificate names the hostname, not the IP.
"""
global LOOP
with STATE:
if (ip, hostname) not in PINS:
if LOOP is None:
LOOP = asyncio.new_event_loop()
threading.Thread(target=LOOP.run_forever, daemon=True, name="surfshark").start()
server = asyncio.run_coroutine_threadsafe(
asyncio.start_server(partial(tunnel, ip, hostname), "127.0.0.1", 0), LOOP
).result()
PINS[ip, hostname] = server.sockets[0].getsockname()[1]
return PINS[ip, hostname]
class SurfsharkVPN(Proxy):
def __init__(self, username: str, password: str, server_map: Optional[dict[str, str]] = None):
@@ -53,6 +122,7 @@ class SurfsharkVPN(Proxy):
country, sep, city = str(region).lower().partition(":")
self.server_map[COUNTRY_CODE_ALIASES.get(country, country) + sep + city] = server
self.last_server: Optional[tuple[str, str]] = None
self.countries = self.get_countries()
def __repr__(self) -> str:
@@ -69,11 +139,14 @@ class SurfsharkVPN(Proxy):
- Country code: "us", "ca", "gb" (or "uk")
- Specific server: "us-bos" (Boston)
- City selection: "us:seattle", "us:new-york"
- Network selection: "fr-bod@datacamp", "fr@-hostroyale" (a leading "-" excludes)
- One server IP: "fr-bod@195.86.24.103"
A network or IP selection goes through a loopback port pinned to the server IP (see `pinned`).
Returns None for a query that names no SurfsharkVPN country or server, so that the
next proxy provider can answer it. A city with no matching server raises ValueError.
"""
query = query.strip().lower()
query, selector = split_selector(query.strip().lower())
city = None
if ":" in query:
@@ -83,18 +156,65 @@ class SurfsharkVPN(Proxy):
server_map_key = f"{query}:{city}" if city else query
if server_map_key in self.server_map:
server = self.server_map[server_map_key]
servers = [self.server_map[server_map_key]]
elif not city and any(x["connectionName"].split(".", 1)[0] == query for x in self.countries):
server = query
servers = [query]
elif re.fullmatch(r"[a-z]{2}", query):
servers = [x for x in self.countries if x["countryCode"] == query.upper()]
if not servers:
in_country = [x for x in self.countries if x["countryCode"] == query.upper()]
if not in_country:
return None
server = self.get_random_server(servers, city)
servers = [x["connectionName"] for x in self.get_city_servers(in_country, city)]
else:
return None
return f"https://{self.username}:{self.password}@{self.get_hostname(server)}:443"
hostnames = [self.get_hostname(x) for x in servers]
self.last_server = None
if not selector:
return f"https://{self.username}:{self.password}@{random.choice(hostnames)}:443"
if is_ip(selector):
hostname, ip = random.choice(hostnames), selector
else:
hostname, ip = self.get_server_on_network(hostnames, selector)
self.last_server = (hostname, ip)
return f"http://{self.username}:{self.password}@127.0.0.1:{pinned(ip, hostname)}"
def last_connection_display(self) -> Optional[str]:
"""Name the pinned server with its IP and network, so it can be pinned again or excluded with '@-'."""
return describe(*self.last_server) if self.last_server else None
def get_server_on_network(self, hostnames: list[str], selector: str) -> tuple[str, str]:
"""Get a random (hostname, IP) that matches the selector (see `asn.select`), trying the clusters in random order."""
for hostname in random.sample(hostnames, len(hostnames)):
ips = select({ip: ip for ip in self.get_pool(hostname)}, selector)
if ips:
return hostname, random.choice(ips)
raise ValueError(f"No SurfsharkVPN server matches '@{selector}'.")
@staticmethod
def get_pool(hostname: str) -> list[str]:
"""
Get the server IPs behind a cluster hostname.
Its nameserver answers with two of them at random, so this sends it many queries at once and keeps every answer.
"""
ips: set[str] = set()
try:
address = nameserver(hostname.split(".", 1)[1])
query = build_query(hostname)
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
sock.settimeout(1)
for _ in range(POOL_QUERIES):
sock.sendto(query, (address, 53))
try:
for _ in range(POOL_QUERIES):
ips.update(ip for ip, _ in parse_a_records(sock.recv(4096)))
except TimeoutError:
pass
except (requests.RequestException, ValueError, IndexError, OSError) as e:
raise ValueError(f"Could not list the SurfsharkVPN servers of {hostname}: {e}") from None
if not ips:
raise ValueError(f"The nameserver of {hostname} did not answer, so its servers could not be listed.")
return sorted(ips)
@staticmethod
def get_hostname(server: str) -> str:
@@ -102,16 +222,16 @@ class SurfsharkVPN(Proxy):
server = server.lower()
return server if server.endswith(".surfshark.com") else f"{server}.prod.surfshark.com"
def get_random_server(self, servers: list[dict], city: Optional[str] = None) -> str:
def get_city_servers(self, servers: list[dict], city: Optional[str] = None) -> list[dict]:
"""
Get a random server name from a country's servers, optionally filtered by city.
Get a country's servers, optionally filtered by city.
A city matches with case, spaces, hyphens and accents ignored ("new-york" matches "New York"),
exactly first, then as a prefix ("frankfurt" matches "Frankfurt am Main").
"""
if city:
wanted = self.fold(city)
located = [(self.fold(x.get("location", "")), x) for x in servers]
wanted = fold(city)
located = [(fold(x.get("location", "")), x) for x in servers]
servers = [x for location, x in located if location == wanted] or [
x for location, x in located if location.startswith(wanted)
]
@@ -120,12 +240,7 @@ class SurfsharkVPN(Proxy):
f"No servers found in city '{city}'. Try a different city or check the city name spelling."
)
return random.choice(servers)["connectionName"]
@staticmethod
def fold(text: str) -> str:
"""Reduce a place name to lowercase ASCII letters and digits."""
return re.sub(r"[^a-z0-9]", "", unidecode(text).lower())
return servers
@staticmethod
def get_countries() -> list[dict]:
+26 -6
View File
@@ -5,6 +5,7 @@ from typing import Iterator, Optional
import requests
from unshackle.core.proxies.asn import describe, resolve_all, select, split_selector
from unshackle.core.proxies.proxy import Proxy
@@ -30,6 +31,7 @@ class WindscribeVPN(Proxy):
self.username = username
self.password = password
self.server_map = server_map or {}
self.last_hostname: Optional[str] = None
self.countries = self.get_countries()
@@ -47,11 +49,13 @@ class WindscribeVPN(Proxy):
- Country code: "us", "ca", "gb"
- Specific server: "sg007", "us150", "us-central-150"
- City selection: "us:seattle", "ca:toronto"
- Network selection: "fr@datacamp", "ca:toronto@-datacamp" (a leading "-" excludes)
- One server IP: "fr@195.86.24.129"
Returns None for a query WindscribeVPN cannot serve. A city with no matching server raises ValueError.
"""
# Windscribe names GB hosts "uk-NNN"; Ukraine is "ua", so "uk" is unambiguous.
query = re.sub(r"^uk(?=$|[:\d])", "gb", query.lower())
query, selector = split_selector(re.sub(r"^uk(?=$|[:\d@])", "gb", query.lower()))
city = None
if ":" in query:
@@ -59,8 +63,12 @@ class WindscribeVPN(Proxy):
city = city.strip()
server_map_key = f"{query}:{city}" if city else query
if server_map_key in self.server_map:
hostname: Optional[str] = self.server_map[server_map_key]
if selector:
if not re.fullmatch(r"[a-z]+", query):
raise ValueError(f"'{query}' is already one WindscribeVPN server, so it takes no '@' network selector.")
hostname: Optional[str] = self.get_random_server(query, city, selector)
elif server_map_key in self.server_map:
hostname = self.server_map[server_map_key]
elif query in self.server_map:
hostname = self.server_map[query]
else:
@@ -77,9 +85,13 @@ class WindscribeVPN(Proxy):
if not hostname:
return None
hostname = hostname.split(":")[0]
hostname = self.last_hostname = hostname.split(":")[0]
return f"https://{self.username}:{self.password}@{hostname}:443"
def last_connection_display(self) -> Optional[str]:
"""Name the last server with its IP and network, so a blocked network can be excluded with '@-'."""
return describe(self.last_hostname) if self.last_hostname else None
def iter_hostnames(self) -> Iterator[str]:
"""Yield every known server hostname."""
for location in self.countries:
@@ -107,19 +119,23 @@ class WindscribeVPN(Proxy):
return hostname
return None
def get_random_server(self, country_code: str, city: Optional[str] = None) -> Optional[str]:
def get_random_server(
self, country_code: str, city: Optional[str] = None, selector: Optional[str] = None
) -> Optional[str]:
"""
Get a random server hostname for a country, optionally filtered by city.
Args:
country_code: The country code (e.g., "us", "ca")
city: Optional city name to filter by (case-insensitive)
selector: Optional network selector, such as "datacamp" or "-datacamp" (see asn.select)
Returns:
A random hostname from matching servers, or None if the country has no servers.
Raises:
ValueError: If you give a city and no server in that country matches it.
ValueError: If you give a city and no server in that country matches it, or a selector
and no server is on a matching network.
"""
hostnames = []
@@ -135,6 +151,10 @@ class WindscribeVPN(Proxy):
if hostname := host.get("hostname"):
hostnames.append(hostname)
if hostnames and selector:
hostnames = select(resolve_all(hostnames), selector)
if not hostnames:
raise ValueError(f"No WindscribeVPN server in {country_code} matches '@{selector}'.")
if hostnames:
return random.choice(hostnames)
elif city:
+3 -1
View File
@@ -916,6 +916,8 @@ def resolve_remote_proxy_arg(proxy_arg: str, providers: Optional[list] = None) -
# the providers dl or a serve already loaded, which a serve leaves empty for a key without server_proxy
providers = initialize_proxy_providers() if providers is None else providers
provider, _, query = proxy_arg.partition(":")
if provider.lower() == "surfsharkvpn" and "@" in query:
return proxy_arg
if provider.lower() == "controld" and query:
controld = find_provider(providers, "controld")
uri = controld.get_remote_proxy(query)
@@ -1281,7 +1283,7 @@ class RemoteService:
if resolved_proxy:
create_data["proxy"] = resolved_proxy
query = (self.ctx.parent.params.get("proxy_query") if self.ctx.parent else None) or proxy
country = re.match(r"^(?:[a-z]+:)?([a-z]{2})\d*$", query, re.IGNORECASE)
country = re.match(r"^(?:[a-z]+:)?([a-z]{2})\d*(?:@.*)?$", query, re.IGNORECASE)
if country:
create_data["proxy_region"] = country.group(1).lower()
self.require_reachable_proxy(create_data.get("proxy"))