89 lines
4.8 KiB
Python
89 lines
4.8 KiB
Python
#!/usr/bin/env python3
|
|
"""Local negative checks for TLS identity, secret scope, ACL and session storage."""
|
|
import argparse
|
|
import base64
|
|
import hashlib
|
|
import json
|
|
from pathlib import Path
|
|
import re
|
|
import subprocess
|
|
import uuid
|
|
|
|
from client import Client, check
|
|
|
|
ROOT=Path(__file__).resolve().parents[1]
|
|
PKI=ROOT/'.local/pki'
|
|
|
|
|
|
def probe(mode):
|
|
p=subprocess.run(['docker','compose','run','--rm','-T','--no-deps','tls-probe',
|
|
'--url','https://api1:8443','--mode',mode],cwd=ROOT,text=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
|
|
if p.returncode:
|
|
raise AssertionError('internal mTLS probe '+mode+' failed: '+p.stdout[-800:])
|
|
print(p.stdout.strip())
|
|
|
|
|
|
def psql(query):
|
|
return subprocess.check_output(['docker','compose','exec','-T','postgres','psql','-U','postgres','-d','messenger','-At','-c',query],cwd=ROOT,text=True).strip()
|
|
|
|
|
|
def main():
|
|
parser=argparse.ArgumentParser()
|
|
parser.add_argument('--base-url',default='https://localhost:8443')
|
|
parser.add_argument('--ca-file',default=str(PKI/'external-ca.crt'))
|
|
args=parser.parse_args()
|
|
c=Client(args.base_url,args.ca_file)
|
|
c.call('GET','/health/ready',schema='Health')
|
|
print('PASS: external HTTPS endpoint is trusted')
|
|
subprocess.run(['docker','compose','build','tls-probe'],cwd=ROOT,check=True,
|
|
stdout=subprocess.DEVNULL,stderr=subprocess.STDOUT)
|
|
for mode in ('trusted','no-cert','untrusted-ca','wrong-identity'):
|
|
probe(mode)
|
|
|
|
# The login rate table is shared in PostgreSQL, so both API replicas enforce it.
|
|
username='rate_'+uuid.uuid4().hex
|
|
auth='Basic '+base64.b64encode((username+':wrong-pass').encode()).decode()
|
|
for _ in range(5): c.call('POST','/api/v1/auth/sessions',401,headers={'Authorization':auth})
|
|
limited=c.call('POST','/api/v1/auth/sessions',429,headers={'Authorization':auth})
|
|
check(int(limited['headers'].get('Retry-After','0'))>=1,'429 response lacks Retry-After')
|
|
print('PASS: login limiter returns 429 with Retry-After across shared database')
|
|
|
|
user=c.user('hash')
|
|
stored=psql("SELECT password FROM users WHERE username='"+user['registration']['username']+"'")
|
|
check(bool(re.fullmatch(r'\$argon2id\$v=19\$m=19456,t=2,p=1\$[^$]+\$[^$]+',stored)), 'password is not Argon2id m=19456,t=2,p=1')
|
|
token_hash=hashlib.sha256(user['token'].encode()).hexdigest()
|
|
check(psql("SELECT count(*) FROM sessions WHERE token='"+token_hash+"'")=='1','session token hash is not stored')
|
|
check(psql("SELECT count(*) FROM sessions WHERE token='"+user['token']+"'")=='0','raw session token was stored')
|
|
expired=c.user('expiry')
|
|
expired_hash=hashlib.sha256(expired['token'].encode()).hexdigest()
|
|
check(psql("UPDATE sessions SET expires_at=now()-interval '1 second' WHERE token='"+expired_hash+"'")=='UPDATE 1','could not prepare expired-session probe')
|
|
c.call('GET','/api/v1/users/me',401,actor=expired)
|
|
c.call('DELETE','/api/v1/auth/sessions/current',204,actor=user)
|
|
c.call('GET','/api/v1/users/me',401,actor=user)
|
|
print('PASS: password parameters, hashed session tokens, expiry and logout')
|
|
|
|
for service in ('api1','worker'):
|
|
r=subprocess.run(['docker','compose','exec','-T',service,'python','tests/component_security.py'],cwd=ROOT,text=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
|
|
if r.returncode: raise AssertionError(service+' component security checks failed: '+r.stdout[-1200:])
|
|
print(r.stdout.strip())
|
|
|
|
# API listeners are private and contain no database/S3/broker app credentials in container env.
|
|
docs=[json.loads(line) for line in subprocess.check_output(['docker','compose','ps','--format','json'],cwd=ROOT,text=True).splitlines() if line.strip()]
|
|
for service in ('api1','api2'):
|
|
doc=next(x for x in docs if x.get('Service')==service)
|
|
check(not doc.get('Publishers'),service+' published a direct API port')
|
|
cid=doc['ID']
|
|
config=json.loads(subprocess.check_output(['docker','inspect',cid],cwd=ROOT,text=True))[0]
|
|
check(config['Config']['User']=='10001:10001',service+' is not non-root')
|
|
host=config['HostConfig']
|
|
check(not host.get('Privileged') and host.get('ReadonlyRootfs'),service+' container hardening is missing')
|
|
check('ALL' in (host.get('CapDrop') or []),service+' did not drop capabilities')
|
|
env=config['Config'].get('Env',[])
|
|
check(not any(item.startswith(prefix+'=') for item in env for prefix in ('DATABASE_URL','S3_ACCESS_KEY','S3_SECRET_KEY','BROKER_URL','BAO_TOKEN')),
|
|
service+' contains a runtime credential in its environment')
|
|
check(not any('/var/run/docker.sock' in (item.get('Source','')+' '+item.get('Destination','')) for item in (config.get('Mounts') or [])),service+' has Docker socket access')
|
|
print('PASS: API ports are private; non-root/read-only/cap-drop; no runtime credentials or Docker socket')
|
|
|
|
if __name__=='__main__':
|
|
main()
|