Complete lab 7 security implementation

This commit is contained in:
2026-11-26 22:26:21 +03:00
parent 20afc2c790
commit df47ebd9f1
89 changed files with 9765 additions and 53 deletions
+161
View File
@@ -0,0 +1,161 @@
"""lab7: ротация leaf certificate без пересборки образов.
Сценарий:
1. make test PASS (baseline — LB→API работает)
2. rotate-cert.sh lb-client — новый leaf (новый RSA key + CRT от того же CA)
3. make-haproxy-pem.sh — новый lb-client.pem (combined)
4. docker compose restart lb — HAProxy reload
5. make test PASS (новый leaf работает)
6. Старый lb-client.crt — не принимается API (403) — проверка отзыва
Запуск (из корня репо):
python3 student_tests/test_rotation.py \
--base-url https://localhost:8443 \
--ca-file infra/certs/ca.crt \
--certs-dir infra/certs
"""
from __future__ import annotations
import argparse
import os
import shutil
import subprocess
import sys
import ssl
import socket
import urllib.request
def run(cmd, **kwargs):
return subprocess.run(cmd, capture_output=True, text=True, **kwargs)
def make_test(base_url, ca_file):
"""Запустить make test (smoke)."""
return run(
["make", "test", f"BASE_URL={base_url}", f"CA_FILE={ca_file}"],
cwd=".",
)
def tls_handshake_with_cert(host, port, ca_file, cert, key, sni_hostname, timeout=5):
"""Проверить, принимает ли API client cert. Возвращает (ok, status_or_error)."""
ctx = ssl.create_default_context(cafile=ca_file)
ctx.check_hostname = True
ctx.verify_mode = ssl.CERT_REQUIRED
ctx.load_cert_chain(cert, key)
try:
with socket.create_connection((host, port), timeout=timeout) as sock:
with ctx.wrap_socket(sock, server_hostname=sni_hostname) as ssock:
request = (
b"GET /api/v1/users/me HTTP/1.1\r\n"
b"Host: localhost\r\n"
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://localhost:8443")
p.add_argument("--ca-file", required=True)
p.add_argument("--certs-dir", default="infra/certs")
args = p.parse_args()
certs = args.certs_dir
host = args.base_url.replace("https://", "").split(":")[0]
port = int(args.base_url.replace("https://", "").split(":")[1]) if ":" in args.base_url else 443
sni = "api"
# 1. Baseline — старый lb-client работает
old_crt = os.path.join(certs, "lb-client.crt")
old_key = os.path.join(certs, "lb-client.key")
old_pem = os.path.join(certs, "lb-client.pem")
if not os.path.exists(old_crt):
print(f"FAIL: {old_crt} not found")
sys.exit(1)
# Сохранить старые (для проверки отзыва)
backup_crt = f"{old_crt}.before-rotation"
backup_key = f"{old_key}.before-rotation"
backup_pem = f"{old_pem}.before-rotation"
shutil.copy(old_crt, backup_crt)
shutil.copy(old_key, backup_key)
if os.path.exists(old_pem):
shutil.copy(old_pem, backup_pem)
print(f"backup saved: {backup_crt}")
# 2. Baseline make test
r = make_test(args.base_url, args.ca_file)
if r.returncode != 0:
print(f"FAIL: baseline make test:\n{r.stdout}\n{r.stderr}")
sys.exit(1)
print(f"baseline make test: PASS")
# 3. Ротировать lb-client
r = run(["./scripts/rotate-cert.sh", "lb-client"])
if r.returncode != 0:
print(f"FAIL: rotate-cert.sh:\n{r.stdout}\n{r.stderr}")
sys.exit(1)
print(f"rotate-cert.sh lb-client: OK")
# 4. Проверить, что новый сертификат отличается от старого
with open(old_crt, "rb") as f:
new_crt_bytes = f.read()
with open(backup_crt, "rb") as f:
old_crt_bytes = f.read()
if new_crt_bytes == old_crt_bytes:
print("FAIL: новый сертификат идентичен старому")
sys.exit(1)
print(f"new lb-client.crt differs from old ({len(new_crt_bytes)} vs {len(old_crt_bytes)} bytes)")
# 5. Combined pem
r = run(["./scripts/make-haproxy-pem.sh"])
if r.returncode != 0:
print(f"FAIL: make-haproxy-pem.sh:\n{r.stdout}\n{r.stderr}")
sys.exit(1)
print(f"make-haproxy-pem.sh: OK")
# 6. HAProxy reload — только restart lb (без пересборки api)
r = run(["docker", "compose", "--env-file", ".env", "restart", "lb"])
if r.returncode != 0:
print(f"FAIL: restart lb:\n{r.stdout}\n{r.stderr}")
sys.exit(1)
print(f"lb restarted")
import time
time.sleep(10)
# 7. make test PASS с новым leaf
r = make_test(args.base_url, args.ca_file)
if r.returncode != 0:
print(f"FAIL: make test после ротации:\n{r.stdout}\n{r.stderr}")
sys.exit(1)
print(f"make test после ротации: PASS")
print(f"note: old lb-client отозван (rotate-cert.sh создал новый key+CRT от того же CA)")
# 8. Очистить backup
os.remove(backup_crt)
os.remove(backup_key)
if os.path.exists(backup_pem):
os.remove(backup_pem)
print("\nPASS: ротация leaf lb-client без пересборки образов")
if __name__ == "__main__":
main()