feat: complete lab 7 grade 4 security controls and report

This commit is contained in:
Dmitrii Grishko
2026-11-15 21:58:27 +03:00
parent c5e3ac3aff
commit c69d735692
52 changed files with 1124 additions and 129 deletions
+28 -8
View File
@@ -6,21 +6,30 @@ dir=secrets/tls
mkdir -p "$dir"
chmod 700 "$dir"
make_key() {
if [ "$algorithm" = ec ]; then
openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out "$dir/$name.key"
else
openssl genpkey -algorithm ED25519 -out "$dir/$name.key"
fi
}
make_ca() {
name=$1
name=$1 algorithm=${2:-ed25519}
if [ ! -e "$dir/$name.crt" ]; then
openssl req -x509 -newkey ed25519 -nodes -days 365 \
make_key
openssl req -x509 -new -key "$dir/$name.key" -days 365 \
-subj "/CN=$name" -addext "basicConstraints=critical,CA:TRUE,pathlen:0" \
-addext "keyUsage=critical,keyCertSign,cRLSign" \
-keyout "$dir/$name.key" -out "$dir/$name.crt"
-out "$dir/$name.crt"
fi
}
make_leaf() {
name=$1 ca=$2 usage=$3 san=$4
name=$1 ca=$2 usage=$3 san=$4 algorithm=${5:-ed25519}
if [ ! -e "$dir/$name.crt" ]; then
openssl req -new -newkey ed25519 -nodes -subj "/CN=$name" \
-keyout "$dir/$name.key" -out "$dir/$name.csr"
make_key
openssl req -new -key "$dir/$name.key" -subj "/CN=$name" -out "$dir/$name.csr"
printf 'basicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature\nextendedKeyUsage=%s\nsubjectAltName=%s\nsubjectKeyIdentifier=hash\nauthorityKeyIdentifier=keyid:always\n' \
"$usage" "$san" > "$dir/$name.ext"
openssl x509 -req -in "$dir/$name.csr" -CA "$dir/$ca.crt" -CAkey "$dir/$ca.key" \
@@ -34,7 +43,9 @@ make_leaf() {
make_ca lab7-ca
make_ca untrusted-ca
chmod 644 "$dir/lab7-ca.crt"
make_leaf ingress lab7-ca serverAuth DNS:localhost,IP:127.0.0.1
make_ca lab7-ingress-ca ec
chmod 644 "$dir/lab7-ingress-ca.crt"
make_leaf ingress-browser lab7-ingress-ca serverAuth DNS:localhost,IP:127.0.0.1 ec
make_leaf api lab7-ca serverAuth DNS:api
for service in db redis s3 broker; do
san="DNS:$service"
@@ -59,6 +70,11 @@ chmod 644 "$dir/telemetry-ingest-ca.crt"
for role in api worker dispatcher; do
make_leaf "otel-$role" telemetry-ingest-ca clientAuth "URI:urn:lab7:otel:$role"
done
make_ca broker-client-ca
chmod 644 "$dir/broker-client-ca.crt"
for role in dispatcher worker unregistered; do
make_leaf "messenger_$role" broker-client-ca clientAuth "URI:urn:lab7:broker:$role"
done
make_leaf openbao lab7-ca serverAuth DNS:openbao,DNS:localhost,IP:127.0.0.1
for role in api worker dispatcher cleanup; do
make_leaf "bao-$role" lab7-ca clientAuth "URI:urn:lab7:bao:$role"
@@ -66,7 +82,11 @@ done
make_leaf lb lab7-ca clientAuth URI:urn:lab7:load-balancer
make_leaf wrong-role lab7-ca clientAuth URI:urn:lab7:probe
make_leaf wrong-ca untrusted-ca clientAuth URI:urn:lab7:load-balancer
for name in ingress lb; do
# The Collector trusts only the leaf certificates registered for ingest.
cat "$dir/otel-api.crt" "$dir/otel-worker.crt" "$dir/otel-dispatcher.crt" > "$dir/telemetry-ingest-clients.crt"
chmod 644 "$dir/telemetry-ingest-clients.crt"
make_leaf otel-wrong-role telemetry-ingest-ca clientAuth URI:urn:lab7:otel:unregistered
for name in ingress-browser lb; do
cat "$dir/$name.crt" "$dir/$name.key" > "$dir/$name.pem"
chmod 644 "$dir/$name.pem"
done
+1 -1
View File
@@ -19,7 +19,7 @@ def request(context, path, *, body=None, token="", status=200):
try:
with urlopen(req, context=context, timeout=5) as response:
assert response.status == status, (path, response.status, status)
return json.load(response)
return json.load(response) if response.status != 204 else None
except HTTPError as error:
assert error.code == status, (path, error.code, status)
+11 -1
View File
@@ -4,6 +4,7 @@ import json
import subprocess
APP_ROLES = {"api", "worker", "dispatcher", "upload-cleanup"}
READ_ONLY = APP_ROLES | {"haproxy", "otel-collector", "prometheus", "loki", "tempo", "grafana"}
ALLOWED_PORTS = {("haproxy", "8443/tcp"), ("grafana", "3000/tcp"),
("openbao", "8200/tcp"), ("s3", "9000/tcp")}
@@ -21,6 +22,15 @@ def main():
for port, bindings in (config.get("PortBindings") or {}).items():
assert (name, port) in ALLOWED_PORTS, (name, port)
assert all(binding["HostIp"] == "127.0.0.1" for binding in bindings), name
if name in READ_ONLY:
assert config["ReadonlyRootfs"] and config["CapDrop"] == ["ALL"], name
assert "no-new-privileges:true" in config["SecurityOpt"], name
assert config["Memory"] > 0 and config["NanoCpus"] > 0, name
assert config["Tmpfs"], name
if name == "worker":
env = dict(item.split("=", 1) for item in service["Config"]["Env"] if "=" in item)
assert 0 < int(env["JOB_TIMEOUT_SECONDS"]) <= 60, name
assert config["Memory"] <= 512 * 1024 * 1024 and config["NanoCpus"] <= 10**9, name
if name in APP_ROLES:
assert service["Config"]["User"] == "app:app", name
assert config["CapDrop"] == ["ALL"] and not config["CapAdd"], name
@@ -29,7 +39,7 @@ def main():
assert not any(path.startswith("/run/secrets") for path in mounts), name
assert not any("BAO_TOKEN=" in field for field in service["Config"]["Env"]), name
assert APP_ROLES <= {svc["Config"]["Labels"]["com.docker.compose.service"] for svc in services}
print("PASS: local-only ports, runtime secrets on tmpfs, non-root app roles with limits and dropped capabilities")
print("PASS: local ports, read-only app/ingress/telemetry, no-new-privileges, dropped capabilities, worker CPU/RAM/time budget")
if __name__ == "__main__":
+4 -2
View File
@@ -13,7 +13,7 @@ import http.client
TLS = Path(__file__).resolve().parents[1] / "secrets/tls"
def query(service, port, path, params):
def query(service, port, path, params, *, allow_missing=False):
context = ssl.create_default_context(cafile=str(TLS / "lab7-ca.crt"))
context.load_cert_chain(TLS / "grafana-reader.crt", TLS / "grafana-reader.key")
container = subprocess.check_output(["docker", "compose", "ps", "-q", service], text=True).strip()
@@ -26,6 +26,8 @@ def query(service, port, path, params):
try:
connection.request("GET", f"{path}?{urlencode(params)}")
response = connection.getresponse()
if allow_missing and response.status == 404:
return None
assert response.status == 200, (service, response.status)
return json.load(response)
finally:
@@ -35,7 +37,7 @@ def query(service, port, path, params):
def main():
try:
with urlopen("https://localhost:8443/api/v1/users/me", context=ssl.create_default_context(
cafile=str(TLS / "lab7-ca.crt")), timeout=5):
cafile=str(TLS / "lab7-ingress-ca.crt")), timeout=5):
raise AssertionError("Anonymous request should be rejected")
except HTTPError as error:
assert error.code == 401
+12 -4
View File
@@ -9,7 +9,7 @@ from pathlib import Path
TLS = Path(__file__).resolve().parents[1] / "secrets/tls"
ENDPOINTS = (
("s3", 9000, None, False),
("broker", 5671, None, False),
("broker", 5671, "messenger_worker", False),
("redis", 6379, None, False),
("db", 5432, None, True),
("otel-collector", 4318, "otel-api", False),
@@ -34,7 +34,7 @@ def probe(address, service, port, identity, pg, ca):
assert conn.recv(1) == b"S", "PostgreSQL did not accept TLS negotiation"
with context.wrap_socket(conn, server_hostname=service) as encrypted:
assert encrypted.version() in {"TLSv1.2", "TLSv1.3"}
if identity:
if identity or (service, port) == ("otel-collector", 4318):
encrypted.sendall(b"GET / HTTP/1.0\r\n\r\n")
encrypted.recv(1)
@@ -52,9 +52,17 @@ def main():
pass
else:
raise AssertionError(f"{service}:{port} accepted a foreign CA")
if identity:
if (service, port) == ("otel-collector", 4318):
try:
probe(address, service, port, "wrong-role", pg, "lab7-ca")
probe(address, service, port, None, pg, "lab7-ca")
except ssl.SSLError:
print("PASS Collector: missing client certificate rejected")
else:
raise AssertionError("Collector accepted an anonymous client")
if identity:
foreign = "otel-wrong-role" if (service, port) == ("otel-collector", 4318) else "wrong-role"
try:
probe(address, service, port, foreign, pg, "lab7-ca")
except ssl.SSLError:
pass
else:
+91
View File
@@ -0,0 +1,91 @@
#!/usr/bin/env python3
"""Exercise AMQP EXTERNAL authentication and role ACLs on new connections."""
import socket
import ssl
import struct
import subprocess
from pathlib import Path
TLS = Path(__file__).resolve().parents[1] / "secrets/tls"
def read_exact(conn, size):
result = bytearray()
while len(result) < size:
chunk = conn.recv(size - len(result))
if not chunk:
raise EOFError("RabbitMQ closed the connection")
result.extend(chunk)
return bytes(result)
def read_method(conn):
kind, _, size = struct.unpack(">BHI", read_exact(conn, 7))
assert kind == 1 and size >= 4
body = read_exact(conn, size)
assert read_exact(conn, 1) == b"\xce"
return struct.unpack(">HH", body[:4]), body[4:]
def send_method(conn, channel, klass, method, args):
body = struct.pack(">HH", klass, method) + args
conn.sendall(struct.pack(">BHI", 1, channel, len(body)) + body + b"\xce")
def short(value):
return bytes([len(value)]) + value
def authenticate(conn):
conn.sendall(b"AMQP\x00\x00\x09\x01")
method, data = read_method(conn)
assert method == (10, 10) and b"EXTERNAL" in data
send_method(conn, 0, 10, 11, b"\x00" * 4 + short(b"EXTERNAL") + b"\x00" * 4 + short(b"en_US"))
try:
method, data = read_method(conn)
except EOFError:
return False
if method == (10, 50):
assert struct.unpack_from(">H", data)[0] == 403
return False
assert method == (10, 30)
send_method(conn, 0, 10, 31, data)
send_method(conn, 0, 10, 40, short(b"/") + short(b"") + b"\x00")
assert read_method(conn)[0] == (10, 41)
return True
def main():
container = subprocess.check_output(["docker", "compose", "ps", "-q", "broker"], text=True).strip()
address = subprocess.check_output(["docker", "inspect", "-f",
'{{(index .NetworkSettings.Networks "highload-lab7_data").IPAddress}}', container], text=True).strip()
for identity in (None, "wrong-role", "messenger_unregistered", "messenger_worker", "messenger_dispatcher"):
context = ssl.create_default_context(cafile=str(TLS / "lab7-ca.crt"))
if identity:
context.load_cert_chain(TLS / f"{identity}.crt", TLS / f"{identity}.key")
with socket.create_connection((address, 5671), timeout=5) as tcp:
try:
with context.wrap_socket(tcp, server_hostname="broker") as conn:
admitted = authenticate(conn)
assert admitted == (identity in ("messenger_worker", "messenger_dispatcher"))
if admitted:
send_method(conn, 1, 20, 10, short(b""))
assert read_method(conn)[0] == (20, 11)
# Worker cannot publish. Dispatcher cannot read using basic.get.
if identity == "messenger_worker":
send_method(conn, 1, 60, 40, b"\x00\x00" + short(b"") + short(b"attachments.v1") + b"\x00")
conn.sendall(struct.pack(">BHIHHQH", 2, 1, 14, 60, 0, 0, 0) + b"\xce")
else:
send_method(conn, 1, 60, 70, b"\x00\x00" + short(b"attachments.v1") + b"\x01")
method, data = read_method(conn)
assert method == (20, 40) and struct.unpack_from(">H", data)[0] == 403
except ssl.SSLError:
if identity not in (None, "wrong-role"):
raise
else:
assert identity not in (None, "wrong-role"), "TLS accepted an untrusted peer"
print(f"PASS: {identity or 'no certificate'}")
if __name__ == "__main__":
main()
+118
View File
@@ -0,0 +1,118 @@
#!/usr/bin/env python3
"""Rotate a real API database password and OpenBao client leaf on the lab stand."""
import json
import os
import secrets
import ssl
import subprocess
import time
from pathlib import Path
from urllib.error import HTTPError
from urllib.parse import urlsplit, urlunsplit
from check_bao_roles import request
ROOT = Path(__file__).resolve().parents[1]
FILES = ROOT / "secrets"
TLS = FILES / "tls"
CA = TLS / "lab7-ca.crt"
def run(*args, **kwargs):
return subprocess.run(args, cwd=ROOT, check=True, **kwargs)
def identity(cert, key):
context = ssl.create_default_context(cafile=str(CA))
context.load_cert_chain(cert, key)
return context
def main():
admin = json.loads((FILES / "bao-operator.json").read_text())["root_token"]
base = ssl.create_default_context(cafile=str(CA))
old = identity(TLS / "bao-api.crt", TLS / "bao-api.key")
login = lambda ctx: request(ctx, "auth/cert/login", body={"name": "api"})["auth"]
policy_path = "auth/cert/certs/api"
secret_path = "messenger/data/api"
old_auth = login(old)
values = request(old, secret_path, token=old_auth["client_token"])["data"]["data"]
old_password = urlsplit(values["database_url"]).password
password = secrets.token_hex(24)
for name in ("bao-api-next.crt", "bao-api-next.key"):
if (TLS / name).exists():
(TLS / name).unlink()
run("openssl", "req", "-new", "-newkey", "ed25519", "-nodes", "-subj", "/CN=bao-api",
"-keyout", str(TLS / "bao-api-next.key"), "-out", str(TLS / "bao-api-next.csr"),
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
run("openssl", "x509", "-req", "-in", str(TLS / "bao-api-next.csr"), "-CA", str(CA),
"-CAkey", str(TLS / "lab7-ca.key"), "-CAcreateserial", "-days", "30",
"-extfile", "/dev/stdin", "-out", str(TLS / "bao-api-next.crt"), input=
"basicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature\nextendedKeyUsage=clientAuth\n"
"subjectAltName=URI:urn:lab7:bao:api\nsubjectKeyIdentifier=hash\nauthorityKeyIdentifier=keyid:always\n",
text=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
new_cert, new_key = TLS / "bao-api-next.crt", TLS / "bao-api-next.key"
new = identity(new_cert, new_key)
leaf = new_cert.read_text()
def role(ttl):
request(base, policy_path, token=admin, status=204, body={
"certificate": leaf, "token_policies": ["api"], "token_no_default_policy": True,
"token_ttl": ttl, "token_max_ttl": ttl,
})
def db_login(candidate, allowed):
result = subprocess.run(["docker", "compose", "exec", "-T", "db", "sh", "-ec",
'IFS= read -r PGPASSWORD; export PGPASSWORD PGCHANNELBINDING=disable '
'PGSSLMODE=verify-full PGSSLROOTCERT=/run/tls/ca.crt; '
'psql -X -h db -U messenger_api "$POSTGRES_DB" -Atc "SELECT 1"'],
cwd=ROOT, input=candidate+"\n", text=True, capture_output=True)
assert (result.returncode == 0 and result.stdout.strip() == "1") == allowed
if not allowed:
assert "password authentication failed" in result.stderr
role("3s")
try:
request(old, "auth/cert/login", body={"name": "api"}, status=400)
request(base, "auth/token/revoke-accessor", token=admin, status=204,
body={"accessor": old_auth["accessor"]})
request(old, secret_path, token=old_auth["client_token"], status=403)
auth = login(new)
request(new, secret_path, token=auth["client_token"])
time.sleep(auth["lease_duration"] + 1)
request(new, secret_path, token=auth["client_token"], status=403)
print("PASS: replaced leaf, revoked old token, expired short-lived token")
finally:
role("15m")
for source, target in ((new_cert, TLS / "bao-api.crt"), (new_key, TLS / "bao-api.key")):
source.chmod(0o644)
os.replace(source, target)
(TLS / "bao-api-next.csr").unlink(missing_ok=True)
db_login(old_password, True)
run("docker", "compose", "exec", "-T", "db", "sh", "-ec",
'psql -X -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" "$POSTGRES_DB"',
text=True, input=f"ALTER ROLE messenger_api PASSWORD '{password}';\n", stdout=subprocess.DEVNULL)
parts = urlsplit(values["database_url"])
values["database_url"] = urlunsplit(parts._replace(netloc=f"{parts.username}:{password}@{parts.hostname}:{parts.port}"))
request(base, secret_path, token=admin, status=200, body={"data": values})
for path, content in (("database_api_password", password), ("database_api_url", values["database_url"])):
(FILES / path).write_text(content + "\n")
db_login(old_password, False)
db_login(password, True)
run("docker", "compose", "up", "-d", "--no-deps", "--no-build", "--force-recreate", "api")
run("./scripts/wait_ingress.sh")
print("PASS: database secret rotated, old password refused, API ready without rebuilding")
try:
request(base, "sys/seal", token=admin, status=204, body={})
request(new, "auth/cert/login", body={"name": "api"}, status=503)
run("./scripts/wait_ingress.sh")
print("PASS: sealed OpenBao denies new login; running API remains ready using loaded credentials")
finally:
run("python3", "scripts/bao_operator.py", "unseal")
run("python3", "scripts/check_bao_roles.py")
if __name__ == "__main__":
main()
+66
View File
@@ -0,0 +1,66 @@
"""Verify rehash in PostgreSQL and measure rejected concurrent login work."""
import base64
import concurrent.futures
import json
import os
import ssl
import subprocess
import sys
import time
from pathlib import Path
from urllib.error import HTTPError
from urllib.request import Request, urlopen
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client
def main():
ca = "secrets/tls/lab7-ingress-ca.crt"
endpoint = "https://localhost:8443"
api = Client(endpoint, ca)
actor = api.user("rehash")
registration = actor["registration"]
user_id = actor["id"]
def sql(statement):
return subprocess.check_output(["docker", "compose", "exec", "-T", "db", "sh", "-ec",
'psql -X -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" "$POSTGRES_DB" -At'],
text=True, input=statement, cwd=ROOT).strip()
# Derive a synthetic legacy hash with the same Go implementation in the test image.
legacy = subprocess.check_output(["docker", "compose", "--profile", "test", "run", "--rm", "-T",
"--no-deps", "-e", "LAB7_REHASH_FIXTURE", "backend-tests",
"go", "test", "./backend/services", "-run", "^TestPrintLegacyFixture$", "-v"],
cwd=ROOT, text=True, env=os.environ | {"LAB7_REHASH_FIXTURE": registration["password"]})
old = next(line for line in legacy.splitlines() if line.startswith("$argon2id$"))
sql(f"UPDATE users SET password_hash=convert_to('{old}','UTF8') WHERE id='{user_id}';")
auth = "Basic " + base64.b64encode(
f"{registration['username']}:{registration['password']}".encode()).decode()
api.call("POST", "/api/v1/auth/sessions", 201, headers={"Authorization": auth}, schema="Session")
assert sql(f"SELECT split_part(convert_from(password_hash,'UTF8'),'$',4) FROM users WHERE id='{user_id}';") == "m=65536,t=3,p=2"
print("PASS: successful login upgraded the stored legacy Argon2id hash")
context = ssl.create_default_context(cafile=ca)
def login(_):
started = time.monotonic()
req = Request(endpoint + "/api/v1/auth/sessions", data=b"", headers={"Authorization": auth})
try:
with urlopen(req, context=context, timeout=10) as response:
return response.status, time.monotonic()-started
except HTTPError as error:
assert error.code == 429 and error.headers["Retry-After"]
return error.code, time.monotonic()-started
with concurrent.futures.ThreadPoolExecutor(max_workers=24) as pool:
result = list(pool.map(login, range(24)))
status = {code: sum(c == code for c, _ in result) for code in (201, 429)}
assert all(status.values()), status
latencies = sorted(duration for _, duration in result)
print(json.dumps({"requests": len(result), "status": status,
"p50_ms": round(latencies[11]*1000), "max_ms": round(latencies[-1]*1000)}))
if __name__ == "__main__":
main()
+56
View File
@@ -0,0 +1,56 @@
"""Send a synthetic marker as a credential and check exported signals for it."""
import base64
import json
import secrets
import ssl
import subprocess
import time
from urllib.error import HTTPError
from urllib.request import Request, urlopen
from check_grade3_signals import TLS, query
def main():
marker = "lab7-secret-" + secrets.token_hex(16)
encoded = base64.b64encode(("lab7_probe:" + marker).encode()).decode()
context = ssl.create_default_context(cafile=str(TLS / "lab7-ingress-ca.crt"))
started = int(time.time()) - 1
req = Request("https://localhost:8443/api/v1/auth/sessions", data=b"",
headers={"Authorization": "Basic " + encoded})
try:
with urlopen(req, context=context, timeout=5):
raise AssertionError("Synthetic invalid login succeeded")
except HTTPError as error:
assert error.code == 401
request_id = error.headers["X-Request-Id"]
assert request_id
for _ in range(30):
now = int(time.time()) + 1
selector = '{service_name="messenger-api"} | request_id=`' + request_id + '`'
window = {"start": started * 10**9, "end": now * 10**9, "limit": 10}
logs = query("loki", 3100, "/loki/api/v1/query_range",
{**window, "query": selector})
correlated = query("loki", 3100, "/loki/api/v1/query_range",
{**window, "query": selector + ' | line_format "{{.trace_id}}"'})
trace_id = next((entry[1] for stream in correlated["data"]["result"]
for entry in stream["values"] if len(entry[1]) == 32), None)
if trace_id:
trace = query("tempo", 3200, "/api/traces/" + trace_id, {}, allow_missing=True)
metrics = query("prometheus", 9090, "/api/v1/query", {
"query": 'messenger_http_requests_total{http_route="/api/v1/auth/sessions",http_status_class="4xx"}',
})["data"]["result"]
if trace and metrics:
break
time.sleep(2)
else:
raise AssertionError("Missing correlated log, trace or ingress metric for synthetic request")
container_logs = subprocess.check_output(
["docker", "compose", "logs", "--since", str(started), "api", "otel-collector"], text=True)
for output in (json.dumps(logs), json.dumps(trace), json.dumps(metrics), container_logs):
assert marker not in output and encoded not in output
print("PASS: synthetic Basic secret absent from correlated log, correlated trace, metric labels and container logs")
if __name__ == "__main__":
main()
+1 -1
View File
@@ -9,7 +9,7 @@ from urllib.request import Request, urlopen
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--base-url", default="https://localhost:8443")
parser.add_argument("--ca-file", default="secrets/tls/lab7-ca.crt")
parser.add_argument("--ca-file", default="secrets/tls/lab7-ingress-ca.crt")
args = parser.parse_args()
context = ssl.create_default_context(cafile=args.ca_file)
instances = set()
+1 -1
View File
@@ -7,4 +7,4 @@ test -n "$replica"
trap 'docker compose start api >/dev/null' EXIT
TARGET_INSTANCE_ID="$replica" ./scripts/stop-one.sh
./scripts/wait_ingress.sh
make test CA_FILE=secrets/tls/lab7-ca.crt
make test CA_FILE=secrets/tls/lab7-ingress-ca.crt
+5 -5
View File
@@ -7,7 +7,7 @@ import subprocess
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
CA = "secrets/tls/lab7-ca.crt"
CA = "secrets/tls/lab7-ingress-ca.crt"
OUTPUT = ROOT / "evidence"
VALIDATION = {"CA_FILE": str(ROOT / CA)}
CHECKS = {
@@ -64,10 +64,10 @@ CHECKS = {
}
def main():
def main(checks=CHECKS):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--only", nargs="+", choices=CHECKS)
selected = parser.parse_args().only or CHECKS
parser.add_argument("--only", nargs="+", choices=checks)
selected = parser.parse_args().only or checks
OUTPUT.mkdir(exist_ok=True)
if "grade3-resilience" in selected:
for name in ("restart", "failover"):
@@ -77,7 +77,7 @@ def main():
VALIDATION[f"{name.upper()}_EVIDENCE_FILE"] = str(path)
passed = True
for slug in selected:
title, commands = CHECKS[slug]
title, commands = checks[slug]
report = [f"# {title}", "", "Предпосылки: подготовленный, разблокированный учебный стенд; Docker Compose, Python и локальный CA.", ""]
for command in commands:
result = subprocess.run(command, cwd=ROOT, env=os.environ | VALIDATION,
+35
View File
@@ -0,0 +1,35 @@
"""Collect evidence for the level-4 criteria on the rehearsal stack."""
from collect_grade3 import main
CA = "secrets/tls/lab7-ingress-ca.crt"
CHECKS = {
"grade4-mtls": ("Проверка ролей RabbitMQ и Collector", [
["python3", "scripts/check_grade4_broker.py"],
["python3", "scripts/check_grade3_tls.py"],
["python3", "scripts/check_grade3_signals.py"],
]),
"grade4-login": ("Rehash в PostgreSQL и бюджет защиты входа", [
["docker", "compose", "--profile", "test", "build", "backend-tests"],
["sleep", "60"], ["python3", "scripts/check_grade4_login.py"],
]),
"grade4-lifecycle": ("Ротация секрета и leaf, отзыв, expiry и seal", [
["python3", "scripts/check_grade4_lifecycle.py"],
]),
"grade4-hardening": ("Права контейнеров, лимиты и эксплуатационные границы", [
["python3", "scripts/check_grade3_runtime.py"],
]),
"grade4-audit": ("Сетевой аудит, ACL и отсутствие контрольного секрета в телеметрии", [
["python3", "scripts/check_grade3_tls.py"],
["python3", "scripts/check_grade4_broker.py"],
["./scripts/check_dependency_roles.sh"],
["python3", "scripts/check_bao_roles.py"],
["sleep", "60"], ["python3", "scripts/check_grade3_http.py", "--ca-file", CA],
["python3", "scripts/check_grade4_telemetry.py"],
]),
"grade4-scan": ("Сканирование зависимостей и образов", [
["./scripts/scan_grade4.sh"],
]),
}
if __name__ == "__main__":
main(CHECKS)
-2
View File
@@ -54,8 +54,6 @@ def main():
names = {"database_url": f"database_{role}_url"}
if role == "api":
names["cache_url"] = "cache_tls_url"
if role in ("worker", "dispatcher"):
names["broker_url"] = f"broker_{role}_url"
if role != "dispatcher":
for key in ("access_key_id", "secret_access_key"):
names[f"s3_{key}"] = f"s3_{role}_{key}"
-3
View File
@@ -95,9 +95,6 @@ def main():
create_secret(f"database_{role}_url",
f"postgres://messenger_{role}:{password}@db:5432/{database}"
"?sslmode=verify-full&sslrootcert=/run/tls/ca.crt")
if role in ("worker", "dispatcher"):
password = create_secret(f"broker_{role}_password", secrets.token_hex(24))
create_secret(f"broker_{role}_url", f"amqps://messenger_{role}:{password}@broker:5671/%2F")
if role != "dispatcher":
create_secret(f"s3_{role}_access_key_id", secrets.token_hex(12))
create_secret(f"s3_{role}_secret_access_key", secrets.token_hex(32))
+2 -2
View File
@@ -6,9 +6,9 @@ if [ -n "${RESTART_EVIDENCE_FILE:-}" ]; then
-f '{{.Name}} {{.State.StartedAt}}' > "$RESTART_EVIDENCE_FILE"
fi
docker compose --project-name highload-lab7 --env-file .env -f compose.yml restart db redis s3 broker >/dev/null
docker compose --project-name highload-lab7 --env-file .env -f compose.yml up -d --wait db redis s3 broker >/dev/null
docker compose start --wait --wait-timeout 45 db redis s3 broker >/dev/null
docker compose --project-name highload-lab7 --env-file .env -f compose.yml restart api upload-cleanup worker dispatcher >/dev/null
docker compose --project-name highload-lab7 --env-file .env -f compose.yml up -d --wait >/dev/null
./scripts/wait_ingress.sh
if [ -n "${RESTART_EVIDENCE_FILE:-}" ]; then
docker compose ps -q db redis s3 broker api | xargs docker inspect \
-f '{{.Name}} {{.State.StartedAt}}' >> "$RESTART_EVIDENCE_FILE"
+26
View File
@@ -0,0 +1,26 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
cache=highload-lab7-trivy-cache
trivy=aquasec/trivy:0.69.3
mkdir -p .memory/scans
docker run --rm -v "$cache:/root/.cache/trivy" -v "$PWD/src:/src:ro" "$trivy" \
fs --timeout 20m --no-progress --quiet --scanners vuln --format json /src > .memory/scans/dependencies.raw
mv .memory/scans/dependencies.raw .memory/scans/dependencies.json
docker compose ps -aq | xargs docker inspect --format '{{.Image}} {{.Config.Image}}' |
sort -u | while read -r image configured; do
archive=$(mktemp)
trap 'rm -f "$archive"' EXIT HUP INT TERM
if ! docker image inspect "$image" >/dev/null 2>&1; then
echo "Container image $image is untagged/unavailable; scanning configured image $configured"
image=$(docker image inspect --format '{{.Id}}' "$configured")
fi
printf 'Scanning %s (%s)\n' "$configured" "$image"
docker image save "$image" -o "$archive"
docker run --rm -v "$cache:/root/.cache/trivy" -v "$archive:/scan.tar:ro" "$trivy" \
image --timeout 15m --no-progress --quiet --input /scan.tar --scanners vuln --format json > ".memory/scans/image-$image.raw"
mv ".memory/scans/image-$image.raw" ".memory/scans/image-$image.json"
rm -f "$archive"
trap - EXIT HUP INT TERM
done
python3 scripts/summarize_grade4_scan.py .memory/scans
+15
View File
@@ -0,0 +1,15 @@
"""Print a compact inventory from raw Trivy JSON."""
import collections
import json
import sys
from pathlib import Path
for path in sorted(Path(sys.argv[1]).glob("*.json")):
report = json.loads(path.read_text())
matches = {}
for target in report.get("Results", []):
for entry in target.get("Vulnerabilities") or []:
key = entry["VulnerabilityID"], entry["PkgName"], entry["InstalledVersion"]
matches[key] = entry
counts = collections.Counter(entry["Severity"] for entry in matches.values())
print(path.name, dict(sorted(counts.items())))
+1 -1
View File
@@ -3,7 +3,7 @@ set -eu
cd "$(dirname "$0")/.."
port=$(docker compose port haproxy 8443)
for attempt in $(seq 1 30); do
if curl --silent --fail --max-time 2 --cacert secrets/tls/lab7-ca.crt \
if curl --silent --fail --max-time 2 --cacert secrets/tls/lab7-ingress-ca.crt \
"https://localhost:${port##*:}/health/ready" >/dev/null; then
exit 0
fi