Реализовать лабораторную 7
This commit is contained in:
@@ -0,0 +1,202 @@
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import ssl
|
||||
import sys
|
||||
import time
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.request import Request, urlopen
|
||||
from urllib.parse import urlencode
|
||||
from uuid import uuid4
|
||||
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
import psycopg
|
||||
import redis
|
||||
|
||||
sys.path.insert(0, "/tests")
|
||||
from client import Client, check
|
||||
|
||||
CA = "/tls/ca.pem"
|
||||
|
||||
|
||||
def tls_context(role=None):
|
||||
context = ssl.create_default_context(cafile=CA)
|
||||
if role:
|
||||
context.load_cert_chain(f"/identities/{role}/cert.pem", f"/identities/{role}/key.pem")
|
||||
return context
|
||||
|
||||
|
||||
def request(url, role, data=None, token=None, method=None):
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if token:
|
||||
headers["X-Vault-Token"] = token
|
||||
req = Request(url, data=json.dumps(data).encode() if data is not None else None,
|
||||
headers=headers, method=method)
|
||||
with urlopen(req, context=tls_context(role), timeout=5) as response:
|
||||
return json.load(response) if response.status != 204 else {}
|
||||
|
||||
|
||||
def credentials(role):
|
||||
auth = request("https://openbao:8200/v1/auth/cert/login", role, {"name": role})["auth"]
|
||||
values = request(f"https://openbao:8200/v1/secret/data/{role}", role,
|
||||
token=auth["client_token"])["data"]["data"]
|
||||
return values, auth
|
||||
|
||||
|
||||
def exchange(host, port, role, data):
|
||||
with socket.create_connection((host, port), timeout=4) as sock:
|
||||
with tls_context(role).wrap_socket(sock, server_hostname=host) as secured:
|
||||
secured.sendall(data)
|
||||
return secured.recv(1024)
|
||||
|
||||
|
||||
def denied(call):
|
||||
try:
|
||||
result = call()
|
||||
except (OSError, URLError, BotoCoreError, ClientError, psycopg.Error, redis.RedisError):
|
||||
return
|
||||
check(not result, "unauthorized connection succeeded")
|
||||
|
||||
|
||||
def main():
|
||||
client = Client("https://lb:8443", CA)
|
||||
actor, _, outsider, chat = client.bootstrap()
|
||||
attachment, _ = client.attachment(actor, chat)
|
||||
client.wait_ready(actor, attachment)
|
||||
client.call("GET", "/api/v1/attachments/" + attachment["id"], 404, actor=outsider)
|
||||
client.call("GET", "/api/v1/users/me", 401, headers={"X-User-Id": actor["id"]})
|
||||
print("PASS: HTTPS API, asynchronous images and cross-user ACL", flush=True)
|
||||
|
||||
try:
|
||||
urlopen("https://lb:8443/health/live", context=ssl.create_default_context(), timeout=5)
|
||||
except URLError as error:
|
||||
check(isinstance(error.reason, ssl.SSLCertVerificationError), "wrong CA test was not a trust failure")
|
||||
else:
|
||||
raise AssertionError("untrusted CA accepted")
|
||||
try:
|
||||
with socket.create_connection(("lb", 8443), timeout=5) as sock:
|
||||
tls_context().wrap_socket(sock, server_hostname="wrong.invalid")
|
||||
except ssl.SSLCertVerificationError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError("wrong hostname accepted")
|
||||
print("PASS: server CA and hostname verification", flush=True)
|
||||
|
||||
get = b"GET /health/ready HTTP/1.0\r\nHost: api-a\r\n\r\n"
|
||||
for target in ("api-a", "api-b"):
|
||||
check(b"200" in exchange(target, 8443, "lb", get), "valid LB identity failed")
|
||||
for role in (None, "foreign", "untrusted", "expired"):
|
||||
denied(lambda: exchange(target, 8443, role, get))
|
||||
denied(lambda: socket.create_connection((target, 8080), timeout=2))
|
||||
print("PASS: both API replicas require allowed LB certificate; plaintext bypass closed", flush=True)
|
||||
|
||||
worker, _ = credentials("worker")
|
||||
dispatcher, _ = credentials("dispatcher")
|
||||
for role, values in (("worker", worker), ("dispatcher", dispatcher)):
|
||||
broker = redis.Redis.from_url(values["BROKER_URL"], ssl_ca_certs=CA,
|
||||
ssl_certfile=f"/identities/{role}/cert.pem", ssl_keyfile=f"/identities/{role}/key.pem",
|
||||
socket_timeout=3)
|
||||
check(broker.ping(), "authorized broker identity failed")
|
||||
if role == "worker":
|
||||
denied(lambda: broker.xadd("images", {"payload": "forbidden"}))
|
||||
else:
|
||||
denied(lambda: broker.xread({"images": "0"}))
|
||||
broker.close()
|
||||
for role in (None, "foreign", "untrusted"):
|
||||
denied(lambda: exchange("broker", 6380, role, b"*1\r\n$4\r\nPING\r\n"))
|
||||
print("PASS: broker mTLS identity and separate producer/consumer ACL", flush=True)
|
||||
|
||||
payload = b"POST /v1/traces HTTP/1.0\r\nHost: otel-collector\r\nContent-Type: application/x-protobuf\r\nContent-Length: 0\r\n\r\n"
|
||||
for role in ("api-a", "worker"):
|
||||
check(b"200" in exchange("otel-collector", 4319, role, payload),
|
||||
"authorized Collector ingest failed")
|
||||
for role in (None, "foreign", "untrusted"):
|
||||
denied(lambda: exchange("otel-collector", 4319, role, payload))
|
||||
print("PASS: Collector requires allowed service identities", flush=True)
|
||||
|
||||
api, auth = credentials("api-a")
|
||||
check(auth["lease_duration"] <= 120, "OpenBao token TTL too long")
|
||||
for path in ("secret/data/worker", "sys/policies/acl"):
|
||||
try:
|
||||
request("https://openbao:8200/v1/" + path, "api-a", token=auth["client_token"])
|
||||
except HTTPError as error:
|
||||
check(error.code == 403, "expected policy denial")
|
||||
else:
|
||||
raise AssertionError("OpenBao policy leaked another service secret")
|
||||
print("PASS: OpenBao scoped read, cross-service and policy access denied, token TTL bounded", flush=True)
|
||||
|
||||
with psycopg.connect(api["DATABASE_URL"], connect_timeout=3) as connection:
|
||||
check(connection.execute("SELECT ssl FROM pg_stat_ssl WHERE pid=pg_backend_pid()").fetchone()[0],
|
||||
"PostgreSQL connection is plaintext")
|
||||
user = connection.execute("SELECT password_hash FROM users WHERE id=%s", (actor["id"],)).fetchone()[0]
|
||||
check(user.startswith(b"$argon2id$"), "registration did not use Argon2id")
|
||||
denied(lambda: psycopg.connect(api["DATABASE_URL"], sslmode="disable", connect_timeout=3))
|
||||
with psycopg.connect(worker["DATABASE_URL"], connect_timeout=3) as connection:
|
||||
try:
|
||||
connection.execute("DELETE FROM users")
|
||||
except psycopg.errors.InsufficientPrivilege:
|
||||
connection.rollback()
|
||||
else:
|
||||
raise AssertionError("worker modified users")
|
||||
print("PASS: PostgreSQL TLS, Argon2id and least-privilege worker role", flush=True)
|
||||
password = actor["registration"]["password"]
|
||||
salt = bytes(range(16))
|
||||
legacy = salt + hashlib.scrypt(password.encode(),salt=salt,n=2**15,r=8,p=1,
|
||||
maxmem=64*1024**2,dklen=32)
|
||||
with psycopg.connect(api["DATABASE_URL"],connect_timeout=3) as connection:
|
||||
connection.execute("UPDATE users SET password_hash=%s WHERE id=%s",(legacy,actor["id"]))
|
||||
valid = base64.b64encode((actor["user"]["username"]+":"+password).encode()).decode()
|
||||
client.call("POST","/api/v1/auth/sessions",201,headers={"Authorization":"Basic "+valid},schema="Session")
|
||||
with psycopg.connect(api["DATABASE_URL"],connect_timeout=3) as connection:
|
||||
stored = connection.execute("SELECT password_hash FROM users WHERE id=%s",(actor["id"],)).fetchone()[0]
|
||||
check(stored.startswith(b"$argon2id$"),"legacy hash was not rehashed")
|
||||
print("PASS: successful login upgrades legacy scrypt hash to Argon2id",flush=True)
|
||||
|
||||
s3 = boto3.client("s3", endpoint_url="https://s3:9002", region_name="us-east-1",
|
||||
verify=CA, aws_access_key_id=api["S3_ACCESS_KEY_ID"],
|
||||
aws_secret_access_key=api["S3_SECRET_ACCESS_KEY"],
|
||||
config=Config(client_cert=("/identities/api-a/cert.pem","/identities/api-a/key.pem"),
|
||||
retries={"total_max_attempts": 1}, connect_timeout=2,read_timeout=3,
|
||||
request_checksum_calculation="when_required", s3={"addressing_style":"path"}))
|
||||
denied(lambda: s3.put_object(Bucket="messenger-attachments", Key="attachments/forbidden-"+uuid4().hex, Body=b"x"))
|
||||
print("PASS: API S3 identity cannot write final-object prefix", flush=True)
|
||||
|
||||
basic = base64.b64encode((actor["user"]["username"] + ":wrong-password").encode()).decode()
|
||||
observed = set()
|
||||
rate_limited = False
|
||||
for _ in range(12):
|
||||
result = client.call("POST", "/api/v1/auth/sessions", [401,429],
|
||||
headers={"Authorization":"Basic " + basic})
|
||||
observed.add(result["headers"]["X-Instance-Id"])
|
||||
if result["status"] == 429:
|
||||
rate_limited = True
|
||||
check(result["headers"].get("Retry-After"), "missing Retry-After")
|
||||
break
|
||||
check(rate_limited and len(observed) >= 2, "shared login rate limit did not cover both replicas")
|
||||
print("PASS: shared login limit across both replicas with 429/Retry-After", flush=True)
|
||||
deadline = time.monotonic()+60
|
||||
while True:
|
||||
try:
|
||||
with urlopen("https://loki:3101/ready",context=tls_context("operator"),timeout=5) as response:
|
||||
if response.status==200:
|
||||
break
|
||||
except (OSError,URLError):
|
||||
pass
|
||||
check(time.monotonic()<deadline,"Loki did not become ready")
|
||||
time.sleep(1)
|
||||
query = urlencode({"query":'{service_name=~"messenger-api|messenger-worker"}',"limit":1000})
|
||||
logs = request("https://loki:3101/loki/api/v1/query_range?"+query,"operator")
|
||||
check(logs["data"]["result"],"no application logs through TLS path")
|
||||
serialized = json.dumps(logs)
|
||||
check(actor["token"] not in serialized and password not in serialized,"secret found in telemetry")
|
||||
metrics = request("https://prometheus:9091/api/v1/query?"+urlencode({"query":"http_requests_total"}),"operator")
|
||||
check(metrics["data"]["result"],"no application metrics through TLS path")
|
||||
print("PASS: TLS telemetry query succeeds and logs exclude test password/session token",flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user