Complete lab 7 security implementation
This commit is contained in:
Executable
+110
@@ -0,0 +1,110 @@
|
||||
"""lab7: rehash старого bcrypt-хеша в argon2id после успешного login."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("--base-url", default="https://localhost:8443")
|
||||
p.add_argument("--ca-file", required=True)
|
||||
p.add_argument("--postgres-container", default="mtusi2026lab7-postgres-1")
|
||||
p.add_argument("--postgres-user", default="messenger")
|
||||
p.add_argument("--postgres-db", default="messenger")
|
||||
args = p.parse_args()
|
||||
|
||||
base = args.base_url.rstrip("/")
|
||||
ctx = ssl.create_default_context(cafile=args.ca_file)
|
||||
ctx.check_hostname = True
|
||||
ctx.verify_mode = ssl.CERT_REQUIRED
|
||||
|
||||
def call(method, path, headers=None, body=None, timeout=5):
|
||||
h = dict(headers or {})
|
||||
data = None
|
||||
if body is not None:
|
||||
data = json.dumps(body, ensure_ascii=False).encode()
|
||||
h["Content-Type"] = "application/json"
|
||||
req = urllib.request.Request(base + path, data=data, headers=h, method=method)
|
||||
try:
|
||||
r = urllib.request.urlopen(req, context=ctx, timeout=timeout)
|
||||
raw = r.read()
|
||||
return r.status, json.loads(raw) if raw else None
|
||||
except urllib.error.HTTPError as e:
|
||||
raw = e.read()
|
||||
try:
|
||||
return e.code, json.loads(raw) if raw else None
|
||||
except Exception:
|
||||
return e.code, None
|
||||
|
||||
def psql(sql):
|
||||
return subprocess.run(
|
||||
["docker", "exec", "-i", args.postgres_container,
|
||||
"psql", "-U", args.postgres_user, "-d", args.postgres_db, "-t", "-A", "-c", sql],
|
||||
capture_output=True, text=True, check=True,
|
||||
).stdout.strip()
|
||||
|
||||
# 1. Регистрация
|
||||
username = "rehash_" + uuid.uuid4().hex[:10]
|
||||
password = "rehash-pass-1234567890"
|
||||
code, user = call("POST", "/api/v1/users", body={
|
||||
"username": username, "display_name": "Rehash", "password": password,
|
||||
})
|
||||
if code != 201:
|
||||
print(f"FAIL: register {code} {user}")
|
||||
sys.exit(1)
|
||||
print(f"user: {username}")
|
||||
|
||||
# 2. Проверить argon2id
|
||||
h = psql(f"SELECT password_hash FROM users WHERE username='{username}'")
|
||||
if not h.startswith("$argon2id$"):
|
||||
print(f"FAIL: ожидали argon2id, получили {h[:30]}")
|
||||
sys.exit(1)
|
||||
print(f"initial hash: argon2id ({h[:20]}...)")
|
||||
|
||||
# 3. Заменить на bcrypt
|
||||
import bcrypt
|
||||
bcrypt_hash = bcrypt.hashpw(password.encode(), bcrypt.gensalt(rounds=10)).decode()
|
||||
psql(f"UPDATE users SET password_hash='{bcrypt_hash}' WHERE username='{username}'")
|
||||
h2 = psql(f"SELECT password_hash FROM users WHERE username='{username}'")
|
||||
if not h2.startswith("$2b$"):
|
||||
print(f"FAIL: ожидали bcrypt, получили {h2[:20]}")
|
||||
sys.exit(1)
|
||||
print(f"replaced with bcrypt: {h2[:20]}...")
|
||||
|
||||
# 4. Login — verify OK
|
||||
cred = base64.b64encode(f"{username}:{password}".encode()).decode()
|
||||
code, session = call("POST", "/api/v1/auth/sessions",
|
||||
headers={"Authorization": "Basic " + cred})
|
||||
if code != 201:
|
||||
print(f"FAIL: login with bcrypt — ожидали 201, получили {code}")
|
||||
sys.exit(1)
|
||||
print(f"login with bcrypt: 201 (verify OK)")
|
||||
|
||||
# 5. После login — argon2id
|
||||
h3 = psql(f"SELECT password_hash FROM users WHERE username='{username}'")
|
||||
if not h3.startswith("$argon2id$"):
|
||||
print(f"FAIL: rehash не сработал — password_hash={h3[:20]}")
|
||||
sys.exit(1)
|
||||
print(f"after login: argon2id ({h3[:20]}...) — rehash OK")
|
||||
|
||||
# 6. Повторный login — argon2id verify OK
|
||||
code, session = call("POST", "/api/v1/auth/sessions",
|
||||
headers={"Authorization": "Basic " + cred})
|
||||
if code != 201:
|
||||
print(f"FAIL: повторный login — ожидали 201, получили {code}")
|
||||
sys.exit(1)
|
||||
print("повторный login: 201 (argon2id verify OK)")
|
||||
|
||||
print("\nPASS: bcrypt → argon2id rehash при успешном login")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user