Debian Codegraph @

test/contrib/test_socks.py

raw
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
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(
123 py_socks.socket, "getaddrinfo", fake_getaddrinfo # type: ignore[attr-defined]
124 )
125
126
127 def handle_socks5_negotiation(
128 sock: socket.socket,
129 negotiate: bool,
130 username: bytes | None = None,
131 password: bytes | None = None,
132 ) -> typing.Generator[tuple[bytes | str, int], bool, None]:
133 """
134 Handle the SOCKS5 handshake.
135
136 Returns a generator object that allows us to break the handshake into
137 steps so that the test code can intervene at certain useful points.
138 """
139 received_version = sock.recv(1)
140 assert received_version == SOCKS_VERSION_SOCKS5
141 nmethods = ord(sock.recv(1))
142 methods = _read_exactly(sock, nmethods)
143
144 if negotiate:
145 assert SOCKS_NEGOTIATION_PASSWORD in methods
146 send_data = SOCKS_VERSION_SOCKS5 + SOCKS_NEGOTIATION_PASSWORD
147 sock.sendall(send_data)
148
149 # This is the password negotiation.
150 negotiation_version = sock.recv(1)
151 assert negotiation_version == b"\x01"
152 ulen = ord(sock.recv(1))
153 provided_username = _read_exactly(sock, ulen)
154 plen = ord(sock.recv(1))
155 provided_password = _read_exactly(sock, plen)
156
157 if username == provided_username and password == provided_password:
158 sock.sendall(b"\x01\x00")
159 else:
160 sock.sendall(b"\x01\x01")
161 sock.close()
162 return
163 else:
164 assert SOCKS_NEGOTIATION_NONE in methods
165 send_data = SOCKS_VERSION_SOCKS5 + SOCKS_NEGOTIATION_NONE
166 sock.sendall(send_data)
167
168 # Client sends where they want to go.
169 received_version = sock.recv(1)
170 command = sock.recv(1)
171 reserved = sock.recv(1)
172 addr = _address_from_socket(sock)
173 port_raw = _read_exactly(sock, 2)
174 port = (ord(port_raw[0:1]) << 8) + (ord(port_raw[1:2]))
175
176 # Check some basic stuff.
177 assert received_version == SOCKS_VERSION_SOCKS5
178 assert command == b"\x01" # Only support connect, not bind.
179 assert reserved == b"\x00"
180
181 # Yield the address port tuple.
182 succeed = yield addr, port
183
184 if succeed:
185 # Hard-coded response for now.
186 response = SOCKS_VERSION_SOCKS5 + b"\x00\x00\x01\x7f\x00\x00\x01\xea\x60"
187 else:
188 # Hard-coded response for now.
189 response = SOCKS_VERSION_SOCKS5 + b"\x01\00"
190
191 sock.sendall(response)
192
193
194 def handle_socks4_negotiation(
195 sock: socket.socket, username: bytes | None = None
196 ) -> typing.Generator[tuple[bytes | str, int], bool, None]:
197 """
198 Handle the SOCKS4 handshake.
199
200 Returns a generator object that allows us to break the handshake into
201 steps so that the test code can intervene at certain useful points.
202 """
203 received_version = sock.recv(1)
204 command = sock.recv(1)
205 port_raw = _read_exactly(sock, 2)
206 port = (ord(port_raw[0:1]) << 8) + (ord(port_raw[1:2]))
207 addr_raw = _read_exactly(sock, 4)
208 provided_username = _read_until(sock, b"\x00")[:-1] # Strip trailing null.
209
210 addr: bytes | str
211 if addr_raw == b"\x00\x00\x00\x01":
212 # Magic string: means DNS name.
213 addr = _read_until(sock, b"\x00")[:-1] # Strip trailing null.
214 else:
215 addr = socket.inet_ntoa(addr_raw)
216
217 # Check some basic stuff.
218 assert received_version == SOCKS_VERSION_SOCKS4
219 assert command == b"\x01" # Only support connect, not bind.
220
221 if username is not None and username != provided_username:
222 sock.sendall(b"\x00\x5d\x00\x00\x00\x00\x00\x00")
223 sock.close()
224 return
225
226 # Yield the address port tuple.
227 succeed = yield addr, port
228
229 if succeed:
230 response = b"\x00\x5a\xea\x60\x7f\x00\x00\x01"
231 else:
232 response = b"\x00\x5b\x00\x00\x00\x00\x00\x00"
233
234 sock.sendall(response)
235
236
237 class TestSOCKSProxyManager:
238 def test_invalid_socks_version_is_valueerror(self) -> None:
239 with pytest.raises(ValueError, match="Unable to determine SOCKS version"):
240 socks.SOCKSProxyManager(proxy_url="http://example.org")
241
242
243 class TestSocks5Proxy(IPV4SocketDummyServerTestCase):
244 """
245 Test the SOCKS proxy in SOCKS5 mode.
246 """
247
248 def test_basic_request(self) -> None:
249 def request_handler(listener: socket.socket) -> None:
250 sock = listener.accept()[0]
251
252 handler = handle_socks5_negotiation(sock, negotiate=False)
253 addr, port = next(handler)
254
255 assert addr == "16.17.18.19"
256 assert port == 80
257 with pytest.raises(StopIteration):
258 handler.send(True)
259
260 while True:
261 buf = sock.recv(65535)
262 if buf.endswith(b"\r\n\r\n"):
263 break
264
265 sock.sendall(
266 b"HTTP/1.1 200 OK\r\n"
267 b"Server: SocksTestServer\r\n"
268 b"Content-Length: 0\r\n"
269 b"\r\n"
270 )
271 sock.close()
272
273 self._start_server(request_handler)
274 proxy_url = f"socks5://{self.host}:{self.port}"
275 with socks.SOCKSProxyManager(proxy_url) as pm:
276 response = pm.request("GET", "http://16.17.18.19")
277
278 assert response.status == 200
279 assert response.data == b""
280 assert response.headers["Server"] == "SocksTestServer"
281
282 def test_local_dns(self) -> None:
283 def request_handler(listener: socket.socket) -> None:
284 sock = listener.accept()[0]
285
286 handler = handle_socks5_negotiation(sock, negotiate=False)
287 addr, port = next(handler)
288
289 assert addr in ["127.0.0.1", "::1"]
290 assert port == 80
291 with pytest.raises(StopIteration):
292 handler.send(True)
293
294 while True:
295 buf = sock.recv(65535)
296 if buf.endswith(b"\r\n\r\n"):
297 break
298
299 sock.sendall(
300 b"HTTP/1.1 200 OK\r\n"
301 b"Server: SocksTestServer\r\n"
302 b"Content-Length: 0\r\n"
303 b"\r\n"
304 )
305 sock.close()
306
307 self._start_server(request_handler)
308 proxy_url = f"socks5://{self.host}:{self.port}"
309 with socks.SOCKSProxyManager(proxy_url) as pm:
310 response = pm.request("GET", "http://localhost")
311
312 assert response.status == 200
313 assert response.data == b""
314 assert response.headers["Server"] == "SocksTestServer"
315
316 def test_correct_header_line(self) -> None:
317 def request_handler(listener: socket.socket) -> None:
318 sock = listener.accept()[0]
319
320 handler = handle_socks5_negotiation(sock, negotiate=False)
321 addr, port = next(handler)
322
323 assert addr == b"example.com"
324 assert port == 80
325 with pytest.raises(StopIteration):
326 handler.send(True)
327
328 buf = b""
329 while True:
330 buf += sock.recv(65535)
331 if buf.endswith(b"\r\n\r\n"):
332 break
333
334 assert buf.startswith(b"GET / HTTP/1.1")
335 assert b"Host: example.com" in buf
336
337 sock.sendall(
338 b"HTTP/1.1 200 OK\r\n"
339 b"Server: SocksTestServer\r\n"
340 b"Content-Length: 0\r\n"
341 b"\r\n"
342 )
343 sock.close()
344
345 self._start_server(request_handler)
346 proxy_url = f"socks5h://{self.host}:{self.port}"
347 with socks.SOCKSProxyManager(proxy_url) as pm:
348 response = pm.request("GET", "http://example.com")
349 assert response.status == 200
350
351 def test_connection_timeouts(self) -> None:
352 event = threading.Event()
353
354 def request_handler(listener: socket.socket) -> None:
355 event.wait()
356
357 self._start_server(request_handler)
358 proxy_url = f"socks5h://{self.host}:{self.port}"
359 with socks.SOCKSProxyManager(proxy_url) as pm:
360 with pytest.raises(ConnectTimeoutError):
361 pm.request(
362 "GET", "http://example.com", timeout=SHORT_TIMEOUT, retries=False
363 )
364 event.set()
365
366 @patch("socks.create_connection")
367 def test_socket_timeout(self, create_connection: Mock) -> None:
368 create_connection.side_effect = SocketTimeout()
369 proxy_url = f"socks5h://{self.host}:{self.port}"
370 with socks.SOCKSProxyManager(proxy_url) as pm:
371 with pytest.raises(ConnectTimeoutError, match="timed out"):
372 pm.request("GET", "http://example.com", retries=False)
373
374 def test_connection_failure(self) -> None:
375 event = threading.Event()
376
377 def request_handler(listener: socket.socket) -> None:
378 listener.close()
379 event.set()
380
381 self._start_server(request_handler)
382 proxy_url = f"socks5h://{self.host}:{self.port}"
383 with socks.SOCKSProxyManager(proxy_url) as pm:
384 event.wait()
385 with pytest.raises(NewConnectionError):
386 pm.request("GET", "http://example.com", retries=False)
387
388 def test_proxy_rejection(self, monkeypatch: pytest.MonkeyPatch) -> None:
389 _set_up_fake_getaddrinfo(monkeypatch)
390 evt = threading.Event()
391
392 def request_handler(listener: socket.socket) -> None:
393 sock = listener.accept()[0]
394
395 handler = handle_socks5_negotiation(sock, negotiate=False)
396 addr, port = next(handler)
397 with pytest.raises(StopIteration):
398 handler.send(False)
399
400 evt.wait()
401 sock.close()
402
403 self._start_server(request_handler)
404 proxy_url = f"socks5h://{self.host}:{self.port}"
405 with socks.SOCKSProxyManager(proxy_url) as pm:
406 with pytest.raises(NewConnectionError):
407 pm.request("GET", "http://example.com", retries=False)
408 evt.set()
409
410 def test_socks_with_password(self) -> None:
411 def request_handler(listener: socket.socket) -> None:
412 sock = listener.accept()[0]
413
414 handler = handle_socks5_negotiation(
415 sock, negotiate=True, username=b"user", password=b"pass"
416 )
417 addr, port = next(handler)
418
419 assert addr == "16.17.18.19"
420 assert port == 80
421 with pytest.raises(StopIteration):
422 handler.send(True)
423
424 while True:
425 buf = sock.recv(65535)
426 if buf.endswith(b"\r\n\r\n"):
427 break
428
429 sock.sendall(
430 b"HTTP/1.1 200 OK\r\n"
431 b"Server: SocksTestServer\r\n"
432 b"Content-Length: 0\r\n"
433 b"\r\n"
434 )
435 sock.close()
436
437 self._start_server(request_handler)
438 proxy_url = f"socks5://{self.host}:{self.port}"
439 with socks.SOCKSProxyManager(proxy_url, username="user", password="pass") as pm:
440 response = pm.request("GET", "http://16.17.18.19")
441
442 assert response.status == 200
443 assert response.data == b""
444 assert response.headers["Server"] == "SocksTestServer"
445
446 def test_socks_with_auth_in_url(self) -> None:
447 """
448 Test when we have auth info in url, i.e.
449 socks5://user:pass@host:port and no username/password as params
450 """
451
452 def request_handler(listener: socket.socket) -> None:
453 sock = listener.accept()[0]
454
455 handler = handle_socks5_negotiation(
456 sock, negotiate=True, username=b"user", password=b"pass"
457 )
458 addr, port = next(handler)
459
460 assert addr == "16.17.18.19"
461 assert port == 80
462 with pytest.raises(StopIteration):
463 handler.send(True)
464
465 while True:
466 buf = sock.recv(65535)
467 if buf.endswith(b"\r\n\r\n"):
468 break
469
470 sock.sendall(
471 b"HTTP/1.1 200 OK\r\n"
472 b"Server: SocksTestServer\r\n"
473 b"Content-Length: 0\r\n"
474 b"\r\n"
475 )
476 sock.close()
477
478 self._start_server(request_handler)
479 proxy_url = f"socks5://user:pass@{self.host}:{self.port}"
480 with socks.SOCKSProxyManager(proxy_url) as pm:
481 response = pm.request("GET", "http://16.17.18.19")
482
483 assert response.status == 200
484 assert response.data == b""
485 assert response.headers["Server"] == "SocksTestServer"
486
487 def test_socks_with_percent_encoded_auth_in_url(self) -> None:
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:name", password=b"pa@ss"
493 )
494 addr, port = next(handler)
495
496 assert addr == "16.17.18.19"
497 assert port == 80
498 with pytest.raises(StopIteration):
499 handler.send(True)
500
501 while True:
502 buf = sock.recv(65535)
503 if buf.endswith(b"\r\n\r\n"):
504 break
505
506 sock.sendall(
507 b"HTTP/1.1 200 OK\r\n"
508 b"Server: SocksTestServer\r\n"
509 b"Content-Length: 0\r\n"
510 b"\r\n"
511 )
512 sock.close()
513
514 self._start_server(request_handler)
515 proxy_url = f"socks5://user%3Aname:pa%40ss@{self.host}:{self.port}"
516 with socks.SOCKSProxyManager(proxy_url) as pm:
517 response = pm.request("GET", "http://16.17.18.19")
518
519 assert response.status == 200
520 assert response.data == b""
521 assert response.headers["Server"] == "SocksTestServer"
522
523 def test_socks_with_invalid_password(self, monkeypatch: pytest.MonkeyPatch) -> None:
524 _set_up_fake_getaddrinfo(monkeypatch)
525
526 def request_handler(listener: socket.socket) -> None:
527 sock = listener.accept()[0]
528
529 handler = handle_socks5_negotiation(
530 sock, negotiate=True, username=b"user", password=b"pass"
531 )
532 with pytest.raises(StopIteration):
533 next(handler)
534
535 self._start_server(request_handler)
536 proxy_url = f"socks5h://{self.host}:{self.port}"
537 with socks.SOCKSProxyManager(
538 proxy_url, username="user", password="badpass"
539 ) as pm:
540 with pytest.raises(
541 NewConnectionError, match="SOCKS5 authentication failed"
542 ):
543 pm.request("GET", "http://example.com", retries=False)
544
545 def test_source_address_works(self) -> None:
546 expected_port = _get_free_port(self.host)
547
548 def request_handler(listener: socket.socket) -> None:
549 sock = listener.accept()[0]
550 assert sock.getpeername()[0] == "127.0.0.1"
551 assert sock.getpeername()[1] == expected_port
552
553 handler = handle_socks5_negotiation(sock, negotiate=False)
554 addr, port = next(handler)
555
556 assert addr == "16.17.18.19"
557 assert port == 80
558 with pytest.raises(StopIteration):
559 handler.send(True)
560
561 while True:
562 buf = sock.recv(65535)
563 if buf.endswith(b"\r\n\r\n"):
564 break
565
566 sock.sendall(
567 b"HTTP/1.1 200 OK\r\n"
568 b"Server: SocksTestServer\r\n"
569 b"Content-Length: 0\r\n"
570 b"\r\n"
571 )
572 sock.close()
573
574 self._start_server(request_handler)
575 proxy_url = f"socks5://{self.host}:{self.port}"
576 with socks.SOCKSProxyManager(
577 proxy_url, source_address=("127.0.0.1", expected_port)
578 ) as pm:
579 response = pm.request("GET", "http://16.17.18.19")
580 assert response.status == 200
581
582
583 class TestSOCKS4Proxy(IPV4SocketDummyServerTestCase):
584 """
585 Test the SOCKS proxy in SOCKS4 mode.
586
587 Has relatively fewer tests than the SOCKS5 case, mostly because once the
588 negotiation is done the two cases behave identically.
589 """
590
591 def test_basic_request(self) -> None:
592 def request_handler(listener: socket.socket) -> None:
593 sock = listener.accept()[0]
594
595 handler = handle_socks4_negotiation(sock)
596 addr, port = next(handler)
597
598 assert addr == "16.17.18.19"
599 assert port == 80
600 with pytest.raises(StopIteration):
601 handler.send(True)
602
603 while True:
604 buf = sock.recv(65535)
605 if buf.endswith(b"\r\n\r\n"):
606 break
607
608 sock.sendall(
609 b"HTTP/1.1 200 OK\r\n"
610 b"Server: SocksTestServer\r\n"
611 b"Content-Length: 0\r\n"
612 b"\r\n"
613 )
614 sock.close()
615
616 self._start_server(request_handler)
617 proxy_url = f"socks4://{self.host}:{self.port}"
618 with socks.SOCKSProxyManager(proxy_url) as pm:
619 response = pm.request("GET", "http://16.17.18.19")
620
621 assert response.status == 200
622 assert response.headers["Server"] == "SocksTestServer"
623 assert response.data == b""
624
625 def test_local_dns(self) -> None:
626 def request_handler(listener: socket.socket) -> None:
627 sock = listener.accept()[0]
628
629 handler = handle_socks4_negotiation(sock)
630 addr, port = next(handler)
631
632 assert addr == "127.0.0.1"
633 assert port == 80
634 with pytest.raises(StopIteration):
635 handler.send(True)
636
637 while True:
638 buf = sock.recv(65535)
639 if buf.endswith(b"\r\n\r\n"):
640 break
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"socks4://{self.host}:{self.port}"
652 with socks.SOCKSProxyManager(proxy_url) as pm:
653 response = pm.request("GET", "http://localhost")
654
655 assert response.status == 200
656 assert response.headers["Server"] == "SocksTestServer"
657 assert response.data == b""
658
659 def test_correct_header_line(self) -> None:
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
666 assert addr == b"example.com"
667 assert port == 80
668 with pytest.raises(StopIteration):
669 handler.send(True)
670
671 buf = b""
672 while True:
673 buf += sock.recv(65535)
674 if buf.endswith(b"\r\n\r\n"):
675 break
676
677 assert buf.startswith(b"GET / HTTP/1.1")
678 assert b"Host: example.com" in buf
679
680 sock.sendall(
681 b"HTTP/1.1 200 OK\r\n"
682 b"Server: SocksTestServer\r\n"
683 b"Content-Length: 0\r\n"
684 b"\r\n"
685 )
686 sock.close()
687
688 self._start_server(request_handler)
689 proxy_url = f"socks4a://{self.host}:{self.port}"
690 with socks.SOCKSProxyManager(proxy_url) as pm:
691 response = pm.request("GET", "http://example.com")
692 assert response.status == 200
693
694 def test_proxy_rejection(self, monkeypatch: pytest.MonkeyPatch) -> None:
695 _set_up_fake_getaddrinfo(monkeypatch)
696 evt = threading.Event()
697
698 def request_handler(listener: socket.socket) -> None:
699 sock = listener.accept()[0]
700
701 handler = handle_socks4_negotiation(sock)
702 addr, port = next(handler)
703 with pytest.raises(StopIteration):
704 handler.send(False)
705
706 evt.wait()
707 sock.close()
708
709 self._start_server(request_handler)
710 proxy_url = f"socks4a://{self.host}:{self.port}"
711 with socks.SOCKSProxyManager(proxy_url) as pm:
712 with pytest.raises(NewConnectionError):
713 pm.request("GET", "http://example.com", retries=False)
714 evt.set()
715
716 def test_socks4_with_username(self) -> None:
717 def request_handler(listener: socket.socket) -> None:
718 sock = listener.accept()[0]
719
720 handler = handle_socks4_negotiation(sock, username=b"user")
721 addr, port = next(handler)
722
723 assert addr == "16.17.18.19"
724 assert port == 80
725 with pytest.raises(StopIteration):
726 handler.send(True)
727
728 while True:
729 buf = sock.recv(65535)
730 if buf.endswith(b"\r\n\r\n"):
731 break
732
733 sock.sendall(
734 b"HTTP/1.1 200 OK\r\n"
735 b"Server: SocksTestServer\r\n"
736 b"Content-Length: 0\r\n"
737 b"\r\n"
738 )
739 sock.close()
740
741 self._start_server(request_handler)
742 proxy_url = f"socks4://{self.host}:{self.port}"
743 with socks.SOCKSProxyManager(proxy_url, username="user") as pm:
744 response = pm.request("GET", "http://16.17.18.19")
745
746 assert response.status == 200
747 assert response.data == b""
748 assert response.headers["Server"] == "SocksTestServer"
749
750 def test_socks4_with_percent_encoded_username_in_url(self) -> None:
751 def request_handler(listener: socket.socket) -> None:
752 sock = listener.accept()[0]
753
754 handler = handle_socks4_negotiation(sock, username=b"user:name")
755 addr, port = next(handler)
756
757 assert addr == "16.17.18.19"
758 assert port == 80
759 with pytest.raises(StopIteration):
760 handler.send(True)
761
762 while True:
763 buf = sock.recv(65535)
764 if buf.endswith(b"\r\n\r\n"):
765 break
766
767 sock.sendall(
768 b"HTTP/1.1 200 OK\r\n"
769 b"Server: SocksTestServer\r\n"
770 b"Content-Length: 0\r\n"
771 b"\r\n"
772 )
773 sock.close()
774
775 self._start_server(request_handler)
776 proxy_url = f"socks4://user%3Aname@{self.host}:{self.port}"
777 with socks.SOCKSProxyManager(proxy_url) as pm:
778 response = pm.request("GET", "http://16.17.18.19")
779
780 assert response.status == 200
781 assert response.data == b""
782 assert response.headers["Server"] == "SocksTestServer"
783
784 def test_socks_with_invalid_username(self) -> None:
785 def request_handler(listener: socket.socket) -> None:
786 sock = listener.accept()[0]
787
788 handler = handle_socks4_negotiation(sock, username=b"user")
789 next(handler, None)
790
791 self._start_server(request_handler)
792 proxy_url = f"socks4a://{self.host}:{self.port}"
793 with socks.SOCKSProxyManager(proxy_url, username="baduser") as pm:
794 with pytest.raises(NewConnectionError, match="different user-ids"):
795 pm.request("GET", "http://example.com", retries=False)
796
797
798 class TestSOCKSWithTLS(IPV4SocketDummyServerTestCase):
799 """
800 Test that TLS behaves properly for SOCKS proxies.
801 """
802
803 @pytest.mark.skipif(not HAS_SSL, reason="No TLS available")
804 def test_basic_request(self) -> None:
805 def request_handler(listener: socket.socket) -> None:
806 sock = listener.accept()[0]
807
808 handler = handle_socks5_negotiation(sock, negotiate=False)
809 addr, port = next(handler)
810
811 assert addr == b"localhost"
812 assert port == 443
813 with pytest.raises(StopIteration):
814 handler.send(True)
815
816 # Wrap in TLS
817 context = better_ssl.SSLContext(ssl.PROTOCOL_SSLv23) # type: ignore[misc]
818 context.load_cert_chain(DEFAULT_CERTS["certfile"], DEFAULT_CERTS["keyfile"])
819 tls = context.wrap_socket(sock, server_side=True)
820 buf = b""
821
822 while True:
823 buf += tls.recv(65535)
824 if buf.endswith(b"\r\n\r\n"):
825 break
826
827 assert buf.startswith(b"GET / HTTP/1.1\r\n")
828
829 tls.sendall(
830 b"HTTP/1.1 200 OK\r\n"
831 b"Server: SocksTestServer\r\n"
832 b"Content-Length: 0\r\n"
833 b"\r\n"
834 )
835 tls.close()
836 sock.close()
837
838 self._start_server(request_handler)
839 proxy_url = f"socks5h://{self.host}:{self.port}"
840 with socks.SOCKSProxyManager(proxy_url, ca_certs=DEFAULT_CA) as pm:
841 response = pm.request("GET", "https://localhost")
842
843 assert response.status == 200
844 assert response.data == b""
845 assert response.headers["Server"] == "SocksTestServer"