| 1 | import os |
| 2 | import socket |
| 3 | import subprocess |
| 4 | import sys |
| 5 | import textwrap |
| 6 | import uuid |
| 7 | from pathlib import Path |
| 8 | |
| 9 | import pytest |
| 10 | |
| 11 | from tests.loopback_ports import ambient_receivers, bind_peer_tcp |
| 12 | |
| 13 | |
| 14 | def _run_probe(tmp_path, body): |
| 15 | probe = tmp_path / "test_probe.py" |
| 16 | probe.write_text(textwrap.dedent(body), encoding="utf-8") |
| 17 | root = Path(__file__).resolve().parents[1] |
| 18 | environment = dict(os.environ) |
| 19 | environment["PYTHONPATH"] = os.pathsep.join([str(root), environment.get("PYTHONPATH", "")]) |
| 20 | return subprocess.run( |
| 21 | [sys.executable, "-m", "pytest", "-q", "--tb=short", "-p", "tests.network_guard", str(probe)], |
| 22 | cwd=tmp_path, env=environment, capture_output=True, text=True, timeout=30, |
| 23 | ) |
| 24 | |
| 25 | |
| 26 | @pytest.mark.parametrize("operation", [ |
| 27 | "socket.create_connection((host, 443))", |
| 28 | "socket.getaddrinfo(host, 443)", |
| 29 | "socket.gethostbyname(host)", |
| 30 | "socket.gethostbyname_ex(host)", |
| 31 | "socket.gethostbyaddr(host)", |
| 32 | "socket.socket().connect((host, 443))", |
| 33 | "socket.socket().connect_ex((host, 443))", |
| 34 | "socket.socket(socket.AF_INET, socket.SOCK_DGRAM).sendto(b'probe', (host, 53))", |
| 35 | ]) |
| 36 | def test_swallowed_network_attempt_fails_test(tmp_path, operation): |
| 37 | host = f"forbidden-{uuid.uuid4().hex}.invalid" |
| 38 | result = _run_probe(tmp_path, f""" |
| 39 | import socket |
| 40 | |
| 41 | def test_caught_transport_error(): |
| 42 | host = {host!r} |
| 43 | try: |
| 44 | {operation} |
| 45 | except OSError: |
| 46 | pass |
| 47 | """) |
| 48 | assert result.returncode == 1, result.stdout + result.stderr |
| 49 | assert "1 passed, 1 error" in result.stdout |
| 50 | assert "Unexpected network attempts" in result.stdout |
| 51 | assert host in result.stdout |
| 52 | |
| 53 | |
| 54 | @pytest.mark.parametrize("operation, host, expected", [ |
| 55 | ("gethostbyname", "localhost", "127.0.0.1"), |
| 56 | ("gethostbyname", "127.0.0.2", "127.0.0.2"), |
| 57 | ("gethostbyname_ex", "localhost", ("localhost", [], ["127.0.0.1"])), |
| 58 | ("gethostbyname_ex", "127.0.0.2", ("127.0.0.2", [], ["127.0.0.2"])), |
| 59 | ("gethostbyaddr", "localhost", ("localhost", [], ["127.0.0.1"])), |
| 60 | ("gethostbyaddr", "127.0.0.2", ("localhost", [], ["127.0.0.2"])), |
| 61 | ("gethostbyaddr", "::1", ("localhost", [], ["::1"])), |
| 62 | ]) |
| 63 | def test_loopback_resolvers_do_not_delegate_to_libc(tmp_path, operation, host, expected): |
| 64 | result = _run_probe(tmp_path, f""" |
| 65 | import socket |
| 66 | |
| 67 | calls = [] |
| 68 | def system_resolver(host): |
| 69 | calls.append(host) |
| 70 | return {expected!r} |
| 71 | socket.{operation} = system_resolver |
| 72 | |
| 73 | def test_local_answer(): |
| 74 | assert socket.{operation}({host!r}) == {expected!r} |
| 75 | assert calls == [], 'loopback lookup reached the system resolver' |
| 76 | """) |
| 77 | assert result.returncode == 0, result.stdout + result.stderr |
| 78 | assert "1 passed" in result.stdout |
| 79 | |
| 80 | |
| 81 | @pytest.mark.parametrize("operation", ["gethostbyname", "gethostbyname_ex"]) |
| 82 | def test_ipv4_resolvers_reject_ipv6_without_libc(tmp_path, operation): |
| 83 | result = _run_probe(tmp_path, f""" |
| 84 | import socket |
| 85 | import pytest |
| 86 | |
| 87 | calls = [] |
| 88 | def system_resolver(host): |
| 89 | calls.append(host) |
| 90 | raise socket.gaierror(socket.EAI_FAMILY, 'IPv4 lookup requires an IPv4 address') |
| 91 | socket.{operation} = system_resolver |
| 92 | |
| 93 | def test_ipv4_only_contract(): |
| 94 | with pytest.raises(socket.gaierror): |
| 95 | socket.{operation}('::1') |
| 96 | assert calls == [], 'IPv6 input reached the IPv4 system resolver' |
| 97 | """) |
| 98 | assert result.returncode == 0, result.stdout + result.stderr |
| 99 | assert "1 passed" in result.stdout |
| 100 | |
| 101 | |
| 102 | def test_owned_getaddrinfo_delegates_only_numeric_addresses_and_services(tmp_path): |
| 103 | result = _run_probe(tmp_path, """ |
| 104 | import socket |
| 105 | |
| 106 | system_resolver = socket.getaddrinfo |
| 107 | calls = [] |
| 108 | def numeric_resolver(host, port, family=0, type=0, proto=0, flags=0): |
| 109 | calls.append((host, port, flags)) |
| 110 | assert flags & socket.AI_NUMERICHOST, 'system resolver lacks AI_NUMERICHOST' |
| 111 | assert flags & socket.AI_NUMERICSERV, 'system resolver lacks AI_NUMERICSERV' |
| 112 | return system_resolver(host, port, family, type, proto, flags) |
| 113 | socket.getaddrinfo = numeric_resolver |
| 114 | |
| 115 | def test_owned_localhost(): |
| 116 | with socket.socket() as server: |
| 117 | server.bind(('127.0.0.1', 0)) |
| 118 | port = server.getsockname()[1] |
| 119 | result = socket.getaddrinfo('localhost', port, type=socket.SOCK_STREAM) |
| 120 | assert {item[4] for item in result} == {('127.0.0.1', port)} |
| 121 | assert calls |
| 122 | assert all(host == '127.0.0.1' for host, _, _ in calls) |
| 123 | """) |
| 124 | assert result.returncode == 0, result.stdout + result.stderr |
| 125 | assert "1 passed" in result.stdout |
| 126 | |
| 127 | |
| 128 | @pytest.mark.parametrize("form", ["text", "bytes", "four_byte_hostname"]) |
| 129 | def test_bind_hostname_is_denied_before_original_method(tmp_path, form): |
| 130 | host = f"bind-{uuid.uuid4().hex}.invalid" |
| 131 | if form == "bytes": |
| 132 | host = host.encode("ascii") |
| 133 | elif form == "four_byte_hostname": |
| 134 | host = b"abcd" |
| 135 | result = _run_probe(tmp_path, f""" |
| 136 | import socket |
| 137 | |
| 138 | delegated = [] |
| 139 | def original_bind(sock, address): |
| 140 | delegated.append(address) |
| 141 | raise OSError('controlled bind resolver canary; no DNS was called') |
| 142 | socket.socket.bind = original_bind |
| 143 | |
| 144 | def test_denied_hostname(): |
| 145 | with socket.socket() as server: |
| 146 | try: |
| 147 | server.bind(({host!r}, 0)) |
| 148 | except OSError: |
| 149 | pass |
| 150 | assert delegated == [], 'hostname reached original bind' |
| 151 | """) |
| 152 | assert result.returncode == 1, result.stdout + result.stderr |
| 153 | assert "1 passed, 1 error" in result.stdout, result.stdout + result.stderr |
| 154 | assert "Unexpected network attempts" in result.stdout |
| 155 | assert "bind:" in result.stdout |
| 156 | |
| 157 | |
| 158 | @pytest.mark.parametrize("family, host, expected", [ |
| 159 | ("AF_INET", "localhost", "127.0.0.1"), |
| 160 | ("AF_INET", "", "0.0.0.0"), |
| 161 | ("AF_INET", "127.0.0.1", "127.0.0.1"), |
| 162 | ("AF_INET", b"localhost", "127.0.0.1"), |
| 163 | ("AF_INET", b"", "0.0.0.0"), |
| 164 | ("AF_INET", b"127.0.0.1", "127.0.0.1"), |
| 165 | ("AF_INET6", "localhost", "::1"), |
| 166 | ("AF_INET6", "", "::"), |
| 167 | ("AF_INET6", "::1", "::1"), |
| 168 | ("AF_INET6", b"localhost", "::1"), |
| 169 | ("AF_INET6", b"", "::"), |
| 170 | ("AF_INET6", b"::1", "::1"), |
| 171 | ]) |
| 172 | def test_bind_passes_numeric_host_and_preserves_sockaddr_fields(tmp_path, family, host, expected): |
| 173 | trailing = (0,) if family == "AF_INET" else (0, 17, 29) |
| 174 | result = _run_probe(tmp_path, f""" |
| 175 | import socket |
| 176 | |
| 177 | delegated = [] |
| 178 | def original_bind(sock, address): |
| 179 | delegated.append(address) |
| 180 | raise OSError('controlled numeric bind; no system call was made') |
| 181 | socket.socket.bind = original_bind |
| 182 | |
| 183 | class BoundSocket: |
| 184 | family = socket.{family} |
| 185 | |
| 186 | def test_numeric_boundary(): |
| 187 | try: |
| 188 | socket.socket.bind(BoundSocket(), ({host!r}, *{trailing!r})) |
| 189 | except OSError: |
| 190 | pass |
| 191 | assert delegated == [({expected!r}, *{trailing!r})] |
| 192 | """) |
| 193 | assert result.returncode == 0, result.stdout + result.stderr |
| 194 | assert "1 passed" in result.stdout |
| 195 | |
| 196 | |
| 197 | @pytest.mark.parametrize("family, host", [("AF_INET", "::1"), ("AF_INET6", "127.0.0.1")]) |
| 198 | def test_bind_rejects_wrong_ip_family_before_original_method(tmp_path, family, host): |
| 199 | result = _run_probe(tmp_path, f""" |
| 200 | import socket |
| 201 | import pytest |
| 202 | |
| 203 | delegated = [] |
| 204 | def original_bind(sock, address): |
| 205 | delegated.append(address) |
| 206 | raise socket.gaierror(socket.EAI_FAMILY, 'wrong address family') |
| 207 | socket.socket.bind = original_bind |
| 208 | |
| 209 | class BoundSocket: |
| 210 | family = socket.{family} |
| 211 | |
| 212 | def test_family_error_is_local(): |
| 213 | with pytest.raises(socket.gaierror) as error: |
| 214 | socket.socket.bind(BoundSocket(), ({host!r}, 0)) |
| 215 | assert error.value.errno == socket.EAI_FAMILY |
| 216 | assert delegated == [], 'wrong-family host reached original bind' |
| 217 | """) |
| 218 | assert result.returncode == 0, result.stdout + result.stderr |
| 219 | assert "1 passed" in result.stdout |
| 220 | |
| 221 | |
| 222 | def test_bind_preserves_unix_socket_address(tmp_path): |
| 223 | if not hasattr(socket, "AF_UNIX"): |
| 224 | pytest.skip("AF_UNIX is unavailable on this platform") |
| 225 | result = _run_probe(tmp_path, """ |
| 226 | import socket |
| 227 | |
| 228 | delegated = [] |
| 229 | def original_bind(sock, address): |
| 230 | delegated.append(address) |
| 231 | raise OSError('controlled Unix bind; no system call was made') |
| 232 | socket.socket.bind = original_bind |
| 233 | |
| 234 | class BoundSocket: |
| 235 | family = socket.AF_UNIX |
| 236 | |
| 237 | def test_unix_boundary(): |
| 238 | try: |
| 239 | socket.socket.bind(BoundSocket(), '/tmp/owned-fixture.sock') |
| 240 | except OSError: |
| 241 | pass |
| 242 | assert delegated == ['/tmp/owned-fixture.sock'] |
| 243 | """) |
| 244 | assert result.returncode == 0, result.stdout + result.stderr |
| 245 | assert "1 passed" in result.stdout |
| 246 | |
| 247 | |
| 248 | @pytest.mark.parametrize("kind", ["SOCK_STREAM", "SOCK_DGRAM"]) |
| 249 | def test_localhost_bind_preserves_real_owned_transport(tmp_path, kind): |
| 250 | canary = f"bound-{uuid.uuid4().hex}".encode("ascii") |
| 251 | result = _run_probe(tmp_path, f""" |
| 252 | import socket |
| 253 | |
| 254 | def test_owned_bound_transport(): |
| 255 | with socket.socket(socket.AF_INET, socket.{kind}) as server: |
| 256 | server.bind(('localhost', 0)) |
| 257 | server.settimeout(1) |
| 258 | assert server.getsockname()[0] == '127.0.0.1' |
| 259 | address = ('localhost', server.getsockname()[1]) |
| 260 | if socket.{kind} == socket.SOCK_STREAM: |
| 261 | server.listen() |
| 262 | with socket.create_connection(address) as client: |
| 263 | client.sendall({canary!r}) |
| 264 | accepted, _ = server.accept() |
| 265 | with accepted: |
| 266 | assert accepted.recv(128) == {canary!r} |
| 267 | else: |
| 268 | with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as client: |
| 269 | client.sendto({canary!r}, address) |
| 270 | assert server.recv(128) == {canary!r} |
| 271 | """) |
| 272 | assert result.returncode == 0, result.stdout + result.stderr |
| 273 | assert "1 passed" in result.stdout |
| 274 | |
| 275 | |
| 276 | @pytest.mark.parametrize("flags", [0, socket.NI_NUMERICHOST, socket.NI_NUMERICSERV]) |
| 277 | def test_getnameinfo_rejects_resolver_modes_without_libc(tmp_path, flags): |
| 278 | result = _run_probe(tmp_path, f""" |
| 279 | import socket |
| 280 | |
| 281 | calls = [] |
| 282 | def system_resolver(address, flags): |
| 283 | calls.append((address, flags)) |
| 284 | return 'resolver-host', 'resolver-service' |
| 285 | socket.getnameinfo = system_resolver |
| 286 | |
| 287 | def test_no_reverse_resolution(): |
| 288 | try: |
| 289 | socket.getnameinfo(('127.0.0.2', 80), {flags!r}) |
| 290 | except OSError: |
| 291 | pass |
| 292 | assert calls == [], 'reverse name/service lookup reached the system resolver' |
| 293 | """) |
| 294 | assert result.returncode == 1, result.stdout + result.stderr |
| 295 | assert "1 passed, 1 error" in result.stdout |
| 296 | assert "Unexpected network attempts" in result.stdout |
| 297 | assert "getnameinfo" in result.stdout |
| 298 | |
| 299 | |
| 300 | @pytest.mark.parametrize("address", [("127.0.0.2", 80), ("::1", 80, 0, 0)]) |
| 301 | def test_getnameinfo_numeric_mode_remains_usable(tmp_path, address): |
| 302 | result = _run_probe(tmp_path, f""" |
| 303 | import socket |
| 304 | |
| 305 | system_resolver = socket.getnameinfo |
| 306 | calls = [] |
| 307 | def numeric_resolver(address, flags): |
| 308 | calls.append((address, flags)) |
| 309 | assert flags & socket.NI_NUMERICHOST |
| 310 | assert flags & socket.NI_NUMERICSERV |
| 311 | return system_resolver(address, flags) |
| 312 | socket.getnameinfo = numeric_resolver |
| 313 | |
| 314 | def test_numeric_answer(): |
| 315 | flags = socket.NI_NUMERICHOST | socket.NI_NUMERICSERV |
| 316 | assert socket.getnameinfo({address!r}, flags) == ({address[0]!r}, '80') |
| 317 | assert calls == [({address!r}, flags)] |
| 318 | """) |
| 319 | assert result.returncode == 0, result.stdout + result.stderr |
| 320 | assert "1 passed" in result.stdout |
| 321 | |
| 322 | |
| 323 | @pytest.mark.parametrize("address", [("203.0.113.8", 443), ("127.0.0.1", 18800), ("localhost", 9222)]) |
| 324 | def test_unowned_ip_or_loopback_connection_fails_test(tmp_path, address): |
| 325 | result = _run_probe(tmp_path, f""" |
| 326 | import socket |
| 327 | |
| 328 | def test_no_ambient_service(): |
| 329 | try: |
| 330 | socket.create_connection({address!r}) |
| 331 | except OSError: |
| 332 | pass |
| 333 | """) |
| 334 | assert result.returncode == 1, result.stdout + result.stderr |
| 335 | assert "1 passed, 1 error" in result.stdout |
| 336 | assert "Unexpected network attempts" in result.stdout |
| 337 | assert address[0] in result.stdout |
| 338 | |
| 339 | |
| 340 | def test_swallowed_worker_network_attempt_fails_test(tmp_path): |
| 341 | host = f"worker-{uuid.uuid4().hex}.invalid" |
| 342 | result = _run_probe(tmp_path, f""" |
| 343 | import socket |
| 344 | from concurrent.futures import ThreadPoolExecutor |
| 345 | |
| 346 | def test_worker(): |
| 347 | def work(): |
| 348 | try: |
| 349 | socket.create_connection(({host!r}, 443)) |
| 350 | except OSError: |
| 351 | return [] |
| 352 | with ThreadPoolExecutor(max_workers=1) as executor: |
| 353 | assert executor.submit(work).result() == [] |
| 354 | """) |
| 355 | assert result.returncode == 1, result.stdout + result.stderr |
| 356 | assert "1 passed, 1 error" in result.stdout |
| 357 | assert "Unexpected network attempts" in result.stdout |
| 358 | assert host in result.stdout |
| 359 | |
| 360 | |
| 361 | def test_owned_loopback_transport_remains_real(tmp_path): |
| 362 | result = _run_probe(tmp_path, """ |
| 363 | import socket |
| 364 | |
| 365 | def test_local_exchange(): |
| 366 | with socket.socket() as server: |
| 367 | server.bind(('127.0.0.1', 0)) |
| 368 | server.listen() |
| 369 | with socket.create_connection(('localhost', server.getsockname()[1])) as client: |
| 370 | client.sendall(b'owned transport') |
| 371 | connection, _ = server.accept() |
| 372 | with connection: |
| 373 | assert connection.recv(64) == b'owned transport' |
| 374 | """) |
| 375 | assert result.returncode == 0, result.stdout + result.stderr |
| 376 | assert "1 passed" in result.stdout |
| 377 | |
| 378 | |
| 379 | def _can_bind(host): |
| 380 | try: |
| 381 | with socket.socket() as probe: |
| 382 | probe.bind((host, 0)) |
| 383 | except OSError: |
| 384 | return False |
| 385 | return True |
| 386 | |
| 387 | |
| 388 | # macOS lo0 carries only 127.0.0.1 unless an alias is added; Linux routes all of 127/8. |
| 389 | @pytest.mark.skipif(not _can_bind("127.0.0.2"), reason="127.0.0.2 is not bindable on this host") |
| 390 | def test_owned_port_does_not_authorize_another_loopback_address(tmp_path): |
| 391 | canary = f"address-{uuid.uuid4().hex}" |
| 392 | result = _run_probe(tmp_path, f""" |
| 393 | import socket |
| 394 | import pytest |
| 395 | from tests.loopback_ports import ambient_receivers, bind_peer_tcp |
| 396 | |
| 397 | @pytest.mark.parametrize("ambient_receivers", [("127.0.0.2", socket.SOCK_STREAM)], indirect=True) |
| 398 | def test_exact_address(ambient_receivers): |
| 399 | with socket.socket() as owned: |
| 400 | ambient = bind_peer_tcp(owned, ambient_receivers) |
| 401 | try: |
| 402 | with socket.create_connection(ambient.getsockname()) as client: |
| 403 | client.sendall({canary.encode()!r}) |
| 404 | except OSError: |
| 405 | pass |
| 406 | with pytest.raises(BlockingIOError): |
| 407 | accepted, _ = ambient.accept() |
| 408 | with accepted: |
| 409 | assert accepted.recv(128) != {canary.encode()!r} |
| 410 | """) |
| 411 | assert result.returncode == 1, result.stdout + result.stderr |
| 412 | assert "1 passed, 1 error" in result.stdout |
| 413 | assert "Unexpected network attempts" in result.stdout |
| 414 | assert "127.0.0.2" in result.stdout |
| 415 | |
| 416 | |
| 417 | @pytest.mark.parametrize("operation", ["sendto", "sendmsg"]) |
| 418 | def test_owned_tcp_port_does_not_authorize_udp(tmp_path, operation): |
| 419 | if operation == "sendmsg" and not hasattr(socket.socket, "sendmsg"): |
| 420 | pytest.skip("sendmsg is unavailable on this platform") |
| 421 | canary = f"protocol-{uuid.uuid4().hex}" |
| 422 | call = f"sender.sendto({canary.encode()!r}, address)" if operation == "sendto" else f"sender.sendmsg([{canary.encode()!r}], [], 0, address)" |
| 423 | result = _run_probe(tmp_path, f""" |
| 424 | import socket |
| 425 | import pytest |
| 426 | from tests.loopback_ports import ambient_receivers, bind_peer_tcp |
| 427 | |
| 428 | @pytest.mark.parametrize("ambient_receivers", [("127.0.0.1", socket.SOCK_DGRAM)], indirect=True) |
| 429 | def test_exact_transport(ambient_receivers): |
| 430 | with socket.socket() as owned, socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sender: |
| 431 | ambient = bind_peer_tcp(owned, ambient_receivers) |
| 432 | address = ambient.getsockname() |
| 433 | try: |
| 434 | {call} |
| 435 | except OSError: |
| 436 | pass |
| 437 | with pytest.raises(BlockingIOError): |
| 438 | assert ambient.recv(128) != {canary.encode()!r} |
| 439 | """) |
| 440 | assert result.returncode == 1, result.stdout + result.stderr |
| 441 | assert "1 passed, 1 error" in result.stdout |
| 442 | assert "Unexpected network attempts" in result.stdout |
| 443 | assert operation in result.stdout |
| 444 | |
| 445 | |
| 446 | @pytest.mark.parametrize("ambient_receivers", [("127.0.0.1", socket.SOCK_DGRAM)], indirect=True) |
| 447 | def test_paired_ports_skip_a_tcp_port_that_is_already_listening(ambient_receivers): |
| 448 | with socket.socket() as busy, socket.socket() as owned: |
| 449 | busy.bind(("127.0.0.1", 0)) |
| 450 | busy.listen() |
| 451 | selected = bind_peer_tcp(owned, [busy, *ambient_receivers]) |
| 452 | assert selected in ambient_receivers |
| 453 | assert owned.getsockname()[1] == selected.getsockname()[1] |
| 454 | |
| 455 | |
| 456 | @pytest.mark.parametrize("operation", ["sendto", "sendmsg"]) |
| 457 | def test_owned_udp_transport_remains_real(tmp_path, operation): |
| 458 | if operation == "sendmsg" and not hasattr(socket.socket, "sendmsg"): |
| 459 | pytest.skip("sendmsg is unavailable on this platform") |
| 460 | canary = f"owned-{uuid.uuid4().hex}" |
| 461 | call = f"sender.sendto({canary.encode()!r}, address)" if operation == "sendto" else f"sender.sendmsg([{canary.encode()!r}], [], 0, address)" |
| 462 | result = _run_probe(tmp_path, f""" |
| 463 | import socket |
| 464 | |
| 465 | def test_udp_exchange(): |
| 466 | with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as server, socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sender: |
| 467 | server.bind(('127.0.0.1', 0)) |
| 468 | server.settimeout(1) |
| 469 | address = ('localhost', server.getsockname()[1]) |
| 470 | {call} |
| 471 | assert server.recv(128) == {canary.encode()!r} |
| 472 | """) |
| 473 | assert result.returncode == 0, result.stdout + result.stderr |
| 474 | assert "1 passed" in result.stdout |
| 475 | |
| 476 | |
| 477 | def test_guard_restores_every_patched_socket_function(tmp_path): |
| 478 | result = _run_probe(tmp_path, """ |
| 479 | import atexit |
| 480 | import socket |
| 481 | |
| 482 | socket_names = ['bind', 'close', 'detach', 'connect', 'connect_ex', 'sendto'] |
| 483 | if hasattr(socket.socket, 'sendmsg'): |
| 484 | socket_names.append('sendmsg') |
| 485 | module_names = ['create_connection', 'getaddrinfo', 'gethostbyname', |
| 486 | 'gethostbyname_ex', 'gethostbyaddr', 'getnameinfo'] |
| 487 | originals = [(socket.socket, name, getattr(socket.socket, name)) for name in socket_names] |
| 488 | originals += [(socket, name, getattr(socket, name)) for name in module_names] |
| 489 | |
| 490 | def verify_restored(): |
| 491 | for owner, name, original in originals: |
| 492 | assert getattr(owner, name) is original, f'{name} was not restored' |
| 493 | print(f'restored-{len(originals)}-socket-functions') |
| 494 | atexit.register(verify_restored) |
| 495 | |
| 496 | def test_owned_transport(): |
| 497 | with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as server, socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sender: |
| 498 | server.bind(('127.0.0.1', 0)) |
| 499 | server.settimeout(1) |
| 500 | sender.sendto(b'restoration transport', server.getsockname()) |
| 501 | assert server.recv(64) == b'restoration transport' |
| 502 | """) |
| 503 | assert result.returncode == 0, result.stdout + result.stderr |
| 504 | assert "1 passed" in result.stdout |
| 505 | count = 12 + int(hasattr(socket.socket, "sendmsg")) |
| 506 | assert f"restored-{count}-socket-functions" in result.stdout, result.stdout + result.stderr |
| 507 | |
| 508 | |
| 509 | def test_detached_fixture_does_not_authorize_a_port(tmp_path): |
| 510 | result = _run_probe(tmp_path, """ |
| 511 | import socket |
| 512 | |
| 513 | def test_detached_fixture(): |
| 514 | server = socket.socket() |
| 515 | server.bind(('127.0.0.1', 0)) |
| 516 | address = server.getsockname() |
| 517 | descriptor = server.detach() |
| 518 | socket.close(descriptor) |
| 519 | try: |
| 520 | socket.create_connection(address) |
| 521 | except OSError: |
| 522 | pass |
| 523 | """) |
| 524 | assert result.returncode == 1, result.stdout + result.stderr |
| 525 | assert "1 passed, 1 error" in result.stdout |
| 526 | assert "Unexpected network attempts" in result.stdout |
| 527 | |
| 528 | |
| 529 | def test_closed_fixture_does_not_authorize_a_port(tmp_path): |
| 530 | result = _run_probe(tmp_path, """ |
| 531 | import socket |
| 532 | |
| 533 | def test_fixture_closed(): |
| 534 | with socket.socket() as server: |
| 535 | server.bind(('127.0.0.1', 0)) |
| 536 | address = server.getsockname() |
| 537 | try: |
| 538 | socket.create_connection(address) |
| 539 | except OSError: |
| 540 | pass |
| 541 | """) |
| 542 | assert result.returncode == 1, result.stdout + result.stderr |
| 543 | assert "1 passed, 1 error" in result.stdout |
| 544 | assert "Unexpected network attempts" in result.stdout |
| 545 | |
| 546 | |
| 547 | def test_fixture_teardown_network_attempt_fails_test(tmp_path): |
| 548 | host = f"teardown-{uuid.uuid4().hex}.invalid" |
| 549 | result = _run_probe(tmp_path, f""" |
| 550 | import socket |
| 551 | import pytest |
| 552 | |
| 553 | @pytest.fixture |
| 554 | def resource(): |
| 555 | yield |
| 556 | try: |
| 557 | socket.create_connection(({host!r}, 443)) |
| 558 | except OSError: |
| 559 | pass |
| 560 | |
| 561 | def test_teardown(resource): |
| 562 | pass |
| 563 | """) |
| 564 | assert result.returncode == 1, result.stdout + result.stderr |
| 565 | assert "1 passed, 1 error" in result.stdout |
| 566 | assert "Unexpected network attempts" in result.stdout |
| 567 | assert host in result.stdout |
| 568 | |
| 569 | |
| 570 | @pytest.mark.parametrize("allowed", [False, True]) |
| 571 | def test_worker_boundary_guards_destination_and_preserves_allowed_call(tmp_path, allowed): |
| 572 | host = f"worker-boundary-{uuid.uuid4().hex}.invalid" |
| 573 | result = _run_probe(tmp_path, f""" |
| 574 | import socket |
| 575 | import sys |
| 576 | import types |
| 577 | from urllib.request import Request |
| 578 | |
| 579 | package = types.ModuleType('lib') |
| 580 | package.__path__ = [] |
| 581 | worker = types.ModuleType('lib.bounded_get') |
| 582 | calls = [] |
| 583 | def get(req, **kwargs): |
| 584 | calls.append((req.full_url, kwargs)) |
| 585 | return b'owned payload' |
| 586 | worker.get = get |
| 587 | sys.modules['lib'] = package |
| 588 | sys.modules['lib.bounded_get'] = worker |
| 589 | |
| 590 | def test_worker_destination(): |
| 591 | if {allowed!r}: |
| 592 | with socket.socket() as server: |
| 593 | server.bind(('127.0.0.1', 0)) |
| 594 | url = f'http://127.0.0.1:{{server.getsockname()[1]}}/fixture' |
| 595 | assert worker.get(Request(url), timeout=1, deadline_monotonic=123) == b'owned payload' |
| 596 | assert calls == [(url, {{'timeout': 1, 'deadline_monotonic': 123}})] |
| 597 | else: |
| 598 | try: |
| 599 | worker.get(Request('https://{host}/fixture'), timeout=1, deadline_monotonic=123) |
| 600 | except OSError: |
| 601 | pass |
| 602 | assert calls == [] |
| 603 | """) |
| 604 | assert result.returncode == (0 if allowed else 1), result.stdout + result.stderr |
| 605 | if allowed: |
| 606 | assert "1 passed" in result.stdout |
| 607 | else: |
| 608 | assert "1 passed, 1 error" in result.stdout |
| 609 | assert "Unexpected network attempts" in result.stdout |
| 610 | assert host in result.stdout |
| 611 | |
| 612 | |
| 613 | def test_worker_hostname_url_does_not_delegate_to_libc(tmp_path): |
| 614 | result = _run_probe(tmp_path, """ |
| 615 | import socket |
| 616 | import sys |
| 617 | import types |
| 618 | from urllib.request import Request |
| 619 | |
| 620 | package = types.ModuleType('lib') |
| 621 | package.__path__ = [] |
| 622 | worker = types.ModuleType('lib.bounded_get') |
| 623 | launches = [] |
| 624 | worker.get = lambda req, **kwargs: launches.append(req.full_url) |
| 625 | sys.modules['lib'] = package |
| 626 | sys.modules['lib.bounded_get'] = worker |
| 627 | |
| 628 | system_resolver = socket.getaddrinfo |
| 629 | lookups = [] |
| 630 | def resolver(host, port, family=0, type=0, proto=0, flags=0): |
| 631 | lookups.append(host) |
| 632 | numeric_host = '127.0.0.1' if host == 'localhost' else host |
| 633 | return system_resolver(numeric_host, port, family, type, proto, |
| 634 | flags | socket.AI_NUMERICHOST | socket.AI_NUMERICSERV) |
| 635 | socket.getaddrinfo = resolver |
| 636 | |
| 637 | def test_no_worker_hostname_resolution(): |
| 638 | with socket.socket() as server: |
| 639 | server.bind(('127.0.0.1', 0)) |
| 640 | url = f'http://localhost:{server.getsockname()[1]}/fixture' |
| 641 | try: |
| 642 | worker.get(Request(url), timeout=1, deadline_monotonic=123) |
| 643 | except OSError: |
| 644 | pass |
| 645 | assert 'localhost' not in lookups, 'worker hostname reached the system resolver' |
| 646 | assert launches == [] |
| 647 | """) |
| 648 | assert result.returncode == 1, result.stdout + result.stderr |
| 649 | assert "1 passed, 1 error" in result.stdout |
| 650 | assert "Unexpected network attempts" in result.stdout |
| 651 | assert "bounded_get" in result.stdout |
| 652 |