forked from mtusi2026/mtusi2026lab7
Implement lab7 security and compromised worker recovery evidence
This commit is contained in:
@@ -0,0 +1,178 @@
|
||||
import json
|
||||
import uuid
|
||||
import socket
|
||||
import ssl
|
||||
|
||||
import boto3
|
||||
import psycopg
|
||||
import redis
|
||||
from botocore.exceptions import ClientError
|
||||
|
||||
from pipeline.config import credentials
|
||||
|
||||
|
||||
def denied_sql(db, statement):
|
||||
try:
|
||||
with db.transaction():
|
||||
db.execute(statement)
|
||||
except psycopg.errors.InsufficientPrivilege:
|
||||
return True
|
||||
raise AssertionError("Database operation unexpectedly allowed")
|
||||
|
||||
|
||||
def verify_broker_transport():
|
||||
with socket.create_connection(("broker", 6379), timeout=3) as connection:
|
||||
connection.sendall(b"PING\r\n")
|
||||
try:
|
||||
response = connection.recv(64)
|
||||
except ConnectionResetError:
|
||||
response = b""
|
||||
assert response == b"" or response.startswith(b"\x15"), "Plaintext broker command accepted"
|
||||
for trust, hostname in ((False, "broker"), (True, "untrusted.invalid")):
|
||||
context = (
|
||||
ssl.create_default_context(cafile="/pki/ca.crt")
|
||||
if trust
|
||||
else ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
||||
)
|
||||
context.load_cert_chain("/identity/service.crt", "/identity/service.key")
|
||||
try:
|
||||
with socket.create_connection(("broker", 6379), timeout=3) as connection:
|
||||
context.wrap_socket(connection, server_hostname=hostname).close()
|
||||
except ssl.SSLCertVerificationError:
|
||||
continue
|
||||
raise AssertionError("Broker certificate verification bypassed")
|
||||
|
||||
|
||||
def main():
|
||||
values = credentials()
|
||||
verify_broker_transport()
|
||||
connection = dict(
|
||||
host="db",
|
||||
dbname="messenger",
|
||||
user=values["postgres_user"],
|
||||
password=values["postgres_password"],
|
||||
sslmode="verify-full",
|
||||
sslrootcert="/pki/ca.crt",
|
||||
connect_timeout=3,
|
||||
)
|
||||
for override, expected in [
|
||||
({"sslmode": "disable"}, "no encryption"),
|
||||
(
|
||||
{"host": "untrusted.invalid", "hostaddr": socket.gethostbyname("db")},
|
||||
"does not match host name",
|
||||
),
|
||||
({"sslrootcert": "/etc/ssl/certs/ca-certificates.crt"}, "certificate verify failed"),
|
||||
]:
|
||||
try:
|
||||
psycopg.connect(**(connection | override))
|
||||
except psycopg.OperationalError as error:
|
||||
assert expected in str(error), type(error).__name__
|
||||
else:
|
||||
raise AssertionError("PostgreSQL TLS boundary bypassed")
|
||||
with psycopg.connect(
|
||||
host="db",
|
||||
dbname="messenger",
|
||||
user=values["postgres_user"],
|
||||
password=values["postgres_password"],
|
||||
sslmode="verify-full",
|
||||
sslrootcert="/pki/ca.crt",
|
||||
connect_timeout=3,
|
||||
) as db:
|
||||
assert db.execute("SELECT ssl FROM pg_stat_ssl WHERE pid=pg_backend_pid()").fetchone()[0]
|
||||
db.execute("SELECT job_id FROM processing_jobs LIMIT 1")
|
||||
assert denied_sql(db, "SELECT password_hash FROM users LIMIT 1")
|
||||
assert denied_sql(db, "SELECT token_hash FROM sessions LIMIT 1")
|
||||
assert denied_sql(db, "DELETE FROM messages WHERE false")
|
||||
assert denied_sql(db, "CREATE TABLE worker_escape_probe(id int)")
|
||||
assert denied_sql(db, "ALTER ROLE worker SUPERUSER")
|
||||
assert denied_sql(db, "SELECT chat_id,owner_id FROM attachments LIMIT 1")
|
||||
assert denied_sql(db, "UPDATE attachments SET chat_id=chat_id WHERE false")
|
||||
queue = redis.Redis(
|
||||
host="broker",
|
||||
username=values["broker_user"],
|
||||
password=values["broker_password"],
|
||||
ssl=True,
|
||||
ssl_ca_certs="/pki/ca.crt",
|
||||
ssl_certfile="/identity/service.crt",
|
||||
ssl_keyfile="/identity/service.key",
|
||||
ssl_check_hostname=True,
|
||||
socket_timeout=3,
|
||||
)
|
||||
assert queue.ping()
|
||||
assert queue.hget("job-publications", "security-probe-nonexistent") is None
|
||||
for operation in [
|
||||
lambda: queue.flushall(),
|
||||
lambda: queue.get("foreign-secret"),
|
||||
lambda: queue.xadd("attachment-jobs", {"security-probe": "denied"}),
|
||||
]:
|
||||
try:
|
||||
operation()
|
||||
except redis.exceptions.NoPermissionError:
|
||||
continue
|
||||
raise AssertionError("Broker operation unexpectedly allowed")
|
||||
s3 = boto3.client(
|
||||
"s3",
|
||||
endpoint_url="https://minio:9000",
|
||||
aws_access_key_id=values["s3_access_key_id"],
|
||||
aws_secret_access_key=values["s3_secret_access_key"],
|
||||
verify="/pki/ca.crt",
|
||||
)
|
||||
key = "results/security-probe-" + uuid.uuid4().hex
|
||||
s3.put_object(Bucket="messenger-attachments", Key=key, Body=b"synthetic")
|
||||
assert s3.get_object(Bucket="messenger-attachments", Key=key)["Body"].read() == b"synthetic"
|
||||
for operation in [
|
||||
lambda: s3.put_object(
|
||||
Bucket="messenger-attachments", Key="admin/forbidden", Body=b"synthetic"
|
||||
),
|
||||
lambda: s3.delete_object(Bucket="messenger-attachments", Key=key),
|
||||
lambda: s3.create_bucket(Bucket="worker-escape-probe-forbidden"),
|
||||
lambda: s3.list_objects_v2(Bucket="messenger-attachments", Prefix="admin/"),
|
||||
]:
|
||||
try:
|
||||
operation()
|
||||
except ClientError as error:
|
||||
assert error.response["ResponseMetadata"]["HTTPStatusCode"] == 403
|
||||
continue
|
||||
raise AssertionError("S3 operation unexpectedly allowed")
|
||||
print(
|
||||
json.dumps(
|
||||
dict(
|
||||
status="PASS",
|
||||
identity=values["postgres_user"],
|
||||
database=dict(
|
||||
tls=True,
|
||||
plaintext_denied=True,
|
||||
wrong_hostname_denied=True,
|
||||
foreign_ca_denied=True,
|
||||
read_jobs=True,
|
||||
users_denied=True,
|
||||
sessions_denied=True,
|
||||
message_delete_denied=True,
|
||||
ddl_denied=True,
|
||||
superuser_denied=True,
|
||||
ownership_columns_denied=True,
|
||||
),
|
||||
broker=dict(
|
||||
mtls=True,
|
||||
plaintext_denied=True,
|
||||
wrong_hostname_denied=True,
|
||||
foreign_ca_denied=True,
|
||||
read_index=True,
|
||||
flush_denied=True,
|
||||
foreign_key_denied=True,
|
||||
producer_denied=True,
|
||||
),
|
||||
s3=dict(
|
||||
results_put_get=True,
|
||||
admin_prefix_denied=True,
|
||||
result_delete_denied=True,
|
||||
bucket_admin_denied=True,
|
||||
prefix_enumeration_denied=True,
|
||||
),
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user