741 lines
25 KiB
Python
741 lines
25 KiB
Python
"""Shared stdlib-only helpers for Lab 7 security audits, lifecycle tests, and Track 1.
|
|
|
|
Python 3.9+, standard library only. Never prints or persists raw secrets,
|
|
tokens, private keys, unseal shares, or password hashes.
|
|
"""
|
|
import argparse
|
|
import base64
|
|
import hashlib
|
|
import http.client
|
|
import json
|
|
import os
|
|
import re
|
|
import socket
|
|
import ssl
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
import urllib.parse
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[2]
|
|
if str(ROOT / 'tests') not in sys.path:
|
|
sys.path.insert(0, str(ROOT / 'tests'))
|
|
|
|
from client import Client, Failure, check # noqa: E402
|
|
|
|
PROJECT = 'mtusi-lab7'
|
|
ENV_FILE = '.env'
|
|
COMPOSE = ['docker', 'compose', '--env-file', ENV_FILE]
|
|
|
|
_PEM_KEY_RE = re.compile(
|
|
r'-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z0-9 ]*PRIVATE KEY-----',
|
|
re.MULTILINE,
|
|
)
|
|
_BAO_TOKEN_RE = re.compile(r'\b(?:hvs|hvb|hvr)\.[A-Za-z0-9._-]{8,}\b|\bs\.[A-Za-z0-9]{16,}\b')
|
|
_BEARER_RE = re.compile(r'(?i)\bBearer\s+[A-Za-z0-9._~+/=-]{8,}')
|
|
_BASIC_RE = re.compile(r'(?i)\bBasic\s+[A-Za-z0-9+/=]{8,}')
|
|
_ARGON2_RE = re.compile(r'(\$argon2(?:id|i|d)\$v=\d+\$m=\d+,t=\d+,p=\d+)\$[^$\s"\']+\$[^$\s"\']+')
|
|
_SCRYPT_RE = re.compile(r'(\$scrypt\$[^$\s"\']+)\$[^$\s"\']+\$[^$\s"\']+')
|
|
_URL_CRED_RE = re.compile(r'([a-zA-Z][a-zA-Z0-9+.-]*://[^/\s:@]+:)([^/\s@]+)(@)')
|
|
|
|
_SENSITIVE_KEY_RE = re.compile(
|
|
r'(?:^|_)(?:password|passwd|secret|token|private_key|unseal|access_key_id|'
|
|
r'secret_access_key|authorization|cookie|passphrase|key_pem|client_key|ca_key)$',
|
|
re.IGNORECASE,
|
|
)
|
|
_SAFE_META_KEYS = {
|
|
'password_rehashed',
|
|
'password_hash_params',
|
|
'password_hash_prefix',
|
|
'password_hash_valid',
|
|
'old_password_rejected',
|
|
'token_revoked',
|
|
'token_expired',
|
|
'token_ttl_seconds',
|
|
'token_renewable',
|
|
'token_reauth_ok',
|
|
'raw_token_in_redis',
|
|
'root_token_revoked',
|
|
'secret_version',
|
|
'secret_version_before',
|
|
'secret_version_after',
|
|
'secret_rotated',
|
|
'secret_leaks',
|
|
'secret_env_violations',
|
|
'metrics_token_blocked',
|
|
'authorization_header_redacted',
|
|
}
|
|
|
|
|
|
def utc_now():
|
|
return time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())
|
|
|
|
|
|
def default_operator_dir():
|
|
env = os.environ.get('LAB7_OPERATOR_DIR')
|
|
if env:
|
|
return Path(env)
|
|
state_home = os.environ.get('XDG_STATE_HOME') or os.path.join(
|
|
os.path.expanduser('~'), '.local', 'state'
|
|
)
|
|
return Path(state_home) / 'mtusi-lab7-operator'
|
|
|
|
|
|
def default_ca_file():
|
|
return Path(os.environ.get('CA_FILE') or (ROOT / 'secrets/pki/ca.crt'))
|
|
|
|
|
|
def first_existing(candidates):
|
|
for path in candidates:
|
|
p = Path(path)
|
|
if p.exists():
|
|
return p
|
|
return Path(candidates[0])
|
|
|
|
|
|
def operator_cert_pair(operator_dir):
|
|
op = Path(operator_dir)
|
|
crt = first_existing([
|
|
op / 'operator/operator.crt',
|
|
op / 'operator-cert/operator.crt',
|
|
])
|
|
key = first_existing([
|
|
op / 'operator/operator.key',
|
|
op / 'operator-cert/operator.key',
|
|
])
|
|
return crt, key
|
|
|
|
|
|
def rogue_cert_pair(operator_dir):
|
|
op = Path(operator_dir)
|
|
return op / 'pki/rogue-client.crt', op / 'pki/rogue-client.key'
|
|
|
|
|
|
def foreign_ca_and_client(operator_dir):
|
|
op = Path(operator_dir)
|
|
return (
|
|
op / 'pki/foreign-ca.crt',
|
|
op / 'pki/foreign-client.crt',
|
|
op / 'pki/foreign-client.key',
|
|
)
|
|
|
|
|
|
def haproxy_client_pair():
|
|
base = ROOT / 'secrets/pki/haproxy'
|
|
crt = base / 'client.crt'
|
|
key = base / 'client.key'
|
|
if crt.exists() and key.exists():
|
|
return crt, key
|
|
pem = first_existing([base / 'client.pem', base / 'client-bundle.pem'])
|
|
return pem, None
|
|
|
|
|
|
def service_client_pair(service):
|
|
base = ROOT / 'secrets/pki' / service
|
|
return base / 'client.crt', base / 'client.key'
|
|
|
|
|
|
def read_secret_file(names):
|
|
"""Read a trimmed secret from ./secrets/infra/<name> or ./secrets/<name>."""
|
|
if isinstance(names, (str, Path)):
|
|
names = [names]
|
|
candidates = []
|
|
for name in names:
|
|
candidates.append(ROOT / 'secrets/infra' / name)
|
|
candidates.append(ROOT / 'secrets' / name)
|
|
for path in candidates:
|
|
if path.is_file():
|
|
return path.read_text(encoding='utf-8').strip()
|
|
return None
|
|
|
|
|
|
def add_common_args(parser, default_output='evidence/lab7'):
|
|
parser.add_argument(
|
|
'--base-url',
|
|
default=os.environ.get('BASE_URL', 'https://localhost:8443'),
|
|
)
|
|
parser.add_argument('--ca-file', default=str(default_ca_file()))
|
|
parser.add_argument('--operator-dir', default=str(default_operator_dir()))
|
|
parser.add_argument(
|
|
'--openbao-url',
|
|
default=os.environ.get('BAO_ADDR', 'https://localhost:8200'),
|
|
)
|
|
parser.add_argument(
|
|
'--prometheus-url',
|
|
default=os.environ.get('PROMETHEUS_URL', 'https://localhost:9090'),
|
|
)
|
|
parser.add_argument(
|
|
'--grafana-url',
|
|
default=os.environ.get('GRAFANA_URL', 'https://localhost:3000'),
|
|
)
|
|
parser.add_argument(
|
|
'--s3-url',
|
|
default=os.environ.get('S3_PUBLIC_ENDPOINT', 'https://localhost:9000'),
|
|
)
|
|
parser.add_argument('--output-dir', default=default_output)
|
|
return parser
|
|
|
|
|
|
# ----------------------------------------------------------- secret redaction
|
|
|
|
def redact_text(text, extra_secrets=None):
|
|
if not isinstance(text, str):
|
|
return text
|
|
out = _PEM_KEY_RE.sub('[REDACTED_PRIVATE_KEY]', text)
|
|
out = _BAO_TOKEN_RE.sub('[REDACTED_BAO_TOKEN]', out)
|
|
out = _BEARER_RE.sub('Bearer [REDACTED]', out)
|
|
out = _BASIC_RE.sub('Basic [REDACTED]', out)
|
|
out = _ARGON2_RE.sub(r'\1$[REDACTED_SALT_AND_HASH]', out)
|
|
out = _SCRYPT_RE.sub(r'\1$[REDACTED_SALT_AND_HASH]', out)
|
|
out = _URL_CRED_RE.sub(r'\1[REDACTED]\3', out)
|
|
if extra_secrets:
|
|
for secret in sorted(set(s for s in extra_secrets if isinstance(s, str) and len(s) >= 6), key=len, reverse=True):
|
|
if secret in out:
|
|
out = out.replace(secret, '[REDACTED]')
|
|
return out
|
|
|
|
|
|
def sanitize_data(obj, extra_secrets=None):
|
|
if isinstance(obj, dict):
|
|
cleaned = {}
|
|
for k, v in obj.items():
|
|
key_str = str(k)
|
|
if (
|
|
key_str not in _SAFE_META_KEYS
|
|
and _SENSITIVE_KEY_RE.search(key_str)
|
|
and isinstance(v, str)
|
|
and v
|
|
):
|
|
cleaned[key_str] = '[REDACTED]'
|
|
else:
|
|
cleaned[key_str] = sanitize_data(v, extra_secrets)
|
|
return cleaned
|
|
if isinstance(obj, list):
|
|
return [sanitize_data(item, extra_secrets) for item in obj]
|
|
if isinstance(obj, tuple):
|
|
return [sanitize_data(item, extra_secrets) for item in obj]
|
|
if isinstance(obj, str):
|
|
return redact_text(obj, extra_secrets)
|
|
return obj
|
|
|
|
|
|
def write_evidence(output_dir, stem, report, extra_secrets=None):
|
|
out_path = Path(output_dir)
|
|
if not out_path.is_absolute():
|
|
out_path = ROOT / out_path
|
|
out_path.mkdir(parents=True, exist_ok=True)
|
|
safe = sanitize_data(report, extra_secrets)
|
|
json_path = out_path / (stem + '.json')
|
|
txt_path = out_path / (stem + '.txt')
|
|
json_path.write_text(
|
|
json.dumps(safe, indent=2, ensure_ascii=False, sort_keys=True) + '\n',
|
|
encoding='utf-8',
|
|
)
|
|
lines = [
|
|
f"suite={safe.get('suite', stem)} passed={safe.get('passed')} "
|
|
f"checks={safe.get('passed_count', 0)}/{safe.get('total', 0)} "
|
|
f"captured_at={safe.get('captured_at', utc_now())}",
|
|
'',
|
|
]
|
|
for item in safe.get('checks', []):
|
|
mark = 'PASS' if item.get('passed') else 'FAIL'
|
|
lines.append(
|
|
f"[{mark}] {item.get('id')} ({item.get('category', 'general')}): "
|
|
f"{item.get('description', '')} -> {item.get('actual', '')}"
|
|
)
|
|
if safe.get('summary'):
|
|
lines.append('')
|
|
lines.append('summary=' + json.dumps(safe['summary'], ensure_ascii=False, sort_keys=True))
|
|
txt_path.write_text('\n'.join(lines) + '\n', encoding='utf-8')
|
|
return json_path, txt_path
|
|
|
|
|
|
class ResultCollector:
|
|
"""Collects structured pass/fail security assertions for JSON + TXT evidence."""
|
|
|
|
def __init__(self, suite):
|
|
self.suite = suite
|
|
self.started_at = utc_now()
|
|
self.checks = []
|
|
self.summary = {}
|
|
self.extra_secrets = set()
|
|
|
|
def register_secret(self, value):
|
|
if isinstance(value, str) and len(value) >= 6:
|
|
self.extra_secrets.add(value)
|
|
|
|
def add(self, check_id, category, description, passed, expected, actual, evidence=None):
|
|
entry = {
|
|
'id': check_id,
|
|
'category': category,
|
|
'description': description,
|
|
'passed': bool(passed),
|
|
'expected': expected,
|
|
'actual': actual,
|
|
}
|
|
if evidence is not None:
|
|
entry['evidence'] = evidence
|
|
self.checks.append(entry)
|
|
mark = 'PASS' if passed else 'FAIL'
|
|
print(f"[{mark}] {check_id}: {description} ({redact_text(str(actual), self.extra_secrets)})", flush=True)
|
|
return bool(passed)
|
|
|
|
def report(self):
|
|
passed_count = sum(1 for c in self.checks if c['passed'])
|
|
failed = [c['id'] for c in self.checks if not c['passed']]
|
|
return {
|
|
'suite': self.suite,
|
|
'started_at': self.started_at,
|
|
'captured_at': utc_now(),
|
|
'passed': len(failed) == 0 and len(self.checks) > 0,
|
|
'total': len(self.checks),
|
|
'passed_count': passed_count,
|
|
'failed_count': len(failed),
|
|
'failed_ids': failed,
|
|
'summary': self.summary,
|
|
'checks': self.checks,
|
|
}
|
|
|
|
def save(self, output_dir, stem):
|
|
rep = self.report()
|
|
return write_evidence(output_dir, stem, rep, self.extra_secrets), rep
|
|
|
|
|
|
# ------------------------------------------------------ docker & host scripts
|
|
|
|
def compose(*args, stdin=None, check_result=True, timeout=180, env_extra=None):
|
|
env = os.environ.copy()
|
|
if env_extra:
|
|
env.update(env_extra)
|
|
result = subprocess.run(
|
|
COMPOSE + list(args),
|
|
cwd=ROOT,
|
|
input=stdin,
|
|
text=True,
|
|
capture_output=True,
|
|
timeout=timeout,
|
|
env=env,
|
|
)
|
|
if check_result and result.returncode != 0:
|
|
detail = redact_text((result.stderr or result.stdout).strip())
|
|
last = detail.splitlines()[-1] if detail else 'unknown error'
|
|
raise Failure('compose ' + ' '.join(str(a) for a in args) + ' failed: ' + last)
|
|
return result
|
|
|
|
|
|
def docker(*args, stdin=None, check_result=True, timeout=180):
|
|
result = subprocess.run(
|
|
['docker'] + [str(a) for a in args],
|
|
cwd=ROOT,
|
|
input=stdin,
|
|
text=True,
|
|
capture_output=True,
|
|
timeout=timeout,
|
|
)
|
|
if check_result and result.returncode != 0:
|
|
detail = redact_text((result.stderr or result.stdout).strip())
|
|
last = detail.splitlines()[-1] if detail else 'unknown error'
|
|
raise Failure('docker ' + ' '.join(str(a) for a in args) + ' failed: ' + last)
|
|
return result
|
|
|
|
|
|
def run_host_script(script_rel, *args, operator_dir=None, check_result=True, timeout=180, env_extra=None):
|
|
script = ROOT / script_rel
|
|
if not script.is_file():
|
|
raise Failure(f'required operator script missing: {script_rel}')
|
|
env = os.environ.copy()
|
|
if operator_dir:
|
|
env['LAB7_OPERATOR_DIR'] = str(operator_dir)
|
|
if env_extra:
|
|
env.update(env_extra)
|
|
result = subprocess.run(
|
|
[str(script)] + [str(a) for a in args],
|
|
cwd=ROOT,
|
|
text=True,
|
|
capture_output=True,
|
|
timeout=timeout,
|
|
env=env,
|
|
)
|
|
if check_result and result.returncode != 0:
|
|
detail = redact_text((result.stderr or result.stdout).strip())
|
|
last = detail.splitlines()[-1] if detail else f'exit {result.returncode}'
|
|
raise Failure(f'{script_rel} failed: {last}')
|
|
return result
|
|
|
|
|
|
def container_ids(service, all_states=False):
|
|
args = ['ps', '-q']
|
|
if all_states:
|
|
args.append('-a')
|
|
args.append(service)
|
|
out = compose(*args, check_result=False).stdout.split()
|
|
return [line.strip() for line in out if line.strip()]
|
|
|
|
|
|
def container_inspect(cid):
|
|
data = json.loads(docker('inspect', cid).stdout)
|
|
if not data:
|
|
raise Failure('docker inspect returned empty for ' + cid)
|
|
return data[0]
|
|
|
|
|
|
def all_project_containers(all_states=False):
|
|
args = ['ps', '-q']
|
|
if all_states:
|
|
args.append('-a')
|
|
cids = [c.strip() for c in compose(*args, check_result=False).stdout.split() if c.strip()]
|
|
if not cids:
|
|
return []
|
|
return json.loads(docker('inspect', *cids).stdout)
|
|
|
|
|
|
def app_image_id():
|
|
for svc in ('api', 'worker'):
|
|
cids = container_ids(svc, all_states=True)
|
|
if cids:
|
|
return container_inspect(cids[0])['Image']
|
|
out = compose('images', '-q', 'api', check_result=False).stdout.strip().splitlines()
|
|
if out:
|
|
return out[0].strip()
|
|
raise Failure('cannot determine application Docker image ID')
|
|
|
|
|
|
def compose_network(suffix):
|
|
"""Resolve full Docker network name (e.g. mtusi-lab7_lb_api) for a compose network."""
|
|
out = docker('network', 'ls', '--format', '{{.Name}}').stdout.splitlines()
|
|
exact = f'{PROJECT}_{suffix}'
|
|
if exact in out:
|
|
return exact
|
|
for name in out:
|
|
if name.endswith('_' + suffix) or name == suffix:
|
|
return name
|
|
raise Failure(f'docker network ending with _{suffix} not found')
|
|
|
|
|
|
def run_node_probe(js_code, payload, network=None, exec_service=None, timeout=40, image=None):
|
|
"""Run an isolated Node.js probe passing JSON payload over stdin (zero secrets in argv/env)."""
|
|
wrapper = (
|
|
"const fs=require('fs');"
|
|
"const payload=JSON.parse(fs.readFileSync(0,'utf8'));"
|
|
"(async()=>{" + js_code + "})()"
|
|
".then(res=>{process.stdout.write(JSON.stringify({ok:true,result:res})+'\\n');})"
|
|
".catch(err=>{process.stdout.write(JSON.stringify({ok:false,error:String(err&&err.message||err),code:err&&err.code||null,name:err&&err.name||null})+'\\n');});"
|
|
)
|
|
stdin_json = json.dumps(payload)
|
|
if exec_service:
|
|
res = compose(
|
|
'exec', '-T', exec_service, 'node', '-e', wrapper,
|
|
stdin=stdin_json, check_result=False, timeout=timeout,
|
|
)
|
|
else:
|
|
img = image or app_image_id()
|
|
net = compose_network(network) if network else compose_network('app_data')
|
|
res = docker(
|
|
'run', '--rm', '-i',
|
|
'--network', net,
|
|
'--read-only',
|
|
'--cap-drop=ALL',
|
|
'--security-opt', 'no-new-privileges:true',
|
|
'--tmpfs', '/tmp:size=16m,noexec,nosuid,nodev',
|
|
'--user', '1000:1000',
|
|
img, 'node', '-e', wrapper,
|
|
stdin=stdin_json, check_result=False, timeout=timeout,
|
|
)
|
|
lines = [line.strip() for line in (res.stdout or '').splitlines() if line.strip()]
|
|
for line in reversed(lines):
|
|
if line.startswith('{') and line.endswith('}'):
|
|
try:
|
|
return json.loads(line)
|
|
except ValueError:
|
|
pass
|
|
err = redact_text((res.stderr or res.stdout or '').strip())
|
|
return {'ok': False, 'error': err[-400:] if err else f'probe exited {res.returncode}', 'code': res.returncode}
|
|
|
|
|
|
def psql_admin(sql, timeout=30):
|
|
"""Execute SQL as local postgres superuser over Unix socket inside postgres container."""
|
|
script = 'psql -h /var/run/postgresql -U postgres -d messenger -v ON_ERROR_STOP=1 -At -F , -c "$SQL"'
|
|
res = subprocess.run(
|
|
COMPOSE + ['exec', '-T', '-e', 'SQL=' + sql, 'postgres', 'sh', '-c', script],
|
|
cwd=ROOT,
|
|
text=True,
|
|
capture_output=True,
|
|
timeout=timeout,
|
|
)
|
|
if res.returncode != 0:
|
|
err = redact_text((res.stderr or res.stdout).strip())
|
|
raise Failure('psql_admin failed: ' + (err.splitlines()[-1] if err else 'unknown error'))
|
|
return res.stdout.strip()
|
|
|
|
|
|
def redis_admin_cli(*args, timeout=15):
|
|
"""Run redis-cli inside redis container as redis_admin over mTLS (password via stdin)."""
|
|
pw = read_secret_file('redis_admin_password')
|
|
if not pw:
|
|
raise Failure('redis_admin_password not found under secrets/infra/')
|
|
# Build safe shell command passing redis-cli args via "$@"
|
|
cmd = [
|
|
'exec', '-T', 'redis', 'sh', '-c',
|
|
'IFS= read -r pw; export REDISCLI_AUTH="$pw"; '
|
|
'exec redis-cli --no-auth-warning --tls '
|
|
'--cacert /run/certs/ca.crt --cert /run/certs/health.crt --key /run/certs/health.key '
|
|
'--user redis_admin -h localhost -p 6379 "$@"',
|
|
'--',
|
|
] + [str(a) for a in args]
|
|
res = compose(*cmd, stdin=pw + '\n', check_result=False, timeout=timeout)
|
|
if res.returncode != 0:
|
|
err = redact_text((res.stderr or res.stdout).strip())
|
|
raise Failure('redis_admin_cli failed: ' + (err.splitlines()[-1] if err else f'exit {res.returncode}'))
|
|
return res.stdout.strip()
|
|
|
|
|
|
def wait_for_ready(base_url, ca_file, timeout=60):
|
|
client = Client(base_url, str(ca_file))
|
|
deadline = time.monotonic() + timeout
|
|
while time.monotonic() < deadline:
|
|
try:
|
|
r = client.call('GET', '/health/ready', expected=200, schema='Health')
|
|
if r['status'] == 200:
|
|
return True
|
|
except Failure:
|
|
pass
|
|
time.sleep(0.5)
|
|
raise Failure(f'API did not become ready at {base_url} within {timeout}s')
|
|
|
|
|
|
# ----------------------------------------------------------- TLS / HTTPS / X.509
|
|
|
|
def _asn1_read_tl(buf, pos):
|
|
if pos >= len(buf):
|
|
raise ValueError('truncated ASN.1')
|
|
tag = buf[pos]
|
|
pos += 1
|
|
first = buf[pos]
|
|
pos += 1
|
|
if first < 0x80:
|
|
length = first
|
|
else:
|
|
nbytes = first & 0x7F
|
|
length = int.from_bytes(buf[pos:pos + nbytes], 'big')
|
|
pos += nbytes
|
|
return tag, pos, pos + length
|
|
|
|
|
|
def parse_der_serial(der_bytes):
|
|
"""Extract canonical uppercase hex serial number from DER-encoded X.509 certificate."""
|
|
tag, inner_start, _ = _asn1_read_tl(der_bytes, 0)
|
|
if tag != 0x30:
|
|
raise ValueError('expected outer SEQUENCE')
|
|
tag, tbs_start, _ = _asn1_read_tl(der_bytes, inner_start)
|
|
if tag != 0x30:
|
|
raise ValueError('expected tbsCertificate SEQUENCE')
|
|
pos = tbs_start
|
|
if der_bytes[pos] == 0xA0:
|
|
_, _, pos = _asn1_read_tl(der_bytes, pos)
|
|
tag, val_start, val_end = _asn1_read_tl(der_bytes, pos)
|
|
if tag != 0x02:
|
|
raise ValueError('expected INTEGER serialNumber')
|
|
raw = der_bytes[val_start:val_end]
|
|
# Strip ASN.1 sign-extension leading zero byte when present
|
|
if len(raw) > 1 and raw[0] == 0x00:
|
|
raw = raw[1:]
|
|
return raw.hex().upper()
|
|
|
|
|
|
def pem_cert_info(cert_path):
|
|
"""Read serial and SHA-256 fingerprint from a PEM certificate file using stdlib ssl."""
|
|
text = Path(cert_path).read_text(encoding='utf-8')
|
|
m = re.search(r'-----BEGIN CERTIFICATE-----[\s\S]+?-----END CERTIFICATE-----', text)
|
|
if not m:
|
|
raise Failure(f'no CERTIFICATE block in {cert_path}')
|
|
der = ssl.PEM_cert_to_DER_cert(m.group(0))
|
|
return {
|
|
'serial': parse_der_serial(der),
|
|
'sha256': hashlib.sha256(der).hexdigest().upper(),
|
|
}
|
|
|
|
|
|
def make_ssl_context(ca_file=None, cert_file=None, key_file=None,
|
|
verify=True, check_hostname=True, empty_trust=False):
|
|
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
|
ctx.minimum_version = ssl.TLSVersion.TLSv1_2
|
|
# Disable TLS session tickets on client side so revocation tests always do full handshakes.
|
|
if hasattr(ssl, 'OP_NO_TICKET'):
|
|
ctx.options |= ssl.OP_NO_TICKET
|
|
if not verify:
|
|
ctx.check_hostname = False
|
|
ctx.verify_mode = ssl.CERT_NONE
|
|
else:
|
|
ctx.verify_mode = ssl.CERT_REQUIRED
|
|
ctx.check_hostname = bool(check_hostname)
|
|
if not empty_trust:
|
|
if ca_file:
|
|
ctx.load_verify_locations(cafile=str(ca_file))
|
|
else:
|
|
ctx.load_default_certs()
|
|
if cert_file:
|
|
ctx.load_cert_chain(
|
|
certfile=str(cert_file),
|
|
keyfile=str(key_file) if key_file else None,
|
|
)
|
|
return ctx
|
|
|
|
|
|
def https_request(method, url, headers=None, body=None, ssl_ctx=None, timeout=10):
|
|
"""Perform a fresh-connection HTTP/HTTPS request (no connection pooling or TLS resumption).
|
|
|
|
Returns dict: {status, headers, body, peer_cert}
|
|
"""
|
|
parsed = urllib.parse.urlsplit(url)
|
|
host = parsed.hostname
|
|
port = parsed.port or (443 if parsed.scheme == 'https' else 80)
|
|
path = parsed.path or '/'
|
|
if parsed.query:
|
|
path += '?' + parsed.query
|
|
|
|
req_headers = {'Connection': 'close'}
|
|
if headers:
|
|
req_headers.update(headers)
|
|
raw_body = body
|
|
if isinstance(body, (dict, list)):
|
|
raw_body = json.dumps(body).encode('utf-8')
|
|
req_headers.setdefault('Content-Type', 'application/json')
|
|
elif isinstance(body, str):
|
|
raw_body = body.encode('utf-8')
|
|
|
|
if parsed.scheme == 'https':
|
|
conn = http.client.HTTPSConnection(host, port, timeout=timeout, context=ssl_ctx)
|
|
else:
|
|
conn = http.client.HTTPConnection(host, port, timeout=timeout)
|
|
peer_cert = None
|
|
try:
|
|
conn.request(method, path, body=raw_body, headers=req_headers)
|
|
resp = conn.getresponse()
|
|
data = resp.read()
|
|
if parsed.scheme == 'https' and conn.sock is not None:
|
|
der = conn.sock.getpeercert(binary_form=True)
|
|
if der:
|
|
peer_cert = {
|
|
'serial': parse_der_serial(der),
|
|
'sha256': hashlib.sha256(der).hexdigest().upper(),
|
|
'version': conn.sock.version(),
|
|
}
|
|
resp_headers = {k.lower(): v for k, v in resp.getheaders()}
|
|
return {
|
|
'status': resp.status,
|
|
'headers': resp_headers,
|
|
'body': data,
|
|
'peer_cert': peer_cert,
|
|
}
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def get_tls_cert_info(host, port, ca_file=None, cert_file=None, key_file=None,
|
|
server_hostname=None, timeout=5):
|
|
ctx = make_ssl_context(ca_file=ca_file, cert_file=cert_file, key_file=key_file)
|
|
sni = server_hostname or host
|
|
with socket.create_connection((host, int(port)), timeout=timeout) as raw_sock:
|
|
with ctx.wrap_socket(raw_sock, server_hostname=sni) as tls_sock:
|
|
der = tls_sock.getpeercert(binary_form=True)
|
|
parsed = tls_sock.getpeercert() or {}
|
|
return {
|
|
'serial': parse_der_serial(der),
|
|
'sha256': hashlib.sha256(der).hexdigest().upper(),
|
|
'version': tls_sock.version(),
|
|
'subject': parsed.get('subject'),
|
|
'san': parsed.get('subjectAltName'),
|
|
}
|
|
|
|
|
|
def tcp_port_closed(host, port, timeout=2.0):
|
|
"""Return True if TCP port refuses connection."""
|
|
try:
|
|
with socket.create_connection((host, int(port)), timeout=timeout):
|
|
return False
|
|
except (ConnectionRefusedError, OSError):
|
|
return True
|
|
|
|
|
|
# ------------------------------------------------------------ OpenBao client
|
|
|
|
class OpenBaoClient:
|
|
"""Minimal stdlib HTTPS OpenBao client (fresh connection per request, zero secret logging)."""
|
|
|
|
def __init__(self, addr, ca_file, cert_file=None, key_file=None, token=None, timeout=10):
|
|
self.addr = addr.rstrip('/')
|
|
self.ca_file = ca_file
|
|
self.cert_file = cert_file
|
|
self.key_file = key_file
|
|
self.token = token
|
|
self.timeout = timeout
|
|
|
|
def _ctx(self):
|
|
return make_ssl_context(
|
|
ca_file=self.ca_file,
|
|
cert_file=self.cert_file,
|
|
key_file=self.key_file,
|
|
)
|
|
|
|
def request(self, method, path, body=None, token=None):
|
|
headers = {'Accept': 'application/json'}
|
|
use_token = token if token is not None else self.token
|
|
if use_token:
|
|
headers['X-Vault-Token'] = use_token
|
|
resp = https_request(
|
|
method,
|
|
self.addr + path,
|
|
headers=headers,
|
|
body=body,
|
|
ssl_ctx=self._ctx(),
|
|
timeout=self.timeout,
|
|
)
|
|
parsed = None
|
|
if resp['body']:
|
|
try:
|
|
parsed = json.loads(resp['body'].decode('utf-8', errors='replace'))
|
|
except ValueError:
|
|
parsed = None
|
|
return resp['status'], parsed
|
|
|
|
def health(self):
|
|
return self.request('GET', '/v1/sys/health')
|
|
|
|
def cert_login(self, role_name):
|
|
status, data = self.request('POST', '/v1/auth/cert/login', body={'name': role_name}, token='')
|
|
if status == 200 and data and data.get('auth', {}).get('client_token'):
|
|
self.token = data['auth']['client_token']
|
|
return status, data
|
|
|
|
def kv_read(self, logical_path):
|
|
path = logical_path.lstrip('/')
|
|
if not path.startswith('v1/'):
|
|
path = '/v1/' + path
|
|
else:
|
|
path = '/' + path
|
|
return self.request('GET', path)
|
|
|
|
def kv_metadata(self, sub_path):
|
|
return self.request('GET', '/v1/secret/metadata/' + sub_path.lstrip('/'))
|
|
|
|
def lookup_self(self):
|
|
return self.request('GET', '/v1/auth/token/lookup-self')
|
|
|
|
def list_accessors(self):
|
|
return self.request('LIST', '/v1/auth/token/accessors')
|
|
|
|
def lookup_accessor(self, accessor):
|
|
return self.request('POST', '/v1/auth/token/lookup-accessor', body={'accessor': accessor})
|
|
|
|
def revoke_accessor(self, accessor):
|
|
return self.request('POST', '/v1/auth/token/revoke-accessor', body={'accessor': accessor})
|
|
|
|
def seal(self):
|
|
return self.request('PUT', '/v1/sys/seal')
|
|
|
|
|
|
def basic_auth_header(username, password):
|
|
raw = base64.b64encode(f'{username}:{password}'.encode('utf-8')).decode('ascii')
|
|
return {'Authorization': 'Basic ' + raw}
|