ЛР 7 — БВТ2303 — Брезгунова — на 5
This commit is contained in:
@@ -0,0 +1,274 @@
|
||||
"""Private integration audit. Uses operator mounts only; writes sanitized evidence."""
|
||||
import base64
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import ssl
|
||||
import statistics
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
import uuid
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
from botocore.exceptions import ClientError
|
||||
import psycopg
|
||||
import redis
|
||||
from argon2 import PasswordHasher
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0,str(ROOT/'tests'))
|
||||
sys.path.insert(0,str(ROOT/'scripts'))
|
||||
from client import Client,check
|
||||
from bootstrap import bao,root_token,value
|
||||
CA = str(ROOT/'pki/ca.crt')
|
||||
BASE = 'https://lb:8443'
|
||||
|
||||
|
||||
def context(role=None):
|
||||
ctx = ssl.create_default_context(cafile=CA)
|
||||
if role:
|
||||
ctx.load_cert_chain(str(ROOT/'secrets/tls'/role/'cert.crt'),str(ROOT/'secrets/tls'/role/'key.key'))
|
||||
return ctx
|
||||
|
||||
|
||||
def request(role,path,body=None,token=None,method=None):
|
||||
headers = {'Content-Type':'application/json'}
|
||||
if token:headers['X-Vault-Token']=token
|
||||
req = urllib.request.Request('https://openbao:8200/v1/'+path,
|
||||
data=json.dumps(body).encode() if body is not None else None,headers=headers,method=method)
|
||||
with urllib.request.urlopen(req,context=context(role),timeout=5) as response:
|
||||
return json.load(response) if response.status!=204 else {}
|
||||
|
||||
|
||||
def scoped(role):
|
||||
auth = request(role,'auth/cert/login',{'name':role})['auth']
|
||||
return auth,request(role,'secret/data/'+role,token=auth['client_token'])['data']['data']
|
||||
|
||||
|
||||
def database(dsn):
|
||||
return psycopg.connect(dsn.replace('/run/pki/ca.crt',CA))
|
||||
|
||||
|
||||
def broker(role,values):
|
||||
return redis.Redis.from_url(values['BROKER_URL'],ssl_ca_certs=CA,
|
||||
ssl_certfile=str(ROOT/'secrets/tls'/role/'cert.crt'),ssl_keyfile=str(ROOT/'secrets/tls'/role/'key.key'),
|
||||
ssl_cert_reqs='required',ssl_check_hostname=True,socket_timeout=3)
|
||||
|
||||
|
||||
def storage(values):
|
||||
return boto3.client('s3',endpoint_url='https://s3:9000',verify=CA,
|
||||
aws_access_key_id=values['S3_ACCESS_KEY_ID'],aws_secret_access_key=values['S3_SECRET_ACCESS_KEY'],
|
||||
config=Config(signature_version='s3v4',s3={'addressing_style':'path'},retries={'total_max_attempts':1}))
|
||||
|
||||
|
||||
def save(name,data):
|
||||
(ROOT/'evidence'/name).write_text(json.dumps(data,ensure_ascii=False,indent=2))
|
||||
|
||||
|
||||
def tls_probe(host,port,role,body):
|
||||
try:
|
||||
with socket.create_connection((host,port),timeout=10) as raw:
|
||||
with context(role).wrap_socket(raw,server_hostname=host) as stream:
|
||||
stream.sendall(body)
|
||||
response = stream.recv(4096)
|
||||
return bool(response), 'application_response' if response else 'identity_eof'
|
||||
except ssl.SSLError:
|
||||
return False,'tls_certificate_rejected'
|
||||
except ConnectionResetError:
|
||||
return False,'identity_reset'
|
||||
|
||||
|
||||
def matrix():
|
||||
rows=[]
|
||||
targets=[('api1',8443,'lb',b'GET /health/live HTTP/1.1\r\nHost: api1\r\nConnection: close\r\n\r\n'),
|
||||
('api2',8443,'lb',b'GET /health/live HTTP/1.1\r\nHost: api2\r\nConnection: close\r\n\r\n'),
|
||||
('broker',6380,'worker',b'*1\r\n$4\r\nPING\r\n'),
|
||||
('otel-collector',4319,'api1',b'POST /v1/traces HTTP/1.1\r\nHost: otel-collector\r\nContent-Type: application/json\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{}'),
|
||||
('otel-collector',8890,'prometheus',b'GET /metrics HTTP/1.1\r\nHost: otel-collector\r\nConnection: close\r\n\r\n'),
|
||||
('prometheus',9443,'grafana',b'GET /-/ready HTTP/1.1\r\nHost: prometheus\r\nConnection: close\r\n\r\n'),
|
||||
('loki',3443,'grafana',b'GET /ready HTTP/1.1\r\nHost: loki\r\nConnection: close\r\n\r\n'),
|
||||
('tempo',3443,'grafana',b'GET /ready HTTP/1.1\r\nHost: tempo\r\nConnection: close\r\n\r\n'),
|
||||
('tempo',4438,'otel-collector',b'POST /v1/traces HTTP/1.1\r\nHost: tempo\r\nContent-Type: application/json\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{}')]
|
||||
for host,port,allowed,body in targets:
|
||||
print('Checking verified TLS',host,port,flush=True)
|
||||
positive,stage=tls_probe(host,port,allowed,body)
|
||||
check(positive,'positive TLS probe failed '+host+':'+str(port))
|
||||
for role in (None,'foreign','intruder','expired'):
|
||||
accepted,stage=tls_probe(host,port,role,body)
|
||||
check(not accepted,'unauthorized TLS identity accepted')
|
||||
rows.append({'host':host,'port':port,'client':role or 'none','result':'DENIED','stage':stage})
|
||||
rows.append({'host':host,'port':port,'client':allowed,'result':'ALLOWED'})
|
||||
# Same CA with a different SAN must also fail the client's hostname verification.
|
||||
try:
|
||||
with socket.create_connection(('lb',8443),timeout=3) as raw:
|
||||
context().wrap_socket(raw,server_hostname='wrong.invalid')
|
||||
raise AssertionError('wrong hostname accepted')
|
||||
except ssl.SSLCertVerificationError:
|
||||
pass
|
||||
blocked=[]
|
||||
for host,port in [('api1',8080),('api2',8080),('broker',6379),('otel-collector',4318),('otel-collector',8889),('prometheus',9090),('loki',3100),('tempo',3200),('tempo',4318),('grafana',3000)]:
|
||||
try:
|
||||
with socket.create_connection((host,port),timeout=2):
|
||||
raise AssertionError('plaintext bypass '+host)
|
||||
except (ConnectionRefusedError,TimeoutError):
|
||||
blocked.append({'host':host,'port':port,'result':'blocked'})
|
||||
save('tls-matrix.json',{'result':'PASS','probes':rows,'plaintext_bypasses':blocked,'wrong_hostname':'DENIED'})
|
||||
print('PASS: full TLS/mTLS matrix, wrong identities and plaintext bypasses',flush=True)
|
||||
|
||||
|
||||
def permissions():
|
||||
auth,values=scoped('worker')
|
||||
check(auth['lease_duration']<=30,'unbounded Bao token')
|
||||
denied=[]
|
||||
for path,body,method in [('secret/data/api1',None,None),('sys/policies/acl/evil',{'policy':'path "*" { capabilities=["sudo"] }'},None),('secret/data/worker',{'data':{'evil':'no'}},None)]:
|
||||
try:
|
||||
request('worker',path,body,auth['client_token'],method)
|
||||
raise AssertionError('Bao policy escalation')
|
||||
except urllib.error.HTTPError as error:
|
||||
check(error.code==403,'unexpected policy error')
|
||||
denied.append(path)
|
||||
for operation in ['SELECT * FROM users LIMIT 1','SELECT * FROM sessions LIMIT 1','SELECT * FROM messages LIMIT 1','CREATE TABLE public.compromised(x int)','ALTER ROLE worker SUPERUSER']:
|
||||
try:
|
||||
with database(values['DATABASE_URL']) as conn:conn.execute(operation)
|
||||
raise AssertionError('worker DB escalation')
|
||||
except psycopg.errors.InsufficientPrivilege:
|
||||
denied.append(operation)
|
||||
with database(values['DATABASE_URL']) as conn:
|
||||
conn.execute('SELECT * FROM jobs LIMIT 1')
|
||||
check(conn.execute('SELECT ssl FROM pg_stat_ssl WHERE pid=pg_backend_pid()').fetchone()[0],'DB connection not TLS')
|
||||
conn.execute("UPDATE attachments SET error_code=error_code WHERE id='00000000-0000-0000-0000-000000000000'")
|
||||
comparison=[{'table':table,'lab6_style_owner_can_select':conn.execute('SELECT has_table_privilege(%s,%s,%s)',('messenger',table,'SELECT')).fetchone()[0],
|
||||
'worker_can_select':conn.execute('SELECT has_table_privilege(%s,%s,%s)',('worker',table,'SELECT')).fetchone()[0]} for table in ('users','sessions','messages','jobs','attachments')]
|
||||
r=broker('worker',values)
|
||||
check(r.ping(),'worker broker auth')
|
||||
for operation in [lambda:r.config_get('*'),lambda:r.acl_list(),lambda:r.set('foreign:key','x'),lambda:r.xadd('attachments:v1',{'job':'forbidden'})]:
|
||||
try:
|
||||
operation();raise AssertionError('worker Redis escalation')
|
||||
except redis.ResponseError:
|
||||
denied.append('redis_admin_or_producer_denied')
|
||||
s3=storage(values)
|
||||
key='results/security-probe/'+uuid.uuid4().hex
|
||||
s3.put_object(Bucket='messenger-attachments',Key=key,Body=b'synthetic')
|
||||
check(s3.get_object(Bucket='messenger-attachments',Key=key)['Body'].read()==b'synthetic','worker own result unavailable')
|
||||
for operation in [lambda:s3.put_object(Bucket='messenger-attachments',Key='staging/forbidden',Body=b'x'),lambda:s3.put_object(Bucket='messenger-attachments',Key='other/forbidden',Body=b'x'),lambda:s3.delete_object(Bucket='messenger-attachments',Key=key),lambda:s3.create_bucket(Bucket='forbidden-security-probe')]:
|
||||
try:
|
||||
operation();raise AssertionError('worker S3 escalation')
|
||||
except ClientError as error:
|
||||
check(error.response['Error']['Code']=='AccessDenied','unexpected S3 denial')
|
||||
denied.append('s3_prefix_delete_or_admin_denied')
|
||||
admin={'S3_ACCESS_KEY_ID':value('operator_s3_key'),'S3_SECRET_ACCESS_KEY':value('operator_s3_secret')}
|
||||
storage(admin).delete_object(Bucket='messenger-attachments',Key=key)
|
||||
save('worker-privileges.json',{'result':'PASS','bao_token_ttl_seconds':auth['lease_duration'],
|
||||
'least_privilege_comparison_in_isolated_lab7':comparison,
|
||||
'denied':denied,'allowed':['read own KV','read jobs','update attachment result','broker consumer','put/get results prefix'],
|
||||
'residual_risk':'Worker can corrupt available image results and consume/drop notification deliveries. Durable DB jobs allow relay recovery, but least privilege is not an integrity proof against a malicious authorized worker.'})
|
||||
print('PASS: scoped Bao, DB, S3 and broker allow/deny',flush=True)
|
||||
|
||||
|
||||
def authentication():
|
||||
c=Client(BASE,CA,timeout=10)
|
||||
a,b,e,chat=c.bootstrap()
|
||||
att,raw=c.attachment(a,chat);c.wait_ready(a,att)
|
||||
for suffix in ('','/content'):
|
||||
c.call('GET','/api/v1/attachments/'+att['id']+suffix,404,actor=e)
|
||||
c.call('POST','/api/v1/chats/'+chat['id']+'/messages',404,actor=e,
|
||||
body={'text':'','attachment_ids':[att['id']]},headers={'Idempotency-Key':uuid.uuid4().hex})
|
||||
response=c.call('GET','/api/v1/users/me',actor=e,headers={'X-User-Id':a['id']},schema='User')
|
||||
check(response['json']['id']==e['id'],'spoofed identity')
|
||||
# Expire only this synthetic session using the operator connection.
|
||||
import hashlib
|
||||
dsn='host=postgres dbname=messenger user=messenger password='+value('postgres_password')+' sslmode=verify-full sslrootcert='+CA
|
||||
with psycopg.connect(dsn) as conn:
|
||||
hashes=conn.execute('SELECT password_hash FROM users WHERE id=%s',(a['id'],)).fetchone()[0]
|
||||
check(hashes.startswith('$argon2id$v=19$m=19456,t=2,p=1$'),'password KDF parameters')
|
||||
token_hash=hashlib.sha256(a['token'].encode()).hexdigest()
|
||||
check(conn.execute('SELECT 1 FROM sessions WHERE token_hash=%s',(token_hash,)).fetchone(),'session hashed')
|
||||
conn.execute("UPDATE sessions SET expires_at=clock_timestamp()-interval '1 second' WHERE token_hash=%s",(token_hash,))
|
||||
c.call('GET','/api/v1/users/me',401,actor=a)
|
||||
c.call('DELETE','/api/v1/auth/sessions/current',204,actor=b)
|
||||
c.call('GET','/api/v1/users/me',401,actor=b)
|
||||
# Actual old hash with weaker parameters -> successful login must rehash.
|
||||
credential=base64.b64encode((a['registration']['username']+':'+a['registration']['password']).encode()).decode()
|
||||
with psycopg.connect(dsn) as conn:
|
||||
conn.execute('UPDATE users SET password_hash=%s WHERE id=%s',(PasswordHasher(time_cost=1,memory_cost=8192,parallelism=1).hash(a['registration']['password']),a['id']))
|
||||
c.call('POST','/api/v1/auth/sessions',201,headers={'Authorization':'Basic '+credential},schema='Session')
|
||||
with psycopg.connect(dsn) as conn:
|
||||
check('m=19456,t=2,p=1' in conn.execute('SELECT password_hash FROM users WHERE id=%s',(a['id'],)).fetchone()[0],'rehash absent')
|
||||
wrong='Basic '+base64.b64encode((a['registration']['username']+':wrong-password-long').encode()).decode()
|
||||
outcomes=[]
|
||||
for _ in range(12):
|
||||
r=c.call('POST','/api/v1/auth/sessions',[401,429],headers={'Authorization':wrong})
|
||||
outcomes.append({'status':r['status'],'instance':r['headers']['X-Instance-Id'],'retry_after':r['headers'].get('Retry-After')})
|
||||
check(any(r['status']==429 and r['retry_after'] for r in outcomes),'rate limit absent')
|
||||
check(len({r['instance'] for r in outcomes})==2,'rate limit not tested across both replicas')
|
||||
ph=PasswordHasher(time_cost=2,memory_cost=19456,parallelism=1)
|
||||
durations=[]
|
||||
for _ in range(12):
|
||||
started=time.perf_counter();ph.hash('synthetic-password-for-budget');durations.append(time.perf_counter()-started)
|
||||
save('authentication.json',{'result':'PASS','ACL_negative_checks':4,'expiry_logout_rehash':'PASS','session_storage':'sha256(random 256-bit bearer)',
|
||||
'rate_limit_outcomes':outcomes,'argon2id':{'memory_kib':19456,'time_cost':2,'parallelism':1,'measured_hash_seconds':durations,
|
||||
'median_seconds':statistics.median(durations),'max_seconds':max(durations),'shared_KDF_slots':2,
|
||||
'peak_KDF_memory_budget_mib':38,'global_login_budget_per_second':20,'per_username_attempts_per_30s':8}})
|
||||
print('PASS: ACL/expiry/logout/rehash/shared rate limit/Argon2 measurements',flush=True)
|
||||
|
||||
|
||||
def token_expiry():
|
||||
auth,_=scoped('worker')
|
||||
started=time.monotonic()
|
||||
time.sleep(auth['lease_duration']+2)
|
||||
try:
|
||||
request('worker','secret/data/worker',token=auth['client_token'])
|
||||
raise AssertionError('expired Bao token accepted')
|
||||
except urllib.error.HTTPError as error:
|
||||
check(error.code==403,'unexpected expiry failure')
|
||||
newer,_=scoped('worker')
|
||||
check(newer['client_token']!=auth['client_token'],'re-auth did not issue new token')
|
||||
save('bao-token-expiry.json',{'result':'PASS','issued_ttl_seconds':auth['lease_duration'],
|
||||
'tested_after_seconds':round(time.monotonic()-started,3),'expired_read_status':403,'fresh_cert_auth_succeeded':True})
|
||||
print('PASS: expired Bao token denied; certificate re-auth issues new short-lived token',flush=True)
|
||||
|
||||
|
||||
def propagation_bounds():
|
||||
sys.path.insert(0,str(ROOT))
|
||||
from src.telemetry import extract
|
||||
oversized=' '*1048576+'!'
|
||||
started=time.perf_counter()
|
||||
for _ in range(100):
|
||||
extract({'traceparent':oversized,'tracestate':oversized})
|
||||
elapsed=time.perf_counter()-started
|
||||
check(elapsed<1,'unbounded propagator processing')
|
||||
save('propagation-bounds.json',{'result':'PASS','malicious_header_bytes':len(oversized),
|
||||
'iterations':100,'duration_seconds':elapsed,'entry_points':['HTTP','consumer','relay']})
|
||||
|
||||
|
||||
def store_permissions():
|
||||
rows=[]
|
||||
for host,port,path in [('loki',3443,'/otlp/v1/logs'),('tempo',3443,'/flush'),('prometheus',9443,'/api/v1/admin/tsdb/delete_series')]:
|
||||
req=urllib.request.Request('https://'+host+':'+str(port)+path,data=b'{}',headers={'Content-Type':'application/json'})
|
||||
try:
|
||||
urllib.request.urlopen(req,context=context('grafana'),timeout=10)
|
||||
raise AssertionError('Grafana obtained store write/admin permissions')
|
||||
except urllib.error.HTTPError as error:
|
||||
check(error.code==403,'expected explicit gateway ACL denial')
|
||||
rows.append({'client':'grafana','path':path,'server':host,'status':403})
|
||||
with socket.create_connection(('loki',3443),timeout=10) as raw:
|
||||
with context('grafana').wrap_socket(raw,server_hostname='loki') as stream:
|
||||
stream.sendall(b'GET /ready HTTP/1.1\r\nHost: loki\r\nConnection: keep-alive\r\n\r\nPOST /otlp/v1/logs HTTP/1.1\r\nHost: loki\r\nContent-Length: 2\r\n\r\n{}')
|
||||
response=b''
|
||||
while part:=stream.recv(4096):response+=part
|
||||
check(response.count(b'HTTP/1.1')==1 and b'connection: close' in response.lower(),'pipelined write could bypass first-request authorization')
|
||||
save('store-query-permissions.json',{'result':'PASS','write_admin_denied':rows,'pipelined_second_request_blocked':True})
|
||||
print('PASS: Grafana store identities can query, cannot ingest/admin or bypass with HTTP pipelining',flush=True)
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
matrix()
|
||||
permissions()
|
||||
authentication()
|
||||
token_expiry()
|
||||
propagation_bounds()
|
||||
store_permissions()
|
||||
Reference in New Issue
Block a user