| 1 | """Exercise the BusyBox wget TLS helper against a private local peer.""" |
| 2 | |
| 3 | import os |
| 4 | import socket |
| 5 | import ssl |
| 6 | import subprocess |
| 7 | from concurrent.futures import ThreadPoolExecutor |
| 8 | from pathlib import Path |
| 9 | |
| 10 | |
| 11 | def make_cert(name): |
| 12 | subprocess.run( |
| 13 | ["openssl", "req", "-x509", "-newkey", "ec", "-pkeyopt", |
| 14 | "ec_paramgen_curve:P-256", "-nodes", "-days", "1", |
| 15 | "-subj", f"/CN={name}", "-addext", f"subjectAltName=DNS:{name}", |
| 16 | "-keyout", f"{name}.key", "-out", f"{name}.crt"], |
| 17 | check=True, capture_output=True, |
| 18 | ) |
| 19 | |
| 20 | |
| 21 | def serve(connection, context, expect_success): |
| 22 | connection.settimeout(8) |
| 23 | try: |
| 24 | with context.wrap_socket(connection, server_side=True) as peer: |
| 25 | if not expect_success: |
| 26 | raise AssertionError("client accepted the invalid peer") |
| 27 | with peer.makefile("rb") as data: |
| 28 | assert data.readline() == b"ping\n" |
| 29 | peer.sendall(b"pong\n") |
| 30 | # Send close_notify. The one-shot client may exit without replying. |
| 31 | try: |
| 32 | peer.unwrap().close() |
| 33 | except ssl.SSLEOFError: |
| 34 | pass |
| 35 | except ssl.SSLError: |
| 36 | if expect_success: |
| 37 | raise |
| 38 | finally: |
| 39 | connection.close() |
| 40 | |
| 41 | |
| 42 | def check(context, hostname, trust, expect_success): |
| 43 | client, server = socket.socketpair() |
| 44 | with client, ThreadPoolExecutor(max_workers=1) as pool: |
| 45 | task = pool.submit(serve, server, context, expect_success) |
| 46 | try: |
| 47 | result = subprocess.run( |
| 48 | ["vinix-run", "./ssl_client", "-s", str(client.fileno()), "-n", hostname], |
| 49 | input=b"ping\n", capture_output=True, pass_fds=(client.fileno(),), |
| 50 | env={**os.environ, "SSL_CERT_FILE": str(Path(trust).resolve()), |
| 51 | "SSL_CERT_DIR": str(Path("empty-certs").resolve())}, |
| 52 | timeout=10, |
| 53 | ) |
| 54 | finally: |
| 55 | client.close() |
| 56 | task.result(timeout=10) |
| 57 | if expect_success: |
| 58 | assert result.returncode == 0 and result.stdout == b"pong\n", result.stderr |
| 59 | else: |
| 60 | assert result.returncode != 0 and b"certificate verify failed" in result.stderr, result.stderr |
| 61 | |
| 62 | |
| 63 | make_cert("vinix.test") |
| 64 | make_cert("other.test") |
| 65 | Path("empty-certs").mkdir() |
| 66 | context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) |
| 67 | context.load_cert_chain("vinix.test.crt", "vinix.test.key") |
| 68 | check(context, "vinix.test.", "vinix.test.crt", True) |
| 69 | check(context, "wrong.test", "vinix.test.crt", False) |
| 70 | check(context, "vinix.test", "other.test.crt", False) |
| 71 | |