Files
mtusi2026lab7/scripts/remote_probe.py

146 lines
7.8 KiB
Python

import json
import ssl
import sys
from urllib.request import build_opener, HTTPSHandler, ProxyHandler, Request
def opener(identity='operator', trusted=True):
context=ssl.create_default_context(cafile='/run/pki/ca.crt') if trusted else ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
if identity:
context.load_cert_chain('/run/all-pki/client/'+identity+'/client.crt','/run/all-pki/client/'+identity+'/client.key')
return build_opener(ProxyHandler({}),HTTPSHandler(context=context))
def fetch(url, identity='operator', data=None, headers=None, method=None):
raw=json.dumps(data).encode() if data is not None else None
with opener(identity).open(Request(url,data=raw,headers={'Accept':'application/json','Content-Type':'application/json',**(headers or {})},method=method),timeout=10) as r:
raw=r.read()
return json.loads(raw) if raw else {}
def secret(role, identity):
auth=fetch('https://openbao:8200/v1/auth/cert/login',identity,{'name':identity})['auth']
return fetch('https://openbao:8200/v1/secret/data/'+role,identity,
headers={'X-Vault-Token':auth['client_token']})['data']['data']
def main():
spec=json.load(sys.stdin)
if spec['op']=='fetch':
print(json.dumps([fetch(url) for url in spec['urls']]))
elif spec['op']=='tls':
import socket
results={}
reasons={}
for server in ('api1','api2'):
for identity in (None,'wrong-role','foreign','expired','lb'):
context=ssl.create_default_context(cafile='/run/pki/ca.crt')
if identity:
context.load_cert_chain('/run/all-pki/client/'+identity+'/client.crt','/run/all-pki/client/'+identity+'/client.key')
try:
with socket.create_connection((server,8443),timeout=5) as raw:
with context.wrap_socket(raw,server_hostname=server) as connection:
connection.sendall(b'GET /health/live HTTP/1.1\r\nHost: api\r\nConnection: close\r\n\r\n')
data=connection.recv(4096)
success=b'200 OK' in data
except (TimeoutError,ConnectionRefusedError):
raise RuntimeError('TLS test endpoint unavailable') from None
except (ssl.SSLError,ConnectionResetError) as error:
reasons[server+':'+str(identity)]=type(error).__name__
success=False
results[server+':'+str(identity)]=success
try:
with socket.create_connection((server,8080),timeout=2):
results[server+':plaintext']=True
except OSError:
results[server+':plaintext']=False
results['reject_reasons']=reasons
print(json.dumps(results))
elif spec['op']=='audit':
import socket
results={}
hidden={'api1':[8080],'api2':[8080],'s3':[7333,8080,8888,9333,19001],
'broker':[4369,5672,15672,15692,25672],'otel-collector':[4319,8890,8888,13133],
'loki':[3101,9095],'tempo':[3201,4319,9095],'prometheus':[9091],'openbao':[8201]}
for host,ports in hidden.items():
for port in ports:
try:
with socket.create_connection((host,port),timeout=1):results[host+':'+str(port)]=False
except (ConnectionRefusedError,TimeoutError):results[host+':'+str(port)]=True
print(json.dumps(results))
elif spec['op']=='rights':
import boto3,pika
from botocore.config import Config
from botocore.exceptions import ClientError
from pika.exceptions import ChannelClosedByBroker
results={}
for role,identity in [('api','api1'),('worker','worker')]:
v=secret(role,identity)
c=boto3.client('s3',endpoint_url='https://s3:9000',verify='/run/pki/ca.crt',
aws_access_key_id=v['s3_access_key_id'],aws_secret_access_key=v['s3_secret_access_key'],
config=Config(signature_version='s3v4',proxies={},retries={'total_max_attempts':1}))
operation=(lambda:c.get_object(Bucket='messenger-attachments',Key='staging/forbidden')) if role=='api' else (lambda:c.get_object(Bucket='messenger-attachments',Key='system/readiness'))
try:
operation();results[role+':s3_denied']=False
except ClientError as error:
results[role+':s3_denied']=error.response['ResponseMetadata']['HTTPStatusCode']==403
try:
c.create_bucket(Bucket='forbidden-security-probe');results[role+':bucket_admin_denied']=False
except ClientError as error:
results[role+':bucket_admin_denied']=error.response['ResponseMetadata']['HTTPStatusCode']==403
params=pika.URLParameters(v['broker_url']);params.ssl_options=pika.SSLOptions(ssl.create_default_context(cafile='/run/pki/ca.crt'),'broker')
conn=pika.BlockingConnection(params)
try:
ch=conn.channel();ch.queue_declare(queue='attachment.process.v1',passive=True)
results[role+':amqps']=True
try:
ch.basic_get(queue='attachment.process.v1') if role=='api' else ch.queue_declare(queue='forbidden')
results[role+':broker_denied']=False
except ChannelClosedByBroker as error:
results[role+':broker_denied']=error.reply_code==403
finally:conn.close()
from urllib.error import HTTPError
for label,url,identity in [('grafana_ingest','https://loki:3100/otlp/v1/logs','grafana'),('collector_query','https://loki:3100/loki/api/v1/query_range','collector'),('anonymous_otlp','https://otel-collector:4318/v1/logs',None)]:
try:
fetch(url,identity,{} if label!='collector_query' else None);results[label]=False
except HTTPError as error:
results[label]=error.code in (401,403);error.close()
print(json.dumps(results))
elif spec['op']=='argon2':
import time,statistics
from argon2 import PasswordHasher
h=PasswordHasher(memory_cost=19456,time_cost=2,parallelism=1)
hashed=h.hash('synthetic-benchmark-password')
h.verify(hashed,'synthetic-benchmark-password')
timings={}
for name,operation in [('hash',lambda:h.hash('synthetic-benchmark-password')),('verify',lambda:h.verify(hashed,'synthetic-benchmark-password'))]:
values=[]
for _ in range(30):
started=time.perf_counter();operation();values.append((time.perf_counter()-started)*1000)
timings[name]={'p50_ms':round(statistics.median(values),3),'p95_ms':round(sorted(values)[28],3),'samples':30}
print(json.dumps({'timings':timings,'context':'Linux application image, one CPU'}))
elif spec['op']=='database':
import psycopg
results={}
for role,identity in [('api','api1'),('worker','worker'),('cleanup','cleanup')]:
values=secret(role,identity)
with psycopg.connect(values['database_url'],autocommit=True) as db:
results[role+':tls']=db.execute('SELECT ssl FROM pg_stat_ssl WHERE pid=pg_backend_pid()').fetchone()[0]
try:
db.execute('CREATE TABLE forbidden_probe(id int)')
results[role+':ddl_denied']=False
db.execute('DROP TABLE forbidden_probe')
except psycopg.errors.InsufficientPrivilege:
results[role+':ddl_denied']=True
if role!='api':
try:
db.execute('SELECT password_hash FROM users LIMIT 1')
results[role+':users_denied']=False
except psycopg.errors.InsufficientPrivilege:
results[role+':users_denied']=True
print(json.dumps(results))
if __name__=='__main__':
main()