forked from mtusi2026/mtusi2026lab7
Проверка rehash, login DoS и общего rate limit
This commit is contained in:
@@ -63,6 +63,33 @@ make test-session-expiry BASE_URL=https://localhost:8443 CA_FILE=/absolute/path/
|
||||
logout. Token, пароль и SQL credentials не печатаются. Это не публичный black-box
|
||||
тест, поскольку управляемое истечение часа ожидать непрактично.
|
||||
|
||||
## Login DoS budget и credential storage
|
||||
|
||||
```sh
|
||||
make test-login-dos BASE_URL=https://localhost:8443 CA_FILE=secrets/pki/public-ca/ca.crt
|
||||
make test-credential-storage BASE_URL=https://localhost:8443 CA_FILE=secrets/pki/public-ca/ca.crt
|
||||
```
|
||||
|
||||
`login_dos.py` — black-box проверка через nginx: 5 неверных попыток одного
|
||||
username и 6-я → `429` + `Retry-After`; при `--source-budget` после окна 60 с
|
||||
100 попыток с разными username и 101-я → `429`. Скрипт записывает
|
||||
`X-Instance-Id` и требует, чтобы попытки обслуживали минимум две реплики
|
||||
(`--minimum-instances`, по умолчанию 2). Он также проверяет, что 429 дешевле
|
||||
Argon2-пути, что known/unknown user дают одинаковый `401`, и что тела/headers
|
||||
не содержат credentials. `scripts/measure-login-dos.ps1 -SourceBudget` запускает
|
||||
этот тест вместе с `credential_storage.py`; `-IncludeArgon2` дополнительно
|
||||
запускает калибровку.
|
||||
|
||||
`credential_storage.py` — локальная Compose-проверка: создаёт synthetic
|
||||
пользователя и сессию, читает `password_hash`/`token_hash` из PostgreSQL,
|
||||
сверяет Argon2id PHC и SHA-256, затем ищет plaintext password/token/hash в
|
||||
логах API и nginx. Пароль и token не печатаются. Это не публичный black-box
|
||||
тест, потому что ему нужен операторский доступ к БД и логам.
|
||||
|
||||
Ограничение: source-лимит видит адрес nginx/LB, поэтому это общий cap для
|
||||
клиентов за LB, а не per-client. Username-лимит остаётся основной защитой
|
||||
аккаунта; trusted-proxy модель для клиентского адреса — следующий шаг.
|
||||
|
||||
## Что ещё остаётся доказать
|
||||
|
||||
Smoke не доказывает persistence, число реальных контейнеров, durability брокера, outbox, отсутствие утечек/уязвимостей, полноту telemetry или выполнение уровня 4/5. Конкурентные/нагрузочные/негативные проверки своего решения добавляйте отдельно. Список защиты текущей лабы находится в README.md. Проверки рассчитаны на localhost-стенд, не на production.
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Local Compose check: stored credentials are hashes and are absent from logs.
|
||||
|
||||
The check creates one synthetic user and one session, then reads only the
|
||||
password hash and token hash from PostgreSQL. The synthetic password and token
|
||||
stay in process memory; on failure the script never prints them.
|
||||
"""
|
||||
import hashlib
|
||||
import pathlib
|
||||
import subprocess
|
||||
|
||||
from client import Client, LAB, arguments, check, run
|
||||
|
||||
|
||||
def read_env(path):
|
||||
values = {}
|
||||
env_path = pathlib.Path(path)
|
||||
if not env_path.is_file():
|
||||
return values
|
||||
for raw in env_path.read_text(encoding='utf-8-sig').splitlines():
|
||||
line = raw.strip()
|
||||
if not line or line.startswith('#') or '=' not in line:
|
||||
continue
|
||||
name, value = line.split('=', 1)
|
||||
values[name.strip()] = value.strip()
|
||||
return values
|
||||
|
||||
|
||||
def configure(parser):
|
||||
parser.add_argument('--env-file', default='.env')
|
||||
|
||||
|
||||
def compose(args, *command, input_text=None):
|
||||
return subprocess.run([
|
||||
'docker', 'compose', '--env-file', args.env_file, *command,
|
||||
], cwd=pathlib.Path(__file__).resolve().parents[1], input=input_text,
|
||||
capture_output=True, text=True, timeout=60)
|
||||
|
||||
|
||||
def psql(args, database_user, database_name, sql, variables=None):
|
||||
command = [
|
||||
'exec', '-T', 'postgres',
|
||||
'psql', '--username', database_user, '--dbname', database_name,
|
||||
'--set', 'ON_ERROR_STOP=1',
|
||||
'--tuples-only', '--no-align',
|
||||
]
|
||||
for name, value in (variables or {}).items():
|
||||
command.extend(['--set', name + '=' + value])
|
||||
result = compose(args, *command, input_text=sql)
|
||||
check(result.returncode == 0, 'operator database query failed')
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Local Compose credential storage and log leak check', configure)
|
||||
check(LAB >= 2, 'credential storage requires lab2 or later')
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
client.call('GET', '/health/ready', schema='Health')
|
||||
actor = client.user('storage')
|
||||
username = actor['registration']['username']
|
||||
password = actor['registration']['password']
|
||||
token = actor['token']
|
||||
|
||||
env = read_env(args.env_file)
|
||||
database_user = env.get('DATABASE_USER', 'messenger')
|
||||
database_name = env.get('DATABASE_NAME', 'messenger')
|
||||
|
||||
password_hash = psql(args, database_user, database_name, """
|
||||
SELECT password_hash
|
||||
FROM users
|
||||
WHERE username = :'target_username';
|
||||
""", {'target_username': username})
|
||||
check(password_hash.startswith('$argon2id$v=19$m=32768,t=2,p=1$'),
|
||||
'stored password value is not the measured Argon2id PHC string')
|
||||
check(password not in password_hash, 'stored password hash contains the plaintext password')
|
||||
check(len(password_hash) > 50, 'stored password hash is unexpectedly short')
|
||||
|
||||
token_hash = psql(args, database_user, database_name, """
|
||||
SELECT encode(token_hash, 'hex')
|
||||
FROM sessions
|
||||
WHERE user_id = (SELECT id FROM users WHERE username = :'target_username')
|
||||
ORDER BY created_at DESC
|
||||
LIMIT 1;
|
||||
""", {'target_username': username})
|
||||
expected = hashlib.sha256(token.encode('ascii')).hexdigest()
|
||||
check(token_hash == expected, 'stored session value is not the SHA-256 of the issued token')
|
||||
check(len(token_hash) == 64, 'stored session hash is not 32 bytes')
|
||||
check(token_hash != token, 'session token itself was stored')
|
||||
|
||||
log_text = ''
|
||||
for service in ('api', 'nginx'):
|
||||
result = compose(args, 'logs', '--no-color', service)
|
||||
check(result.returncode == 0, 'could not read ' + service + ' logs')
|
||||
log_text += result.stdout + result.stderr
|
||||
check(len(log_text) > 0, 'no API/LB logs were available for the leak check')
|
||||
check(password not in log_text, 'API/LB logs contain the synthetic password')
|
||||
check(token not in log_text, 'API/LB logs contain the synthetic session token')
|
||||
check(password_hash not in log_text, 'API/LB logs contain the stored password hash')
|
||||
check(token_hash not in log_text, 'API/LB logs contain the stored token hash')
|
||||
|
||||
print('PASS: password and session token are stored only as hashes and are absent from API/LB logs.')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,214 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Measures the shared login rate-limit budget and checks credential non-disclosure.
|
||||
|
||||
The test is intentionally black-box: it talks only through the public HTTPS
|
||||
ingress, records which API replica served each attempt, and never prints a
|
||||
password, session token or password hash.
|
||||
"""
|
||||
import base64
|
||||
import concurrent.futures
|
||||
import json
|
||||
import math
|
||||
import socket
|
||||
import statistics
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def prefer_ipv4_for_localhost():
|
||||
"""Avoid a ~2 s IPv6 fallback on Windows when localhost resolves to ::1 first."""
|
||||
original = socket.getaddrinfo
|
||||
|
||||
def getaddrinfo(host, port, family=0, type=0, proto=0, flags=0):
|
||||
addresses = original(host, port, family, type, proto, flags)
|
||||
if host == 'localhost' and family in (0, socket.AF_UNSPEC):
|
||||
ipv4 = [address for address in addresses if address[0] == socket.AF_INET]
|
||||
return ipv4 or addresses
|
||||
return addresses
|
||||
|
||||
socket.getaddrinfo = getaddrinfo
|
||||
|
||||
|
||||
def configure(parser):
|
||||
parser.add_argument('--minimum-instances', type=int, default=2,
|
||||
help='fail unless this many distinct X-Instance-Id values are observed')
|
||||
parser.add_argument('--username-limit', type=int, default=5)
|
||||
parser.add_argument('--source-limit', type=int, default=100)
|
||||
parser.add_argument('--window-seconds', type=int, default=60)
|
||||
parser.add_argument('--source-budget', action='store_true',
|
||||
help='also exhaust the per-source budget (takes about one window plus 100 verifies)')
|
||||
parser.add_argument('--wait-window', type=int, default=61,
|
||||
help='wait this long before the source-budget phase so its counter is empty')
|
||||
|
||||
|
||||
def register(client, label):
|
||||
username = 'dos_' + label.replace('-', '_') + '_' + uuid.uuid4().hex[:12]
|
||||
password = 'T3st-' + uuid.uuid4().hex
|
||||
client.call('POST', '/api/v1/users', 201,
|
||||
body={'username': username, 'display_name': 'DoS ' + label, 'password': password},
|
||||
schema='User')
|
||||
return username, password
|
||||
|
||||
|
||||
def login(client, username, password):
|
||||
credential = base64.b64encode((username + ':' + password).encode()).decode()
|
||||
return client.call('POST', '/api/v1/auth/sessions', (200, 201, 401, 429),
|
||||
headers={'Authorization': 'Basic ' + credential})
|
||||
|
||||
|
||||
def assert_no_secret(response, *secrets):
|
||||
body = response['bytes'].decode('utf-8', 'replace').lower()
|
||||
headers = ' '.join(f'{key}: {value}' for key, value in response['headers'].items()).lower()
|
||||
for secret in secrets:
|
||||
if not secret:
|
||||
continue
|
||||
check(secret.lower() not in body, 'error response leaked a credential')
|
||||
check(secret.lower() not in headers, 'error headers leaked a credential')
|
||||
|
||||
|
||||
def percentile(values, fraction):
|
||||
if not values:
|
||||
return 0.0
|
||||
ordered = sorted(values)
|
||||
index = max(0, min(len(ordered) - 1, int(math.ceil(fraction * len(ordered))) - 1))
|
||||
return ordered[index]
|
||||
|
||||
|
||||
def burst(base_url, ca_file, username, wrong_password, count):
|
||||
def attempt(_):
|
||||
return login(Client(base_url, ca_file), username, wrong_password)
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=count) as pool:
|
||||
return list(pool.map(attempt, range(count)))
|
||||
|
||||
|
||||
def check_username_budget(args):
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
username, password = register(client, 'known')
|
||||
wrong = 'wrong-' + uuid.uuid4().hex
|
||||
responses = burst(client.base, args.ca_file, username, wrong, args.username_limit)
|
||||
statuses = [response['status'] for response in responses]
|
||||
check(all(status == 401 for status in statuses),
|
||||
'an attempt below the per-username budget was rejected')
|
||||
for response in responses:
|
||||
assert_no_secret(response, username, wrong, password)
|
||||
|
||||
blocked = login(client, username, wrong)
|
||||
check(blocked['status'] == 429, 'attempt above the per-username budget was not rate limited')
|
||||
check(blocked['json']['error']['code'] == 'rate_limited', 'wrong rate-limit error code')
|
||||
retry_after = blocked['headers'].get('Retry-After', '')
|
||||
check(retry_after.isdigit() and 1 <= int(retry_after) <= args.window_seconds,
|
||||
'missing or out-of-window Retry-After')
|
||||
assert_no_secret(blocked, username, wrong, password)
|
||||
|
||||
instances = sorted({response['headers'].get('X-Instance-Id', '') for response in responses})
|
||||
check(len(instances) >= args.minimum_instances,
|
||||
'login attempts reached only ' + str(len(instances)) + ' API replica(s)')
|
||||
latencies = [response['elapsed'] for response in responses]
|
||||
check(blocked['elapsed'] < percentile(latencies, 0.50),
|
||||
'rate-limited response was not cheaper than the Argon2 verification path')
|
||||
|
||||
return {
|
||||
'limit': args.username_limit,
|
||||
'window_seconds': args.window_seconds,
|
||||
'allowed_under_limit': statuses.count(401),
|
||||
'blocked_status': blocked['status'],
|
||||
'blocked_code': blocked['json']['error']['code'],
|
||||
'retry_after_seconds': int(retry_after),
|
||||
'argon2_path_p50_ms': round(statistics.median(latencies) * 1000, 3),
|
||||
'argon2_path_p95_ms': round(percentile(latencies, 0.95) * 1000, 3),
|
||||
'rate_limited_ms': round(blocked['elapsed'] * 1000, 3),
|
||||
'observed_instances': instances,
|
||||
}
|
||||
|
||||
|
||||
def check_user_enumeration(args):
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
known_name, known_password = register(client, 'enum-known')
|
||||
wrong_known = 'wrong-' + uuid.uuid4().hex
|
||||
known = login(client, known_name, wrong_known)
|
||||
unknown_name = 'dos_missing_' + uuid.uuid4().hex
|
||||
wrong_unknown = 'wrong-' + uuid.uuid4().hex
|
||||
unknown = login(client, unknown_name, wrong_unknown)
|
||||
|
||||
check(known['status'] == 401 and unknown['status'] == 401,
|
||||
'known and unknown users did not receive the same 401 class')
|
||||
check(known['json']['error']['code'] == unknown['json']['error']['code'],
|
||||
'known and unknown users received different error codes')
|
||||
check(known['json']['error']['message'] == unknown['json']['error']['message'],
|
||||
'known and unknown users received different error messages')
|
||||
for response in (known, unknown):
|
||||
assert_no_secret(response, known_name, unknown_name, wrong_known, wrong_unknown,
|
||||
known_password)
|
||||
|
||||
return {
|
||||
'known_status': known['status'],
|
||||
'unknown_status': unknown['status'],
|
||||
'error_code': known['json']['error']['code'],
|
||||
'same_message': True,
|
||||
'known_ms': round(known['elapsed'] * 1000, 3),
|
||||
'unknown_ms': round(unknown['elapsed'] * 1000, 3),
|
||||
}
|
||||
|
||||
|
||||
def check_source_budget(args):
|
||||
if args.wait_window > 0:
|
||||
time.sleep(args.wait_window)
|
||||
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
latencies = []
|
||||
instances = set()
|
||||
for _ in range(args.source_limit):
|
||||
username = 'dos_source_' + uuid.uuid4().hex
|
||||
wrong = 'wrong-' + uuid.uuid4().hex
|
||||
response = login(client, username, wrong)
|
||||
check(response['status'] == 401,
|
||||
'an attempt below the per-source budget was rejected')
|
||||
assert_no_secret(response, username, wrong)
|
||||
latencies.append(response['elapsed'])
|
||||
instances.add(response['headers'].get('X-Instance-Id', ''))
|
||||
|
||||
blocked_username = 'dos_source_blocked_' + uuid.uuid4().hex
|
||||
blocked_wrong = 'wrong-' + uuid.uuid4().hex
|
||||
blocked = login(client, blocked_username, blocked_wrong)
|
||||
check(blocked['status'] == 429, 'attempt above the per-source budget was not rate limited')
|
||||
check(blocked['json']['error']['code'] == 'rate_limited', 'wrong source rate-limit code')
|
||||
retry_after = blocked['headers'].get('Retry-After', '')
|
||||
check(retry_after.isdigit() and 1 <= int(retry_after) <= args.window_seconds,
|
||||
'missing or out-of-window source Retry-After')
|
||||
assert_no_secret(blocked, blocked_username, blocked_wrong)
|
||||
|
||||
return {
|
||||
'limit': args.source_limit,
|
||||
'window_seconds': args.window_seconds,
|
||||
'allowed_under_limit': args.source_limit,
|
||||
'blocked_status': blocked['status'],
|
||||
'retry_after_seconds': int(retry_after),
|
||||
'argon2_path_p50_ms': round(statistics.median(latencies) * 1000, 3),
|
||||
'argon2_path_p95_ms': round(percentile(latencies, 0.95) * 1000, 3),
|
||||
'rate_limited_ms': round(blocked['elapsed'] * 1000, 3),
|
||||
'observed_instances': sorted(instances),
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
prefer_ipv4_for_localhost()
|
||||
args = arguments('Shared login rate-limit budget and credential non-disclosure', configure)
|
||||
check(args.username_limit >= 1 and args.source_limit >= args.username_limit,
|
||||
'limits must be positive and source >= username')
|
||||
check(args.window_seconds >= 1, 'window must be positive')
|
||||
|
||||
summary = {
|
||||
'username_budget': check_username_budget(args),
|
||||
'user_enumeration': check_user_enumeration(args),
|
||||
}
|
||||
if args.source_budget:
|
||||
summary['source_budget'] = check_source_budget(args)
|
||||
print(json.dumps(summary, indent=2, sort_keys=True))
|
||||
print('PASS: shared login budget, generic errors and fast rate-limit rejection verified.')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Reference in New Issue
Block a user