1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
| import json import re import time import uuid from hashlib import sha256 from typing import Optional
import redis from flask import Flask, jsonify, redirect, render_template, request, session, url_for from werkzeug.middleware.proxy_fix import ProxyFix from webauthn import ( generate_authentication_options, generate_registration_options, options_to_json, verify_authentication_response, verify_registration_response, ) try: from webauthn.helpers import parse_authentication_credential_json, parse_registration_credential_json except ImportError: parse_authentication_credential_json = None parse_registration_credential_json = None from webauthn.helpers.structs import PublicKeyCredentialDescriptor, UserVerificationRequirement
from app.init_data import bootstrap from app.logger import Logger from app.models import ( create_credential, create_user, get_credential_by_id, get_credential_for_user, get_user_by_id, get_user_by_username, list_credentials_for_user, update_credential_sign_count, ) from app.utils import ( b64url_decode, b64url_encode, get_database_path, get_flag, get_origin, get_origin_host, get_redis_url, get_rp_id, get_rp_name, get_secret_key, sha256_hex, )
CHALLENGE_TTL_SECONDS = 120 REGISTRATION_TTL_SECONDS = 300 USERNAME_RE = re.compile(r"^[A-Za-z0-9_]{3,32}$")
bootstrap()
app = Flask(__name__, template_folder="templates", static_folder="static") app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_port=1) app.config.update( SECRET_KEY=get_secret_key(), SESSION_COOKIE_NAME="tkp_session", SESSION_COOKIE_HTTPONLY=True, SESSION_COOKIE_SAMESITE="Lax", )
redis_client = redis.Redis.from_url(get_redis_url(), decode_responses=True)
def get_or_create_session_id() -> str: if "sid" not in session: session["sid"] = uuid.uuid4().hex return session["sid"]
def current_user(): user_id = session.get("user_id") if not user_id: return None return get_user_by_id(user_id)
def wants_json() -> bool: return request.path.startswith("/login/") or request.path.startswith("/register/") or request.path == "/healthz"
def error_response(message: str, status_code: int = 400): if wants_json(): return jsonify({"ok": False, "error": message}), status_code return render_template("index.html", user=current_user(), error=message), status_code
def challenge_key_for_session() -> str: return f"challenge:{get_or_create_session_id()}"
def register_key_for_session() -> str: return f"register:{get_or_create_session_id()}"
def validate_username(raw_username: str) -> Optional[str]: username = raw_username.strip() if not USERNAME_RE.fullmatch(username): return None return username
@app.get("/") def index(): return render_template("index.html", user=current_user(), error=None)
@app.get("/register") def register_page(): return render_template("register.html", user=current_user(), error=None)
@app.post("/register/begin") def register_begin(): payload = request.get_json(silent=True) or {} username = validate_username(payload.get("username", "")) if not username: return jsonify({"ok": False, "error": "username must be 3-32 chars of letters, digits, or underscore"}), 400
if get_user_by_username(username): return jsonify({"ok": False, "error": "username already exists"}), 400
user_handle = sha256(f"user:{username}".encode("utf-8")).digest()[:16] options = generate_registration_options( rp_id=get_rp_id(), rp_name=get_rp_name(), user_id=user_handle, user_name=username, timeout=60000, )
redis_client.setex( register_key_for_session(), REGISTRATION_TTL_SECONDS, json.dumps({"challenge": b64url_encode(options.challenge), "username": username}), ) return jsonify(json.loads(options_to_json(options)))
@app.post("/register/finish") def register_finish(): credential = request.get_json(silent=True) or {} parsed_credential = credential if parse_registration_credential_json is not None: parsed_credential = parse_registration_credential_json(json.dumps(credential))
raw_state = redis_client.get(register_key_for_session()) if raw_state is None: return jsonify({"ok": False, "error": "registration state expired"}), 400
state = json.loads(raw_state) username = state["username"] if get_user_by_username(username): redis_client.delete(register_key_for_session()) return jsonify({"ok": False, "error": "username already exists"}), 400
try: verification = verify_registration_response( credential=parsed_credential, expected_challenge=b64url_decode(state["challenge"]), expected_rp_id=get_rp_id(), expected_origin=get_origin(), require_user_verification=False, ) except Exception as exc: return jsonify({"ok": False, "error": f"registration verification failed: {exc}"}), 400
user = create_user(username, is_admin=False) create_credential( user_id=user.id, credential_id=b64url_encode(verification.credential_id), public_key=b64url_encode(verification.credential_public_key), sign_count=verification.sign_count, )
redis_client.delete(register_key_for_session()) session["user_id"] = user.id return jsonify({"ok": True, "redirect": url_for("dashboard")})
@app.get("/login") def login_page(): return render_template("login.html", user=current_user(), error=None)
@app.post("/login/begin") def login_begin(): payload = request.get_json(silent=True) or {} username = validate_username(payload.get("username", "")) if not username: return jsonify({"ok": False, "error": "valid username is required"}), 400
user = get_user_by_username(username) if user is None: return jsonify({"ok": False, "error": "unknown user"}), 404
credentials = list_credentials_for_user(user.id) if not credentials: return jsonify({"ok": False, "error": "user has no passkeys"}), 400
options = generate_authentication_options( rp_id=get_rp_id(), allow_credentials=[ PublicKeyCredentialDescriptor(id=b64url_decode(credential.credential_id)) for credential in credentials ], timeout=60000, user_verification=UserVerificationRequirement.PREFERRED, )
redis_client.setex( challenge_key_for_session(), CHALLENGE_TTL_SECONDS, json.dumps( { "challenge": b64url_encode(options.challenge), "username": user.username, "created_at": time.time(), } ), ) return jsonify(json.loads(options_to_json(options)))
@app.post("/login/finish") def login_finish(): credential = request.get_json(silent=True) or {} parsed_credential = credential if parse_authentication_credential_json is not None: parsed_credential = parse_authentication_credential_json(json.dumps(credential))
presented_credential_id = credential.get("id", "") if not presented_credential_id: return jsonify({"ok": False, "error": "credential id is required"}), 400
raw_state = redis_client.get(challenge_key_for_session()) if raw_state is None: return jsonify({"ok": False, "error": "challenge expired"}), 400
state = json.loads(raw_state)
if not state.get("verification_complete"): expected_user = get_user_by_username(state["username"]) if expected_user is None: return jsonify({"ok": False, "error": "expected login user disappeared"}), 400
expected_credential = get_credential_for_user(expected_user.id, presented_credential_id) if expected_credential is None: return jsonify({"ok": False, "error": "credential is not registered for this username"}), 400
try: verification = verify_authentication_response( credential=parsed_credential, expected_challenge=b64url_decode(state["challenge"]), expected_rp_id=get_rp_id(), expected_origin=get_origin(), credential_public_key=b64url_decode(expected_credential.public_key), credential_current_sign_count=expected_credential.sign_count, require_user_verification=False, ) except Exception as exc: return jsonify({"ok": False, "error": f"authentication failed: {exc}"}), 400
update_credential_sign_count(expected_credential.credential_id, verification.new_sign_count)
state["verification_complete"] = True state["verified_credential_id"] = expected_credential.credential_id redis_client.setex(challenge_key_for_session(), CHALLENGE_TTL_SECONDS, json.dumps(state))
log = Logger("app.log") log.log(f"User {state['username']} authenticated with credential {presented_credential_id}") redis_client.delete(challenge_key_for_session())
final_credential = get_credential_by_id(presented_credential_id) if final_credential is None: return jsonify({"ok": False, "error": "unknown credential id"}), 400
final_user = get_user_by_id(final_credential.user_id) if final_user is None: return jsonify({"ok": False, "error": "credential owner disappeared"}), 400
session["user_id"] = final_user.id return jsonify( { "ok": True, "redirect": url_for("dashboard"), "user": final_user.username, "is_admin": final_user.is_admin, } )
@app.get("/dashboard") def dashboard(): user = current_user() if user is None: return redirect(url_for("login_page"))
credentials = [ { "hash": sha256_hex(credential.credential_id), "sign_count": credential.sign_count, } for credential in list_credentials_for_user(user.id) ] return render_template( "dashboard.html", user=user, credentials=credentials, flag=get_flag() if user.is_admin else None, )
@app.get("/logout") def logout(): session.clear() return redirect(url_for("index"))
if __name__ == "__main__": app.run(host="0.0.0.0", port=8000, debug=True)
|