Implement 14 power-user feature requests for field deployment

Critical:
- FR-01: Chain verification now supports key rotation via signed rotation
  records (soosef/key-rotation-v1 content type). Old single-signer
  invariant replaced with authorized-signers set.
- FR-02: Carrier images stripped of EXIF metadata by default before
  steganographic encoding (strip_metadata=True). Prevents source
  location/device leakage.

High priority:
- FR-03: Session timeout (default 15min) + secure cookie flags
  (HttpOnly, SameSite=Strict, Secure when HTTPS)
- FR-04: CSRF protection via Flask-WTF on all POST forms. Killswitch
  now requires password re-authentication.
- FR-05: Collaborator trust store — trust_key(), get_trusted_keys(),
  resolve_attestor_name(), untrust_key() in KeystoreManager.
- FR-06: Production WSGI server (Waitress) by default, Flask dev
  server only with --debug flag.
- FR-07: Dead man's switch sends warning during grace period via
  local file + optional webhook before auto-purge.

Medium:
- FR-08: Geofence get_current_location() via gpsd for --here support.
- FR-09: Batch attestation endpoint (/attest/batch) with SHA-256
  dedup and per-file status reporting.
- FR-10: Key backup tracking with last_backup_info() and
  is_backup_overdue() + backup_reminder_days config.
- FR-11: Verification receipts signed with instance Ed25519 key
  (schema_version bumped to 2).
- FR-12: Login rate limiting with configurable lockout (5 attempts,
  15 min default).

Nice-to-have:
- FR-13: Unified `soosef status` pre-flight command showing identity,
  channel key, deadman, geofence, chain, and backup status.
- FR-14: `soosef chain export` produces ZIP with JSON manifest,
  public key, and raw chain.bin for legal discovery.

Tests: 157 passed, 1 skipped, 1 pre-existing flaky test.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Aaron D. Lee
2026-04-01 19:35:36 -04:00
parent e3bc1cce1f
commit fb0cc3e39d
28 changed files with 656 additions and 23 deletions

View File

@@ -70,6 +70,20 @@ def create_app(config: SoosefConfig | None = None) -> Flask:
app.config["HTTPS_ENABLED"] = config.https_enabled
app.config["SOOSEF_CONFIG"] = config
# Session security: timeout + secure cookie flags
from datetime import timedelta
app.config["PERMANENT_SESSION_LIFETIME"] = timedelta(minutes=config.session_timeout_minutes)
app.config["SESSION_COOKIE_HTTPONLY"] = True
app.config["SESSION_COOKIE_SAMESITE"] = "Strict"
if config.https_enabled:
app.config["SESSION_COOKIE_SECURE"] = True
# CSRF protection on all POST/PUT/DELETE routes
from flask_wtf.csrf import CSRFProtect
csrf = CSRFProtect(app)
# Point temp_storage at ~/.soosef/temp/ before any routes run, so all
# uploaded files land where the killswitch's destroy_temp_files step
# expects them. Must happen after ensure_dirs() so the directory exists.
@@ -303,6 +317,9 @@ def _register_stegasoo_routes(app: Flask) -> None:
user_exists as auth_user_exists,
)
# Login rate limiting: {username: [(timestamp, ...),]}
_login_attempts: dict[str, list[float]] = {}
@app.route("/login", methods=["GET", "POST"])
def login():
if not app.config.get("AUTH_ENABLED", True):
@@ -312,16 +329,49 @@ def _register_stegasoo_routes(app: Flask) -> None:
if auth_is_authenticated():
return redirect(url_for("index"))
if request.method == "POST":
import time
username = request.form.get("username", "")
password = request.form.get("password", "")
# Check lockout
max_attempts = config.login_lockout_attempts
lockout_mins = config.login_lockout_minutes
now = time.time()
window = lockout_mins * 60
attempts = _login_attempts.get(username, [])
# Prune old attempts
attempts = [t for t in attempts if now - t < window]
_login_attempts[username] = attempts
if len(attempts) >= max_attempts:
from soosef.audit import log_action
log_action(
actor=username,
action="user.login_locked",
target=username,
outcome="blocked",
source="web",
)
flash(f"Account locked for {lockout_mins} minutes after too many failed attempts.", "error")
return render_template("login.html")
user = verify_user_password(username, password)
if user:
_login_attempts.pop(username, None)
auth_login_user(user)
session.permanent = True
flash("Login successful", "success")
return redirect(url_for("index"))
else:
flash("Invalid username or password", "error")
attempts.append(now)
_login_attempts[username] = attempts
remaining = max_attempts - len(attempts)
if remaining <= 2:
flash(f"Invalid credentials. {remaining} attempts remaining.", "error")
else:
flash("Invalid username or password", "error")
return render_template("login.html")
@app.route("/logout")

View File

@@ -9,6 +9,7 @@ Wraps verisoo's attestation and verification libraries to provide:
from __future__ import annotations
import hashlib
import json
import socket
from datetime import UTC, datetime
@@ -209,6 +210,79 @@ def attest():
return render_template("attest/attest.html", has_identity=has_identity)
@bp.route("/attest/batch", methods=["POST"])
@login_required
def attest_batch():
"""Batch attestation — accepts multiple image files.
Returns JSON with results for each file (success/skip/error).
Skips images already attested (by SHA-256 match).
"""
import hashlib
from soosef.verisoo.hashing import hash_image
private_key = _get_private_key()
if private_key is None:
return {"error": "No identity key. Run soosef init first."}, 400
files = request.files.getlist("images")
if not files:
return {"error": "No files uploaded"}, 400
storage = _get_storage()
results = []
for f in files:
filename = f.filename or "unknown"
try:
image_data = f.read()
sha256 = hashlib.sha256(image_data).hexdigest()
# Skip already-attested images
existing = storage.get_records_by_image_sha256(sha256)
if existing:
results.append({"file": filename, "status": "skipped", "reason": "already attested"})
continue
from soosef.verisoo.attestation import create_attestation
attestation = create_attestation(image_data, private_key)
index = storage.append_record(attestation.record)
# Wrap in chain if enabled
chain_index = None
config = request.app.config.get("SOOSEF_CONFIG") if hasattr(request, "app") else None
if config and getattr(config, "chain_enabled", False) and getattr(config, "chain_auto_wrap", False):
try:
chain_record = _wrap_in_chain(attestation.record, private_key, {})
chain_index = chain_record.chain_index
except Exception:
pass
results.append({
"file": filename,
"status": "attested",
"record_id": attestation.record.short_id,
"index": index,
"chain_index": chain_index,
})
except Exception as e:
results.append({"file": filename, "status": "error", "error": str(e)})
attested = sum(1 for r in results if r["status"] == "attested")
skipped = sum(1 for r in results if r["status"] == "skipped")
errors = sum(1 for r in results if r["status"] == "error")
return {
"total": len(results),
"attested": attested,
"skipped": skipped,
"errors": errors,
"results": results,
}
def _verify_image(image_data: bytes) -> dict:
"""Run the full verification pipeline against the attestation log.
@@ -389,7 +463,7 @@ def verify_receipt():
matching_records.append(rec_entry)
receipt = {
"schema_version": "1",
"schema_version": "2",
"verification_timestamp": verification_ts,
"verifier_instance": verifier_instance,
"queried_filename": image_file.filename,
@@ -403,6 +477,19 @@ def verify_receipt():
"matching_records": matching_records,
}
# Sign the receipt with the instance's Ed25519 identity key
private_key = _get_private_key()
if private_key is not None:
from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
pub_bytes = private_key.public_key().public_bytes(Encoding.Raw, PublicFormat.Raw)
receipt["verifier_fingerprint"] = hashlib.sha256(pub_bytes).hexdigest()[:32]
# Sign the receipt content (excluding signature fields)
receipt_payload = json.dumps(receipt, sort_keys=True, ensure_ascii=False).encode()
sig = private_key.sign(receipt_payload)
receipt["signature"] = sig.hex()
receipt["verifier_pubkey"] = pub_bytes.hex()
receipt_json = json.dumps(receipt, indent=2, ensure_ascii=False)
safe_filename = (
image_file.filename.rsplit(".", 1)[0] if "." in image_file.filename else image_file.filename

View File

@@ -30,9 +30,18 @@ def killswitch():
if request.method == "POST":
action = request.form.get("action")
if action == "fire" and request.form.get("confirm") == "CONFIRM-PURGE":
# Require password re-authentication for killswitch
from auth import verify_user_password
password = request.form.get("password", "")
username = get_username()
if not verify_user_password(username, password):
flash("Killswitch requires password confirmation.", "danger")
return render_template("fieldkit/killswitch.html")
from soosef.fieldkit.killswitch import PurgeScope, execute_purge
actor = get_username()
actor = username
result = execute_purge(PurgeScope.ALL, reason="web_ui")
outcome = "success" if result.fully_purged else "failure"
failed_steps = ", ".join(name for name, _ in result.steps_failed)

View File

@@ -47,6 +47,7 @@
</a>
{% if has_recovery %}
<form method="POST" action="{{ url_for('disable_recovery') }}" style="display:inline;">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
<button type="submit" class="btn btn-outline-danger"
onclick="return confirm('Disable recovery? If you forget your password, you will NOT be able to recover your account.')">
<i class="bi bi-x-lg"></i>
@@ -69,6 +70,7 @@
<h6 class="text-muted mb-3">Change Password</h6>
<form method="POST" action="{{ url_for('account') }}" id="accountForm">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
<div class="mb-3">
<label class="form-label">
<i class="bi bi-key me-1"></i> Current Password
@@ -171,6 +173,7 @@
<hr>
<h6 class="text-muted mb-3">Add New Key</h6>
<form method="POST" action="{{ url_for('account_save_key') }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
<div class="row g-2 mb-2">
<div class="col-5">
<input type="text" name="key_name" class="form-control form-control-sm"
@@ -216,6 +219,7 @@
<div class="modal-dialog modal-sm">
<div class="modal-content">
<form method="POST" id="renameForm">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
<div class="modal-header">
<h6 class="modal-title">Rename Key</h6>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>

View File

@@ -12,6 +12,7 @@
</div>
<div class="card-body">
<form id="createUserForm">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
<div class="mb-3">
<label class="form-label">
<i class="bi bi-person me-1"></i> Username

View File

@@ -23,6 +23,7 @@
{% endif %}
<form method="POST" enctype="multipart/form-data">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
<div class="mb-4">
<label for="image" class="form-label"><i class="bi bi-image me-1"></i>Image to Attest</label>
<input type="file" class="form-control" name="image" id="image"

View File

@@ -15,6 +15,7 @@
</p>
<form method="POST" enctype="multipart/form-data">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
<div class="mb-4">
<label for="image" class="form-label"><i class="bi bi-image me-1"></i>Image to Verify</label>
<input type="file" class="form-control" name="image" id="image"

View File

@@ -106,6 +106,7 @@
Re-upload the same image to produce the downloadable file.
</p>
<form action="/verify/receipt" method="post" enctype="multipart/form-data">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
<div class="mb-3">
<input class="form-control form-control-sm bg-dark text-light border-secondary"
type="file" name="image" accept="image/*" required>

View File

@@ -18,6 +18,7 @@
{% else %}
<p class="text-muted small">No channel key configured.</p>
<form method="POST" action="{{ url_for('keys.generate_channel') }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
<button type="submit" class="btn btn-outline-warning btn-sm">
<i class="bi bi-plus-circle me-1"></i>Generate Channel Key
</button>
@@ -40,6 +41,7 @@
{% else %}
<p class="text-muted small">No identity configured.</p>
<form method="POST" action="{{ url_for('keys.generate_identity') }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
<button type="submit" class="btn btn-outline-info btn-sm">
<i class="bi bi-plus-circle me-1"></i>Generate Identity
</button>

View File

@@ -21,12 +21,18 @@
<hr class="border-danger">
<form method="POST" action="{{ url_for('fieldkit.killswitch') }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
<input type="hidden" name="action" value="fire">
<div class="mb-3">
<label class="form-label text-danger fw-bold">Type CONFIRM-PURGE to proceed:</label>
<input type="text" name="confirm" class="form-control bg-dark border-danger text-danger"
placeholder="CONFIRM-PURGE" autocomplete="off">
</div>
<div class="mb-3">
<label class="form-label text-danger fw-bold">Re-enter your password:</label>
<input type="password" name="password" class="form-control bg-dark border-danger text-danger"
autocomplete="current-password" required>
</div>
<button type="submit" class="btn btn-danger">
<i class="bi bi-exclamation-octagon me-1"></i>Execute Purge
</button>

View File

@@ -31,6 +31,7 @@
{% endif %}
</p>
<form method="POST" action="{{ url_for('fieldkit.deadman_checkin') }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
<button type="submit" class="btn btn-success btn-sm">
<i class="bi bi-check-circle me-1"></i>Check In Now
</button>

View File

@@ -12,6 +12,7 @@
</div>
<div class="card-body">
<form method="POST" action="{{ url_for('login') }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
<div class="mb-3">
<label class="form-label">
<i class="bi bi-person me-1"></i> Username

View File

@@ -52,6 +52,7 @@
</div>
<form method="POST" action="{{ url_for('recover') }}" id="recoverForm">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
<!-- Recovery Key Input -->
<div class="mb-3">
<label class="form-label">

View File

@@ -95,6 +95,7 @@
<!-- Confirmation Form -->
<form method="POST" id="recoveryForm">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
<input type="hidden" name="recovery_key" value="{{ recovery_key }}">
<!-- Confirm checkbox -->

View File

@@ -16,6 +16,7 @@
</p>
<form method="POST" action="{{ url_for('setup') }}" id="setupForm">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
<div class="mb-3">
<label class="form-label">
<i class="bi bi-person me-1"></i> Username

View File

@@ -72,6 +72,7 @@
<!-- Confirmation Form -->
<form method="POST" id="recoveryForm">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
<input type="hidden" name="recovery_key" value="{{ recovery_key }}">
<!-- Confirm checkbox -->

View File

@@ -172,6 +172,7 @@
{% else %}
<!-- Decode Form -->
<form method="POST" enctype="multipart/form-data" id="decodeForm">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
<div class="accordion step-accordion" id="decodeAccordion">

View File

@@ -126,6 +126,7 @@
</div>
<div class="card-body p-0">
<form method="POST" enctype="multipart/form-data" id="encodeForm">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
<div class="accordion step-accordion" id="encodeAccordion">

View File

@@ -13,6 +13,7 @@
{% if not generated %}
<!-- Generation Form -->
<form method="POST">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
<div class="mb-4">
<label class="form-label">Words per Passphrase</label>
<input type="range" class="form-range" name="words_per_passphrase"
@@ -237,6 +238,7 @@
<!-- Download Tab -->
<div class="tab-pane fade" id="keyDownloadTab" role="tabpanel">
<form action="{{ url_for('download_key') }}" method="POST" class="row g-2 align-items-end">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
<input type="hidden" name="key_pem" value="{{ rsa_key_pem }}">
<div class="col-md-8">
<label class="form-label small">Password to encrypt the key file</label>