| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import socket |
| 4 |
import threading |
| 5 |
import typing |
| 6 |
from socket import getaddrinfo as real_getaddrinfo |
| 7 |
from socket import timeout as SocketTimeout |
| 8 |
from test import SHORT_TIMEOUT |
| 9 |
from unittest.mock import Mock, patch |
| 10 |
|
| 11 |
import pytest |
| 12 |
import socks as py_socks # type: ignore[import-untyped] |
| 13 |
|
| 14 |
from dummyserver.socketserver import DEFAULT_CA, DEFAULT_CERTS |
| 15 |
from dummyserver.testcase import IPV4SocketDummyServerTestCase |
| 16 |
from urllib3.contrib import socks |
| 17 |
from urllib3.exceptions import ConnectTimeoutError, NewConnectionError |
| 18 |
|
| 19 |
try: |
| 20 |
import ssl |
| 21 |
|
| 22 |
from urllib3.util import ssl_ as better_ssl |
| 23 |
|
| 24 |
HAS_SSL = True |
| 25 |
except ImportError: |
| 26 |
ssl = None # type: ignore[assignment] |
| 27 |
better_ssl = None # type: ignore[assignment] |
| 28 |
HAS_SSL = False |
| 29 |
|
| 30 |
|
| 31 |
SOCKS_NEGOTIATION_NONE = b"\x00" |
| 32 |
SOCKS_NEGOTIATION_PASSWORD = b"\x02" |
| 33 |
|
| 34 |
SOCKS_VERSION_SOCKS4 = b"\x04" |
| 35 |
SOCKS_VERSION_SOCKS5 = b"\x05" |
| 36 |
|
| 37 |
|
| 38 |
def _get_free_port(host: str) -> int: |
| 39 |
""" |
| 40 |
Gets a free port by opening a socket, binding it, checking the assigned |
| 41 |
port, and then closing it. |
| 42 |
""" |
| 43 |
s = socket.socket() |
| 44 |
s.bind((host, 0)) |
| 45 |
port = s.getsockname()[1] |
| 46 |
s.close() |
| 47 |
return port # type: ignore[no-any-return] |
| 48 |
|
| 49 |
|
| 50 |
def _read_exactly(sock: socket.socket, amt: int) -> bytes: |
| 51 |
""" |
| 52 |
Read *exactly* ``amt`` bytes from the socket ``sock``. |
| 53 |
""" |
| 54 |
data = b"" |
| 55 |
|
| 56 |
while amt > 0: |
| 57 |
chunk = sock.recv(amt) |
| 58 |
data += chunk |
| 59 |
amt -= len(chunk) |
| 60 |
|
| 61 |
return data |
| 62 |
|
| 63 |
|
| 64 |
def _read_until(sock: socket.socket, char: bytes) -> bytes: |
| 65 |
""" |
| 66 |
Read from the socket until the character is received. |
| 67 |
""" |
| 68 |
chunks = [] |
| 69 |
while True: |
| 70 |
chunk = sock.recv(1) |
| 71 |
chunks.append(chunk) |
| 72 |
if chunk == char: |
| 73 |
break |
| 74 |
|
| 75 |
return b"".join(chunks) |
| 76 |
|
| 77 |
|
| 78 |
def _address_from_socket(sock: socket.socket) -> bytes | str: |
| 79 |
""" |
| 80 |
Returns the address from the SOCKS socket |
| 81 |
""" |
| 82 |
addr_type = sock.recv(1) |
| 83 |
|
| 84 |
if addr_type == b"\x01": |
| 85 |
ipv4_addr = _read_exactly(sock, 4) |
| 86 |
return socket.inet_ntoa(ipv4_addr) |
| 87 |
elif addr_type == b"\x04": |
| 88 |
ipv6_addr = _read_exactly(sock, 16) |
| 89 |
return socket.inet_ntop(socket.AF_INET6, ipv6_addr) |
| 90 |
elif addr_type == b"\x03": |
| 91 |
addr_len = ord(sock.recv(1)) |
| 92 |
return _read_exactly(sock, addr_len) |
| 93 |
else: |
| 94 |
raise RuntimeError(f"Unexpected addr type: {addr_type!r}") |
| 95 |
|
| 96 |
|
| 97 |
def _set_up_fake_getaddrinfo(monkeypatch: pytest.MonkeyPatch) -> None: |
| 98 |
# Work around https://github.com/urllib3/urllib3/pull/2034 |
| 99 |
# Nothing prevents localhost to point to two different IPs. For example, in the |
| 100 |
# Ubuntu set up by GitHub Actions, localhost points both to 127.0.0.1 and ::1. |
| 101 |
# |
| 102 |
# In case of failure, PySocks will try the same request on both IPs, but our |
| 103 |
# handle_socks[45]_negotiation functions don't handle retries, which leads either to |
| 104 |
# a deadlock or a timeout in case of a failure on the first address. |
| 105 |
# |
| 106 |
# However, some tests need to exercise failure. We don't want retries there, but |
| 107 |
# can't affect PySocks retries via its API. Instead, we monkeypatch PySocks so that |
| 108 |
# it only sees a single address, which effectively disables retries. |
| 109 |
def fake_getaddrinfo(addr: str, port: int, family: int, socket_type: int) -> list[ |
| 110 |
tuple[ |
| 111 |
socket.AddressFamily, |
| 112 |
socket.SocketKind, |
| 113 |
int, |
| 114 |
str, |
| 115 |
tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes], |
| 116 |
] |
| 117 |
]: |
| 118 |
gai_list = real_getaddrinfo(addr, port, family, socket_type) |
| 119 |
gai_list = [gai for gai in gai_list if gai[0] == socket.AF_INET] |
| 120 |
return gai_list[:1] |
| 121 |
|
| 122 |
monkeypatch.setattr(py_socks.socket, "getaddrinfo", fake_getaddrinfo) |
| 123 |
|
| 124 |
|
| 125 |
def handle_socks5_negotiation( |
| 126 |
sock: socket.socket, |
| 127 |
negotiate: bool, |
| 128 |
username: bytes | None = None, |
| 129 |
password: bytes | None = None, |
| 130 |
) -> typing.Generator[tuple[bytes | str, int], bool, None]: |
| 131 |
""" |
| 132 |
Handle the SOCKS5 handshake. |
| 133 |
|
| 134 |
Returns a generator object that allows us to break the handshake into |
| 135 |
steps so that the test code can intervene at certain useful points. |
| 136 |
""" |
| 137 |
received_version = sock.recv(1) |
| 138 |
assert received_version == SOCKS_VERSION_SOCKS5 |
| 139 |
nmethods = ord(sock.recv(1)) |
| 140 |
methods = _read_exactly(sock, nmethods) |
| 141 |
|
| 142 |
if negotiate: |
| 143 |
assert SOCKS_NEGOTIATION_PASSWORD in methods |
| 144 |
send_data = SOCKS_VERSION_SOCKS5 + SOCKS_NEGOTIATION_PASSWORD |
| 145 |
sock.sendall(send_data) |
| 146 |
|
| 147 |
# This is the password negotiation. |
| 148 |
negotiation_version = sock.recv(1) |
| 149 |
assert negotiation_version == b"\x01" |
| 150 |
ulen = ord(sock.recv(1)) |
| 151 |
provided_username = _read_exactly(sock, ulen) |
| 152 |
plen = ord(sock.recv(1)) |
| 153 |
provided_password = _read_exactly(sock, plen) |
| 154 |
|
| 155 |
if username == provided_username and password == provided_password: |
| 156 |
sock.sendall(b"\x01\x00") |
| 157 |
else: |
| 158 |
sock.sendall(b"\x01\x01") |
| 159 |
sock.close() |
| 160 |
return |
| 161 |
else: |
| 162 |
assert SOCKS_NEGOTIATION_NONE in methods |
| 163 |
send_data = SOCKS_VERSION_SOCKS5 + SOCKS_NEGOTIATION_NONE |
| 164 |
sock.sendall(send_data) |
| 165 |
|
| 166 |
# Client sends where they want to go. |
| 167 |
received_version = sock.recv(1) |
| 168 |
command = sock.recv(1) |
| 169 |
reserved = sock.recv(1) |
| 170 |
addr = _address_from_socket(sock) |
| 171 |
port_raw = _read_exactly(sock, 2) |
| 172 |
port = (ord(port_raw[0:1]) << 8) + (ord(port_raw[1:2])) |
| 173 |
|
| 174 |
# Check some basic stuff. |
| 175 |
assert received_version == SOCKS_VERSION_SOCKS5 |
| 176 |
assert command == b"\x01" # Only support connect, not bind. |
| 177 |
assert reserved == b"\x00" |
| 178 |
|
| 179 |
# Yield the address port tuple. |
| 180 |
succeed = yield addr, port |
| 181 |
|
| 182 |
if succeed: |
| 183 |
# Hard-coded response for now. |
| 184 |
response = SOCKS_VERSION_SOCKS5 + b"\x00\x00\x01\x7f\x00\x00\x01\xea\x60" |
| 185 |
else: |
| 186 |
# Hard-coded response for now. |
| 187 |
response = SOCKS_VERSION_SOCKS5 + b"\x01\00" |
| 188 |
|
| 189 |
sock.sendall(response) |
| 190 |
|
| 191 |
|
| 192 |
def handle_socks4_negotiation( |
| 193 |
sock: socket.socket, username: bytes | None = None |
| 194 |
) -> typing.Generator[tuple[bytes | str, int], bool, None]: |
| 195 |
""" |
| 196 |
Handle the SOCKS4 handshake. |
| 197 |
|
| 198 |
Returns a generator object that allows us to break the handshake into |
| 199 |
steps so that the test code can intervene at certain useful points. |
| 200 |
""" |
| 201 |
received_version = sock.recv(1) |
| 202 |
command = sock.recv(1) |
| 203 |
port_raw = _read_exactly(sock, 2) |
| 204 |
port = (ord(port_raw[0:1]) << 8) + (ord(port_raw[1:2])) |
| 205 |
addr_raw = _read_exactly(sock, 4) |
| 206 |
provided_username = _read_until(sock, b"\x00")[:-1] # Strip trailing null. |
| 207 |
|
| 208 |
addr: bytes | str |
| 209 |
if addr_raw == b"\x00\x00\x00\x01": |
| 210 |
# Magic string: means DNS name. |
| 211 |
addr = _read_until(sock, b"\x00")[:-1] # Strip trailing null. |
| 212 |
else: |
| 213 |
addr = socket.inet_ntoa(addr_raw) |
| 214 |
|
| 215 |
# Check some basic stuff. |
| 216 |
assert received_version == SOCKS_VERSION_SOCKS4 |
| 217 |
assert command == b"\x01" # Only support connect, not bind. |
| 218 |
|
| 219 |
if username is not None and username != provided_username: |
| 220 |
sock.sendall(b"\x00\x5d\x00\x00\x00\x00\x00\x00") |
| 221 |
sock.close() |
| 222 |
return |
| 223 |
|
| 224 |
# Yield the address port tuple. |
| 225 |
succeed = yield addr, port |
| 226 |
|
| 227 |
if succeed: |
| 228 |
response = b"\x00\x5a\xea\x60\x7f\x00\x00\x01" |
| 229 |
else: |
| 230 |
response = b"\x00\x5b\x00\x00\x00\x00\x00\x00" |
| 231 |
|
| 232 |
sock.sendall(response) |
| 233 |
|
| 234 |
|
| 235 |
class TestSOCKSProxyManager: |
| 236 |
def test_invalid_socks_version_is_valueerror(self) -> None: |
| 237 |
with pytest.raises(ValueError, match="Unable to determine SOCKS version"): |
| 238 |
socks.SOCKSProxyManager(proxy_url="http://example.org") |
| 239 |
|
| 240 |
|
| 241 |
class TestSocks5Proxy(IPV4SocketDummyServerTestCase): |
| 242 |
""" |
| 243 |
Test the SOCKS proxy in SOCKS5 mode. |
| 244 |
""" |
| 245 |
|
| 246 |
def test_basic_request(self) -> None: |
| 247 |
def request_handler(listener: socket.socket) -> None: |
| 248 |
sock = listener.accept()[0] |
| 249 |
|
| 250 |
handler = handle_socks5_negotiation(sock, negotiate=False) |
| 251 |
addr, port = next(handler) |
| 252 |
|
| 253 |
assert addr == "16.17.18.19" |
| 254 |
assert port == 80 |
| 255 |
with pytest.raises(StopIteration): |
| 256 |
handler.send(True) |
| 257 |
|
| 258 |
while True: |
| 259 |
buf = sock.recv(65535) |
| 260 |
if buf.endswith(b"\r\n\r\n"): |
| 261 |
break |
| 262 |
|
| 263 |
sock.sendall( |
| 264 |
b"HTTP/1.1 200 OK\r\n" |
| 265 |
b"Server: SocksTestServer\r\n" |
| 266 |
b"Content-Length: 0\r\n" |
| 267 |
b"\r\n" |
| 268 |
) |
| 269 |
sock.close() |
| 270 |
|
| 271 |
self._start_server(request_handler) |
| 272 |
proxy_url = f"socks5://{self.host}:{self.port}" |
| 273 |
with socks.SOCKSProxyManager(proxy_url) as pm: |
| 274 |
response = pm.request("GET", "http://16.17.18.19") |
| 275 |
|
| 276 |
assert response.status == 200 |
| 277 |
assert response.data == b"" |
| 278 |
assert response.headers["Server"] == "SocksTestServer" |
| 279 |
|
| 280 |
def test_local_dns(self) -> None: |
| 281 |
def request_handler(listener: socket.socket) -> None: |
| 282 |
sock = listener.accept()[0] |
| 283 |
|
| 284 |
handler = handle_socks5_negotiation(sock, negotiate=False) |
| 285 |
addr, port = next(handler) |
| 286 |
|
| 287 |
assert addr in ["127.0.0.1", "::1"] |
| 288 |
assert port == 80 |
| 289 |
with pytest.raises(StopIteration): |
| 290 |
handler.send(True) |
| 291 |
|
| 292 |
while True: |
| 293 |
buf = sock.recv(65535) |
| 294 |
if buf.endswith(b"\r\n\r\n"): |
| 295 |
break |
| 296 |
|
| 297 |
sock.sendall( |
| 298 |
b"HTTP/1.1 200 OK\r\n" |
| 299 |
b"Server: SocksTestServer\r\n" |
| 300 |
b"Content-Length: 0\r\n" |
| 301 |
b"\r\n" |
| 302 |
) |
| 303 |
sock.close() |
| 304 |
|
| 305 |
self._start_server(request_handler) |
| 306 |
proxy_url = f"socks5://{self.host}:{self.port}" |
| 307 |
with socks.SOCKSProxyManager(proxy_url) as pm: |
| 308 |
response = pm.request("GET", "http://localhost") |
| 309 |
|
| 310 |
assert response.status == 200 |
| 311 |
assert response.data == b"" |
| 312 |
assert response.headers["Server"] == "SocksTestServer" |
| 313 |
|
| 314 |
def test_correct_header_line(self) -> None: |
| 315 |
def request_handler(listener: socket.socket) -> None: |
| 316 |
sock = listener.accept()[0] |
| 317 |
|
| 318 |
handler = handle_socks5_negotiation(sock, negotiate=False) |
| 319 |
addr, port = next(handler) |
| 320 |
|
| 321 |
assert addr == b"example.com" |
| 322 |
assert port == 80 |
| 323 |
with pytest.raises(StopIteration): |
| 324 |
handler.send(True) |
| 325 |
|
| 326 |
buf = b"" |
| 327 |
while True: |
| 328 |
buf += sock.recv(65535) |
| 329 |
if buf.endswith(b"\r\n\r\n"): |
| 330 |
break |
| 331 |
|
| 332 |
assert buf.startswith(b"GET / HTTP/1.1") |
| 333 |
assert b"Host: example.com" in buf |
| 334 |
|
| 335 |
sock.sendall( |
| 336 |
b"HTTP/1.1 200 OK\r\n" |
| 337 |
b"Server: SocksTestServer\r\n" |
| 338 |
b"Content-Length: 0\r\n" |
| 339 |
b"\r\n" |
| 340 |
) |
| 341 |
sock.close() |
| 342 |
|
| 343 |
self._start_server(request_handler) |
| 344 |
proxy_url = f"socks5h://{self.host}:{self.port}" |
| 345 |
with socks.SOCKSProxyManager(proxy_url) as pm: |
| 346 |
response = pm.request("GET", "http://example.com") |
| 347 |
assert response.status == 200 |
| 348 |
|
| 349 |
def test_connection_timeouts(self) -> None: |
| 350 |
event = threading.Event() |
| 351 |
|
| 352 |
def request_handler(listener: socket.socket) -> None: |
| 353 |
event.wait() |
| 354 |
|
| 355 |
self._start_server(request_handler) |
| 356 |
proxy_url = f"socks5h://{self.host}:{self.port}" |
| 357 |
with socks.SOCKSProxyManager(proxy_url) as pm: |
| 358 |
with pytest.raises(ConnectTimeoutError): |
| 359 |
pm.request( |
| 360 |
"GET", "http://example.com", timeout=SHORT_TIMEOUT, retries=False |
| 361 |
) |
| 362 |
event.set() |
| 363 |
|
| 364 |
@patch("socks.create_connection") |
| 365 |
def test_socket_timeout(self, create_connection: Mock) -> None: |
| 366 |
create_connection.side_effect = SocketTimeout() |
| 367 |
proxy_url = f"socks5h://{self.host}:{self.port}" |
| 368 |
with socks.SOCKSProxyManager(proxy_url) as pm: |
| 369 |
with pytest.raises(ConnectTimeoutError, match="timed out"): |
| 370 |
pm.request("GET", "http://example.com", retries=False) |
| 371 |
|
| 372 |
def test_connection_failure(self) -> None: |
| 373 |
event = threading.Event() |
| 374 |
|
| 375 |
def request_handler(listener: socket.socket) -> None: |
| 376 |
listener.close() |
| 377 |
event.set() |
| 378 |
|
| 379 |
self._start_server(request_handler) |
| 380 |
proxy_url = f"socks5h://{self.host}:{self.port}" |
| 381 |
with socks.SOCKSProxyManager(proxy_url) as pm: |
| 382 |
event.wait() |
| 383 |
with pytest.raises(NewConnectionError): |
| 384 |
pm.request("GET", "http://example.com", retries=False) |
| 385 |
|
| 386 |
def test_proxy_rejection(self, monkeypatch: pytest.MonkeyPatch) -> None: |
| 387 |
_set_up_fake_getaddrinfo(monkeypatch) |
| 388 |
evt = threading.Event() |
| 389 |
|
| 390 |
def request_handler(listener: socket.socket) -> None: |
| 391 |
sock = listener.accept()[0] |
| 392 |
|
| 393 |
handler = handle_socks5_negotiation(sock, negotiate=False) |
| 394 |
addr, port = next(handler) |
| 395 |
with pytest.raises(StopIteration): |
| 396 |
handler.send(False) |
| 397 |
|
| 398 |
evt.wait() |
| 399 |
sock.close() |
| 400 |
|
| 401 |
self._start_server(request_handler) |
| 402 |
proxy_url = f"socks5h://{self.host}:{self.port}" |
| 403 |
with socks.SOCKSProxyManager(proxy_url) as pm: |
| 404 |
with pytest.raises(NewConnectionError): |
| 405 |
pm.request("GET", "http://example.com", retries=False) |
| 406 |
evt.set() |
| 407 |
|
| 408 |
def test_socks_with_password(self) -> None: |
| 409 |
def request_handler(listener: socket.socket) -> None: |
| 410 |
sock = listener.accept()[0] |
| 411 |
|
| 412 |
handler = handle_socks5_negotiation( |
| 413 |
sock, negotiate=True, username=b"user", password=b"pass" |
| 414 |
) |
| 415 |
addr, port = next(handler) |
| 416 |
|
| 417 |
assert addr == "16.17.18.19" |
| 418 |
assert port == 80 |
| 419 |
with pytest.raises(StopIteration): |
| 420 |
handler.send(True) |
| 421 |
|
| 422 |
while True: |
| 423 |
buf = sock.recv(65535) |
| 424 |
if buf.endswith(b"\r\n\r\n"): |
| 425 |
break |
| 426 |
|
| 427 |
sock.sendall( |
| 428 |
b"HTTP/1.1 200 OK\r\n" |
| 429 |
b"Server: SocksTestServer\r\n" |
| 430 |
b"Content-Length: 0\r\n" |
| 431 |
b"\r\n" |
| 432 |
) |
| 433 |
sock.close() |
| 434 |
|
| 435 |
self._start_server(request_handler) |
| 436 |
proxy_url = f"socks5://{self.host}:{self.port}" |
| 437 |
with socks.SOCKSProxyManager(proxy_url, username="user", password="pass") as pm: |
| 438 |
response = pm.request("GET", "http://16.17.18.19") |
| 439 |
|
| 440 |
assert response.status == 200 |
| 441 |
assert response.data == b"" |
| 442 |
assert response.headers["Server"] == "SocksTestServer" |
| 443 |
|
| 444 |
def test_socks_with_auth_in_url(self) -> None: |
| 445 |
""" |
| 446 |
Test when we have auth info in url, i.e. |
| 447 |
socks5://user:pass@host:port and no username/password as params |
| 448 |
""" |
| 449 |
|
| 450 |
def request_handler(listener: socket.socket) -> None: |
| 451 |
sock = listener.accept()[0] |
| 452 |
|
| 453 |
handler = handle_socks5_negotiation( |
| 454 |
sock, negotiate=True, username=b"user", password=b"pass" |
| 455 |
) |
| 456 |
addr, port = next(handler) |
| 457 |
|
| 458 |
assert addr == "16.17.18.19" |
| 459 |
assert port == 80 |
| 460 |
with pytest.raises(StopIteration): |
| 461 |
handler.send(True) |
| 462 |
|
| 463 |
while True: |
| 464 |
buf = sock.recv(65535) |
| 465 |
if buf.endswith(b"\r\n\r\n"): |
| 466 |
break |
| 467 |
|
| 468 |
sock.sendall( |
| 469 |
b"HTTP/1.1 200 OK\r\n" |
| 470 |
b"Server: SocksTestServer\r\n" |
| 471 |
b"Content-Length: 0\r\n" |
| 472 |
b"\r\n" |
| 473 |
) |
| 474 |
sock.close() |
| 475 |
|
| 476 |
self._start_server(request_handler) |
| 477 |
proxy_url = f"socks5://user:pass@{self.host}:{self.port}" |
| 478 |
with socks.SOCKSProxyManager(proxy_url) as pm: |
| 479 |
response = pm.request("GET", "http://16.17.18.19") |
| 480 |
|
| 481 |
assert response.status == 200 |
| 482 |
assert response.data == b"" |
| 483 |
assert response.headers["Server"] == "SocksTestServer" |
| 484 |
|
| 485 |
def test_socks_with_invalid_password(self, monkeypatch: pytest.MonkeyPatch) -> None: |
| 486 |
_set_up_fake_getaddrinfo(monkeypatch) |
| 487 |
|
| 488 |
def request_handler(listener: socket.socket) -> None: |
| 489 |
sock = listener.accept()[0] |
| 490 |
|
| 491 |
handler = handle_socks5_negotiation( |
| 492 |
sock, negotiate=True, username=b"user", password=b"pass" |
| 493 |
) |
| 494 |
with pytest.raises(StopIteration): |
| 495 |
next(handler) |
| 496 |
|
| 497 |
self._start_server(request_handler) |
| 498 |
proxy_url = f"socks5h://{self.host}:{self.port}" |
| 499 |
with socks.SOCKSProxyManager( |
| 500 |
proxy_url, username="user", password="badpass" |
| 501 |
) as pm: |
| 502 |
with pytest.raises( |
| 503 |
NewConnectionError, match="SOCKS5 authentication failed" |
| 504 |
): |
| 505 |
pm.request("GET", "http://example.com", retries=False) |
| 506 |
|
| 507 |
def test_source_address_works(self) -> None: |
| 508 |
expected_port = _get_free_port(self.host) |
| 509 |
|
| 510 |
def request_handler(listener: socket.socket) -> None: |
| 511 |
sock = listener.accept()[0] |
| 512 |
assert sock.getpeername()[0] == "127.0.0.1" |
| 513 |
assert sock.getpeername()[1] == expected_port |
| 514 |
|
| 515 |
handler = handle_socks5_negotiation(sock, negotiate=False) |
| 516 |
addr, port = next(handler) |
| 517 |
|
| 518 |
assert addr == "16.17.18.19" |
| 519 |
assert port == 80 |
| 520 |
with pytest.raises(StopIteration): |
| 521 |
handler.send(True) |
| 522 |
|
| 523 |
while True: |
| 524 |
buf = sock.recv(65535) |
| 525 |
if buf.endswith(b"\r\n\r\n"): |
| 526 |
break |
| 527 |
|
| 528 |
sock.sendall( |
| 529 |
b"HTTP/1.1 200 OK\r\n" |
| 530 |
b"Server: SocksTestServer\r\n" |
| 531 |
b"Content-Length: 0\r\n" |
| 532 |
b"\r\n" |
| 533 |
) |
| 534 |
sock.close() |
| 535 |
|
| 536 |
self._start_server(request_handler) |
| 537 |
proxy_url = f"socks5://{self.host}:{self.port}" |
| 538 |
with socks.SOCKSProxyManager( |
| 539 |
proxy_url, source_address=("127.0.0.1", expected_port) |
| 540 |
) as pm: |
| 541 |
response = pm.request("GET", "http://16.17.18.19") |
| 542 |
assert response.status == 200 |
| 543 |
|
| 544 |
|
| 545 |
class TestSOCKS4Proxy(IPV4SocketDummyServerTestCase): |
| 546 |
""" |
| 547 |
Test the SOCKS proxy in SOCKS4 mode. |
| 548 |
|
| 549 |
Has relatively fewer tests than the SOCKS5 case, mostly because once the |
| 550 |
negotiation is done the two cases behave identically. |
| 551 |
""" |
| 552 |
|
| 553 |
def test_basic_request(self) -> None: |
| 554 |
def request_handler(listener: socket.socket) -> None: |
| 555 |
sock = listener.accept()[0] |
| 556 |
|
| 557 |
handler = handle_socks4_negotiation(sock) |
| 558 |
addr, port = next(handler) |
| 559 |
|
| 560 |
assert addr == "16.17.18.19" |
| 561 |
assert port == 80 |
| 562 |
with pytest.raises(StopIteration): |
| 563 |
handler.send(True) |
| 564 |
|
| 565 |
while True: |
| 566 |
buf = sock.recv(65535) |
| 567 |
if buf.endswith(b"\r\n\r\n"): |
| 568 |
break |
| 569 |
|
| 570 |
sock.sendall( |
| 571 |
b"HTTP/1.1 200 OK\r\n" |
| 572 |
b"Server: SocksTestServer\r\n" |
| 573 |
b"Content-Length: 0\r\n" |
| 574 |
b"\r\n" |
| 575 |
) |
| 576 |
sock.close() |
| 577 |
|
| 578 |
self._start_server(request_handler) |
| 579 |
proxy_url = f"socks4://{self.host}:{self.port}" |
| 580 |
with socks.SOCKSProxyManager(proxy_url) as pm: |
| 581 |
response = pm.request("GET", "http://16.17.18.19") |
| 582 |
|
| 583 |
assert response.status == 200 |
| 584 |
assert response.headers["Server"] == "SocksTestServer" |
| 585 |
assert response.data == b"" |
| 586 |
|
| 587 |
def test_local_dns(self) -> None: |
| 588 |
def request_handler(listener: socket.socket) -> None: |
| 589 |
sock = listener.accept()[0] |
| 590 |
|
| 591 |
handler = handle_socks4_negotiation(sock) |
| 592 |
addr, port = next(handler) |
| 593 |
|
| 594 |
assert addr == "127.0.0.1" |
| 595 |
assert port == 80 |
| 596 |
with pytest.raises(StopIteration): |
| 597 |
handler.send(True) |
| 598 |
|
| 599 |
while True: |
| 600 |
buf = sock.recv(65535) |
| 601 |
if buf.endswith(b"\r\n\r\n"): |
| 602 |
break |
| 603 |
|
| 604 |
sock.sendall( |
| 605 |
b"HTTP/1.1 200 OK\r\n" |
| 606 |
b"Server: SocksTestServer\r\n" |
| 607 |
b"Content-Length: 0\r\n" |
| 608 |
b"\r\n" |
| 609 |
) |
| 610 |
sock.close() |
| 611 |
|
| 612 |
self._start_server(request_handler) |
| 613 |
proxy_url = f"socks4://{self.host}:{self.port}" |
| 614 |
with socks.SOCKSProxyManager(proxy_url) as pm: |
| 615 |
response = pm.request("GET", "http://localhost") |
| 616 |
|
| 617 |
assert response.status == 200 |
| 618 |
assert response.headers["Server"] == "SocksTestServer" |
| 619 |
assert response.data == b"" |
| 620 |
|
| 621 |
def test_correct_header_line(self) -> None: |
| 622 |
def request_handler(listener: socket.socket) -> None: |
| 623 |
sock = listener.accept()[0] |
| 624 |
|
| 625 |
handler = handle_socks4_negotiation(sock) |
| 626 |
addr, port = next(handler) |
| 627 |
|
| 628 |
assert addr == b"example.com" |
| 629 |
assert port == 80 |
| 630 |
with pytest.raises(StopIteration): |
| 631 |
handler.send(True) |
| 632 |
|
| 633 |
buf = b"" |
| 634 |
while True: |
| 635 |
buf += sock.recv(65535) |
| 636 |
if buf.endswith(b"\r\n\r\n"): |
| 637 |
break |
| 638 |
|
| 639 |
assert buf.startswith(b"GET / HTTP/1.1") |
| 640 |
assert b"Host: example.com" in buf |
| 641 |
|
| 642 |
sock.sendall( |
| 643 |
b"HTTP/1.1 200 OK\r\n" |
| 644 |
b"Server: SocksTestServer\r\n" |
| 645 |
b"Content-Length: 0\r\n" |
| 646 |
b"\r\n" |
| 647 |
) |
| 648 |
sock.close() |
| 649 |
|
| 650 |
self._start_server(request_handler) |
| 651 |
proxy_url = f"socks4a://{self.host}:{self.port}" |
| 652 |
with socks.SOCKSProxyManager(proxy_url) as pm: |
| 653 |
response = pm.request("GET", "http://example.com") |
| 654 |
assert response.status == 200 |
| 655 |
|
| 656 |
def test_proxy_rejection(self, monkeypatch: pytest.MonkeyPatch) -> None: |
| 657 |
_set_up_fake_getaddrinfo(monkeypatch) |
| 658 |
evt = threading.Event() |
| 659 |
|
| 660 |
def request_handler(listener: socket.socket) -> None: |
| 661 |
sock = listener.accept()[0] |
| 662 |
|
| 663 |
handler = handle_socks4_negotiation(sock) |
| 664 |
addr, port = next(handler) |
| 665 |
with pytest.raises(StopIteration): |
| 666 |
handler.send(False) |
| 667 |
|
| 668 |
evt.wait() |
| 669 |
sock.close() |
| 670 |
|
| 671 |
self._start_server(request_handler) |
| 672 |
proxy_url = f"socks4a://{self.host}:{self.port}" |
| 673 |
with socks.SOCKSProxyManager(proxy_url) as pm: |
| 674 |
with pytest.raises(NewConnectionError): |
| 675 |
pm.request("GET", "http://example.com", retries=False) |
| 676 |
evt.set() |
| 677 |
|
| 678 |
def test_socks4_with_username(self) -> None: |
| 679 |
def request_handler(listener: socket.socket) -> None: |
| 680 |
sock = listener.accept()[0] |
| 681 |
|
| 682 |
handler = handle_socks4_negotiation(sock, username=b"user") |
| 683 |
addr, port = next(handler) |
| 684 |
|
| 685 |
assert addr == "16.17.18.19" |
| 686 |
assert port == 80 |
| 687 |
with pytest.raises(StopIteration): |
| 688 |
handler.send(True) |
| 689 |
|
| 690 |
while True: |
| 691 |
buf = sock.recv(65535) |
| 692 |
if buf.endswith(b"\r\n\r\n"): |
| 693 |
break |
| 694 |
|
| 695 |
sock.sendall( |
| 696 |
b"HTTP/1.1 200 OK\r\n" |
| 697 |
b"Server: SocksTestServer\r\n" |
| 698 |
b"Content-Length: 0\r\n" |
| 699 |
b"\r\n" |
| 700 |
) |
| 701 |
sock.close() |
| 702 |
|
| 703 |
self._start_server(request_handler) |
| 704 |
proxy_url = f"socks4://{self.host}:{self.port}" |
| 705 |
with socks.SOCKSProxyManager(proxy_url, username="user") as pm: |
| 706 |
response = pm.request("GET", "http://16.17.18.19") |
| 707 |
|
| 708 |
assert response.status == 200 |
| 709 |
assert response.data == b"" |
| 710 |
assert response.headers["Server"] == "SocksTestServer" |
| 711 |
|
| 712 |
def test_socks_with_invalid_username(self) -> None: |
| 713 |
def request_handler(listener: socket.socket) -> None: |
| 714 |
sock = listener.accept()[0] |
| 715 |
|
| 716 |
handler = handle_socks4_negotiation(sock, username=b"user") |
| 717 |
next(handler, None) |
| 718 |
|
| 719 |
self._start_server(request_handler) |
| 720 |
proxy_url = f"socks4a://{self.host}:{self.port}" |
| 721 |
with socks.SOCKSProxyManager(proxy_url, username="baduser") as pm: |
| 722 |
with pytest.raises(NewConnectionError, match="different user-ids"): |
| 723 |
pm.request("GET", "http://example.com", retries=False) |
| 724 |
|
| 725 |
|
| 726 |
class TestSOCKSWithTLS(IPV4SocketDummyServerTestCase): |
| 727 |
""" |
| 728 |
Test that TLS behaves properly for SOCKS proxies. |
| 729 |
""" |
| 730 |
|
| 731 |
@pytest.mark.skipif(not HAS_SSL, reason="No TLS available") |
| 732 |
def test_basic_request(self) -> None: |
| 733 |
def request_handler(listener: socket.socket) -> None: |
| 734 |
sock = listener.accept()[0] |
| 735 |
|
| 736 |
handler = handle_socks5_negotiation(sock, negotiate=False) |
| 737 |
addr, port = next(handler) |
| 738 |
|
| 739 |
assert addr == b"localhost" |
| 740 |
assert port == 443 |
| 741 |
with pytest.raises(StopIteration): |
| 742 |
handler.send(True) |
| 743 |
|
| 744 |
# Wrap in TLS |
| 745 |
context = better_ssl.SSLContext(ssl.PROTOCOL_SSLv23) # type: ignore[misc] |
| 746 |
context.load_cert_chain(DEFAULT_CERTS["certfile"], DEFAULT_CERTS["keyfile"]) |
| 747 |
tls = context.wrap_socket(sock, server_side=True) |
| 748 |
buf = b"" |
| 749 |
|
| 750 |
while True: |
| 751 |
buf += tls.recv(65535) |
| 752 |
if buf.endswith(b"\r\n\r\n"): |
| 753 |
break |
| 754 |
|
| 755 |
assert buf.startswith(b"GET / HTTP/1.1\r\n") |
| 756 |
|
| 757 |
tls.sendall( |
| 758 |
b"HTTP/1.1 200 OK\r\n" |
| 759 |
b"Server: SocksTestServer\r\n" |
| 760 |
b"Content-Length: 0\r\n" |
| 761 |
b"\r\n" |
| 762 |
) |
| 763 |
tls.close() |
| 764 |
sock.close() |
| 765 |
|
| 766 |
self._start_server(request_handler) |
| 767 |
proxy_url = f"socks5h://{self.host}:{self.port}" |
| 768 |
with socks.SOCKSProxyManager(proxy_url, ca_certs=DEFAULT_CA) as pm: |
| 769 |
response = pm.request("GET", "https://localhost") |
| 770 |
|
| 771 |
assert response.status == 200 |
| 772 |
assert response.data == b"" |
| 773 |
assert response.headers["Server"] == "SocksTestServer" |