Complete lab 7 security implementation
This commit is contained in:
Executable
+152
@@ -0,0 +1,152 @@
|
||||
"""lab7: mTLS LB→API. Проверяет identity (CN) через X-Client-CN (HAProxy header).
|
||||
|
||||
uvicorn 0.30.6 не передаёт ssl_object в scope; HAProxy ставит X-Client-CN
|
||||
после успешного mTLS с client cert (crt lb-client.pem). Тест имитирует LB:
|
||||
- client cert валиден (lb-client) → X-Client-CN=lb-client → 401 (не 403)
|
||||
- client cert с CN=api-1 → X-Client-CN=api-1 → 403 (identity не разрешена)
|
||||
|
||||
Сценарии:
|
||||
1. Без client cert / без X-Client-CN → 403 (нет identity)
|
||||
2. CN=api-1 (запрещённый) → 403
|
||||
3. CN=lb-client (разрешённый) → 401 (нет Bearer, но identity пропущена)
|
||||
4. Чужой CA → handshake failed (проверка TLS)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import socket
|
||||
import ssl
|
||||
import sys
|
||||
|
||||
|
||||
def tls_request(host, port, ca_file, client_cert=None, client_key=None,
|
||||
extra_headers=None, sni_hostname=None, timeout=5):
|
||||
"""TLS-запрос к API. Возвращает (ok, status_or_error)."""
|
||||
ctx = ssl.create_default_context(cafile=ca_file)
|
||||
ctx.check_hostname = True
|
||||
ctx.verify_mode = ssl.CERT_REQUIRED
|
||||
if client_cert and client_key:
|
||||
ctx.load_cert_chain(client_cert, client_key)
|
||||
|
||||
try:
|
||||
with socket.create_connection((host, port), timeout=timeout) as sock:
|
||||
with ctx.wrap_socket(sock, server_hostname=sni_hostname or host) as ssock:
|
||||
request = b"GET /api/v1/users/me HTTP/1.1\r\nHost: localhost\r\n"
|
||||
for k, v in (extra_headers or {}).items():
|
||||
request += f"{k}: {v}\r\n".encode()
|
||||
request += b"Connection: close\r\n\r\n"
|
||||
ssock.sendall(request)
|
||||
response = b""
|
||||
while True:
|
||||
chunk = ssock.recv(4096)
|
||||
if not chunk:
|
||||
break
|
||||
response += chunk
|
||||
if not response:
|
||||
return False, "empty response"
|
||||
status = int(response.split(b" ")[1])
|
||||
return True, status
|
||||
except ssl.SSLError as exc:
|
||||
return False, f"SSLError: {exc}"
|
||||
except (ConnectionError, OSError) as exc:
|
||||
return False, f"ConnectionError: {exc}"
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("--base-url", default="https://api:8080",
|
||||
help="Прямой к API (изнутри Docker-сети)")
|
||||
p.add_argument("--ca-file", required=True)
|
||||
p.add_argument("--certs-dir", default="/certs")
|
||||
p.add_argument("--sni-hostname", default="api")
|
||||
args = p.parse_args()
|
||||
|
||||
url = args.base_url.replace("https://", "").replace("http://", "")
|
||||
host, _, port_s = url.partition(":")
|
||||
port = int(port_s) if port_s else 443
|
||||
sni = args.sni_hostname
|
||||
certs = args.certs_dir
|
||||
failures = 0
|
||||
|
||||
# 1. Без client cert → handshake failed
|
||||
ok, err = tls_request(host, port, args.ca_file, sni_hostname=sni)
|
||||
if ok:
|
||||
print(f"FAIL: без client cert ожидали handshake error, получили status={err}")
|
||||
failures += 1
|
||||
else:
|
||||
print(f"PASS: без client cert → {err}")
|
||||
|
||||
# 2. Чужой CA → handshake failed
|
||||
import subprocess, tempfile
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
fk = f"{tmp}/ca.key"; fc = f"{tmp}/ca.crt"
|
||||
ck = f"{tmp}/client.key"; cc = f"{tmp}/client.crt"
|
||||
subprocess.run(["openssl", "genrsa", "-out", fk, "2048"], check=True, capture_output=True)
|
||||
subprocess.run(["openssl", "req", "-x509", "-new", "-nodes", "-key", fk,
|
||||
"-sha256", "-days", "1", "-out", fc, "-subj", "/O=foreign/CN=foreign-ca"],
|
||||
check=True, capture_output=True)
|
||||
subprocess.run(["openssl", "genrsa", "-out", ck, "2048"], check=True, capture_output=True)
|
||||
subprocess.run(["openssl", "req", "-new", "-key", ck, "-out", f"{tmp}/c.csr",
|
||||
"-subj", "/O=messenger/OU=lb/CN=lb-client"],
|
||||
check=True, capture_output=True)
|
||||
subprocess.run(["openssl", "x509", "-req", "-in", f"{tmp}/c.csr",
|
||||
"-CA", fc, "-CAkey", fk, "-CAcreateserial",
|
||||
"-out", cc, "-days", "1", "-sha256"],
|
||||
check=True, capture_output=True)
|
||||
ok, err = tls_request(host, port, args.ca_file, cc, ck, sni_hostname=sni)
|
||||
if ok:
|
||||
print(f"FAIL: с чужим CA ожидали handshake error, получили {err}")
|
||||
failures += 1
|
||||
else:
|
||||
print(f"PASS: чужой CA → {err}")
|
||||
|
||||
# 3. CN=api-1 (запрещённая) → 403
|
||||
ok, err = tls_request(host, port, args.ca_file,
|
||||
f"{certs}/api-1.crt", f"{certs}/api-1.key",
|
||||
extra_headers={"X-Client-CN": "api-1",
|
||||
"X-Client-OU": "api",
|
||||
"X-Client-O": "messenger"},
|
||||
sni_hostname=sni)
|
||||
if not ok:
|
||||
print(f"FAIL: CN=api-1 — TLS error: {err}")
|
||||
failures += 1
|
||||
elif err != 403:
|
||||
print(f"FAIL: CN=api-1 — ожидали 403, получили {err}")
|
||||
failures += 1
|
||||
else:
|
||||
print(f"PASS: CN=api-1 (запрещённая identity) → 403")
|
||||
|
||||
# 4. CN=lb-client (разрешённая) → 401 (нет Bearer, но identity пропущена)
|
||||
ok, err = tls_request(host, port, args.ca_file,
|
||||
f"{certs}/lb-client.crt", f"{certs}/lb-client.key",
|
||||
extra_headers={"X-Client-CN": "lb-client",
|
||||
"X-Client-OU": "lb",
|
||||
"X-Client-O": "messenger"},
|
||||
sni_hostname=sni)
|
||||
if not ok:
|
||||
print(f"FAIL: CN=lb-client — TLS error: {err}")
|
||||
failures += 1
|
||||
elif err == 403:
|
||||
print(f"FAIL: CN=lb-client — всё ещё 403, middleware не пропускает")
|
||||
failures += 1
|
||||
else:
|
||||
print(f"PASS: CN=lb-client (разрешённая) → {err} (не 403)")
|
||||
|
||||
# 5. Без X-Client-CN → 403
|
||||
ok, err = tls_request(host, port, args.ca_file,
|
||||
f"{certs}/lb-client.crt", f"{certs}/lb-client.key",
|
||||
sni_hostname=sni)
|
||||
if ok and err == 403:
|
||||
print(f"PASS: без X-Client-CN → 403")
|
||||
else:
|
||||
print(f"FAIL: без X-Client-CN — ожидали 403, получили {err}")
|
||||
failures += 1
|
||||
|
||||
if failures:
|
||||
print(f"\nFAIL: {failures} проверок провалено")
|
||||
sys.exit(1)
|
||||
print("\nPASS: mTLS identity проверяется (X-Client-CN, scoped CN)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user