chore: import MCTF services

- Added all seven issued service trees without omissions.
- Preserved the supplied runtime configuration, binaries, and assets.
This commit is contained in:
TakuyaYagam1 committed 2026-11-29 12:25:29 +03:00
commit 13f936bee9
1222 files changed
+21280

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
from flask import current_app
def ledger():
return current_app.extensions["ledger"]
+8
View File
@@ -0,0 +1,8 @@
from flask import abort, request
def json_object():
payload = request.get_json(silent=True)
if not isinstance(payload, dict):
abort(400, "Expected a JSON object")
return payload
+68
View File
@@ -0,0 +1,68 @@
import re
import sqlite3
from uuid import uuid4
from flask import Blueprint, abort, current_app, g
from werkzeug.security import check_password_hash, generate_password_hash
from backend.app.common.utils import account_namespace, utc_now, valid_text
from backend.app.infrastructure.persistence import repositories
from backend.app.infrastructure.persistence.connection import database
from backend.app.api.request import json_object
from backend.app.api.session import owner_session, sign_in
USERNAME = re.compile(r"[A-Za-z0-9_-]{3,32}")
BAD_CREDENTIALS = "Invalid username or password"
bp = Blueprint("auth", __name__)
@bp.post("/register")
def register():
payload = json_object()
username = payload.get("username")
password = payload.get("password")
if not isinstance(username, str) or not USERNAME.fullmatch(username):
abort(400, "Username must contain 3-32 ASCII letters, digits, _ or -")
if not valid_text(password, 8, 128):
abort(400, "Password must contain 8-128 ASCII characters")
user_id = str(uuid4())
namespace = account_namespace(username)
password_hash = generate_password_hash(password, method="scrypt")
connection = database()
try:
with connection:
repositories.create_user(connection, user_id, username, namespace, password_hash, utc_now().isoformat())
except sqlite3.IntegrityError:
abort(409, "Username is already taken")
return sign_in(user_id, username), 201
@bp.post("/login")
def login():
payload = json_object()
username = payload.get("username")
password = payload.get("password")
valid_username = isinstance(username, str) and USERNAME.fullmatch(username)
valid_password = valid_text(password, 8, 128)
row = repositories.get_user_by_username(database(), username if valid_username else "")
correct = check_password_hash(
row["password_hash"] if row else current_app.extensions["ledger"].dummy_hash,
password if valid_password else "",
)
if not correct or row is None or not valid_password:
abort(401, BAD_CREDENTIALS)
return sign_in(row["id"], row["username"])
@bp.get("/home/api/me")
@owner_session
def me():
return g.user
@bp.delete("/home/api/logout")
@owner_session
def logout():
connection = database()
with connection:
repositories.delete_auth_session(connection, g.token_id)
return "", 204
+49
View File
@@ -0,0 +1,49 @@
from flask import Blueprint, g, request, abort
from backend.app.infrastructure.persistence import repositories
from backend.app.infrastructure.persistence.connection import database
from backend.app.application import implants
from backend.app.api.request import json_object
from backend.app.api.context import ledger
from backend.app.api.session import owner_session, claimed_username
bp = Blueprint("implants", __name__, url_prefix="/home/api")
@bp.post("/register_implant")
@owner_session
def register_implant():
return implants.register(database(), ledger(), g.user["id"], json_object()), 201
@bp.get("/implants")
@owner_session
def list_implants():
return implants.list_owned(database(), g.user["id"])
@bp.get("/telemetry")
@owner_session
def telemetry():
username = request.args.get("username") or g.user["username"]
if claimed_username(g.token) != username:
return {"error": "access denied"}, 403
user = repositories.get_user_by_username(database(), username)
if user is None:
abort(404)
return implants.telemetry(database(), user["id"])
@bp.get("/implants/<implant_id>")
@owner_session
def implant_passport(implant_id):
return implants.passport(database(), ledger(), implant_id, g.user["id"])
@bp.route("/check_certificate/<implant_id>/check", methods=["GET", "POST"])
@owner_session
def check_certificate(implant_id):
payload = json_object() if request.method == "POST" else None
return implants.check_certificate(database(), ledger(), implant_id, g.user["id"], payload)
@bp.post("/reissue/<implant_id>")
@owner_session
def reissue_certificate(implant_id):
return implants.reissue(database(), ledger(), implant_id, json_object()), 200
+14
View File
@@ -0,0 +1,14 @@
from flask import Blueprint
from backend.app.infrastructure.persistence.connection import database
from backend.app.application import implants
from backend.app.api.session import owner_session
from backend.app.api.context import ledger
bp = Blueprint("registry", __name__, url_prefix="/home/api")
@bp.get("/registry")
@owner_session
def registry():
return implants.registry(database(), ledger())
+66
View File
@@ -0,0 +1,66 @@
from functools import wraps
from flask import abort, g, request
from obsigil import Obsigil, ObsigilError, generate_uuid7
from backend.app.api.context import ledger
from backend.app.common.constants import AUTH_AUDIENCE, AUTH_LIFETIME
from backend.app.common.utils import utc_now
from backend.app.infrastructure.persistence import repositories
from backend.app.infrastructure.persistence.connection import database
def sign_in(user_id, username):
now = int(utc_now().timestamp())
expires_at = now + int(AUTH_LIFETIME.total_seconds())
tid = generate_uuid7()
token = Obsigil.mint(
clauses={}, mandate_key=ledger().obsigil_key, tid=tid,
sub=user_id, aud=[AUTH_AUDIENCE], exp=expires_at,
manifest={"iss": AUTH_AUDIENCE, "claims": {"username": username}},
).token()
connection = database()
with connection:
repositories.delete_auth_session(connection, g.token_id)
repositories.create_auth_session(connection, tid, user_id, expires_at)
return {"id": user_id, "username": username, "access_token": token}
def claimed_username(token):
claims = Obsigil(token, max_decoded_len=4096).claims() or {}
username = claims.get("username")
return username if isinstance(username, str) else None
def load_identity():
g.user = None
g.token = None
g.token_id = None
authorization = request.headers.get("Authorization", "").split()
if len(authorization) != 2 or authorization[0].lower() != "bearer":
return
token = authorization[1]
if len(token) > 4096:
return
now = int(utc_now().timestamp())
try:
clauses = Obsigil(
token, keys=ledger().obsigil_key, audience=AUTH_AUDIENCE,
now=now, max_decoded_len=4096,
).clauses()
except ObsigilError:
return
user_id = clauses.get("sub")
if not isinstance(user_id, str) or clauses.get("aud") != [AUTH_AUDIENCE]:
return
row = repositories.get_auth_user(database(), clauses["tid"], user_id, clauses["exp"], now)
if row is not None:
g.user = dict(row)
g.token = token
g.token_id = clauses["tid"]
def owner_session(route):
@wraps(route)
def guarded(*args, **kwargs):
if g.user is None:
abort(401, "Authentication required")
return route(*args, **kwargs)
return guarded
+36
View File
@@ -0,0 +1,36 @@
from pathlib import Path
from flask import Blueprint, abort, make_response, send_from_directory
from werkzeug.security import safe_join
from backend.app.api.context import ledger
bp = Blueprint("console", __name__)
@bp.get("/", defaults={"path": ""})
@bp.get("/<path:path>")
def console(path):
static_root = ledger().static_root
public_root = static_root / "public"
if path.startswith("src/"):
source_path = path.removeprefix("src/")
source_root = static_root / "src"
target = safe_join(str(source_root), source_path)
if target and Path(target).is_file():
return send_from_directory(source_root, source_path)
abort(404)
target = safe_join(str(public_root), path)
if path and path != "index.html" and target and Path(target).is_file():
return send_from_directory(public_root, path)
pages = {"", "login", "home", "home/register_implant", "home/check_certificate", "home/reissue", "home/implants", "home/registry"}
if path not in pages and not (
(path.startswith("home/implants/") and len(path.split("/")) == 3)
or (path.startswith("home/check_certificate/") and len(path.split("/")) == 4 and path.endswith("/check"))
):
abort(404)
index = public_root / "index.html"
if not index.is_file():
abort(503, "Console not found")
response = make_response(index.read_text(encoding="utf-8"))
response.headers["Cache-Control"] = "no-store"
return response
+64
View File
@@ -0,0 +1,64 @@
import json
from hmac import compare_digest
from Crypto.Random import get_random_bytes
from backend.app.common.constants import HEX_CHALLENGE
from backend.app.common.errors import LedgerError
from backend.app.common.utils import utc_now, valid_text
from backend.app.infrastructure.security import certificates, envelopes, keys
from backend.app.infrastructure.persistence import repositories
def implant(connection, implant_id, owner_id=None):
row = repositories.get_implant(connection, implant_id)
if row is None or (owner_id is not None and row["user_id"] != owner_id):
raise LedgerError(404, "Implant not found")
return row
def challenge(connection, ledger, implant_id, owner_id):
with connection:
connection.execute("BEGIN IMMEDIATE")
implant(connection, implant_id)
current = repositories.get_current_certificate(connection, implant_id)
if current is None or not certificates.valid(certificates.load_certificate(current["cert_pem"]), ledger.ca):
raise LedgerError(409, "Implant has no valid certificate")
nonce = get_random_bytes(32).hex()
repositories.create_implant_challenge(connection, nonce, implant_id, current["serial"], utc_now())
return {"id": implant_id, "challenge": nonce, "certificate_serial": current["serial"], "certificate": dict(current)}
def read_details(connection, ledger, implant_id, owner_id, payload):
invalid = "Invalid certificate, signature or challenge"
pem = payload.get("certificate")
signature = payload.get("signature")
nonce = payload.get("nonce")
if not valid_text(pem, 1, 60_000) or not isinstance(signature, str) or not isinstance(nonce, str):
raise LedgerError(401, invalid)
if not HEX_CHALLENGE.fullmatch(nonce):
raise LedgerError(401, invalid)
try:
certificate = certificates.load_certificate(pem)
except ValueError:
raise LedgerError(401, invalid) from None
with connection:
connection.execute("BEGIN IMMEDIATE")
row = implant(connection, implant_id)
if not compare_digest(certificates.subject_implant_id(certificate), implant_id):
raise LedgerError(401, invalid)
stored = repositories.get_certificate(connection, implant_id, format(certificate.serial_number, "x"))
if stored is None or stored["revoked_at"]:
raise LedgerError(401, invalid)
if not certificates.valid(certificates.load_certificate(stored["cert_pem"]), ledger.ca):
raise LedgerError(401, invalid)
if not keys.verify_implant_signature(certificate.public_key(), signature, nonce):
raise LedgerError(401, invalid)
consumed = repositories.consume_implant_challenge(
connection, nonce, implant_id, stored["serial"],
(utc_now() - ledger.challenge_lifetime).isoformat(),
)
if not consumed:
raise LedgerError(401, invalid)
details = json.loads(envelopes.decode_envelope(ledger.master_key, row["details"], implant_id))
return {"id": implant_id, "certificate": dict(stored), **details}
+68
View File
@@ -0,0 +1,68 @@
from hashlib import sha256
from cryptography import x509
from cryptography.exceptions import UnsupportedAlgorithm
from cryptography.hazmat.primitives import hashes, serialization
from backend.app.common.errors import LedgerError
from backend.app.common.utils import utc_now, valid_text
from backend.app.infrastructure.security import certificates, keys
def public_key(payload):
pem = payload.get("public_key_pem")
if not valid_text(pem, 1, 60_000):
raise LedgerError(400, "Provide a public key in PEM format")
try:
return keys.parse_public_key(pem)
except keys.UnsupportedKeyType:
raise LedgerError(400, "Supported keys are ECDSA P-256 and RSA with at least 2048 bits") from None
except ValueError:
raise LedgerError(400, "Invalid PEM public key") from None
def signing_request(payload):
pem = payload.get("csr_pem")
if not valid_text(pem, 1, 60_000):
raise LedgerError(400, "Provide a signed CSR in PEM format")
try:
request = x509.load_pem_x509_csr(pem.encode("ascii"))
if not request.is_signature_valid:
raise ValueError
key_pem = request.public_key().public_bytes(
serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo,
).decode("ascii")
except (ValueError, UnsupportedAlgorithm):
raise LedgerError(400, "Invalid CSR or CSR signature") from None
key = public_key({"public_key_pem": key_pem})
return key, sha256(request.public_bytes(serialization.Encoding.DER)).hexdigest()
def issue(ledger, implant_id, key, now, display_name=""):
pem = certificates.issue_certificate(ledger.ca_key, ledger.ca, implant_id, key, now, display_name)
certificate = certificates.load_certificate(pem)
return {
"serial": format(certificate.serial_number, "x"),
"cert_pem": pem,
"fingerprint": certificate.fingerprint(hashes.SHA256()).hex(),
"created_at": now.isoformat(),
"not_after": certificate.not_valid_after_utc.isoformat(),
}
def describe(row, ca):
certificate = certificates.load_certificate(row["cert_pem"])
result = certificates.describe(certificate, ca)
if row["revoked_at"]:
status = "revoked"
elif result["valid"]:
status = "active"
elif certificate.not_valid_after_utc < utc_now():
status = "expired"
else:
status = "invalid"
result.update(
status=status, valid=status == "active", fingerprint=row["fingerprint"],
revoked_at=row["revoked_at"],
cert_pem=row["cert_pem"],
)
return result
+112
View File
@@ -0,0 +1,112 @@
import json
from uuid import uuid4
from backend.app.common.errors import LedgerError
from backend.app.common.utils import utc_now, valid_text
from backend.app.infrastructure.security import envelopes, keys
from backend.app.infrastructure.security.certificates import load_certificate, valid
from backend.app.infrastructure.persistence import repositories
from backend.app.application import access, certificates
def implant_text(value, label):
if isinstance(value, str) and value.isascii():
value = value.strip()
if not valid_text(value, 1, 80):
raise LedgerError(400, f"{label} must contain 1-80 ASCII characters")
return value
def register(connection, ledger, owner_id, payload):
details = {
name: implant_text(payload.get(name), label)
for name, label in (("project_codename", "Project codename"), ("installed_by", "Organization code"))
}
display_name = implant_text(payload.get("display_name"), "Name")
model = implant_text(payload.get("model"), "Model")
key = certificates.public_key(payload)
implant_id = str(uuid4())
now = utc_now()
certificate = certificates.issue(ledger, implant_id, key, now, display_name)
details_bytes = json.dumps(details, separators=(",", ":")).encode("utf-8")
record = envelopes.encode_envelope(ledger.master_key, details_bytes, implant_id)
with connection:
repositories.create_implant(
connection, implant_id, owner_id, display_name, model, record, now.isoformat(),
)
repositories.create_certificate(connection, implant_id, certificate)
repositories.create_implant_telemetry(
connection, implant_id, payload["display_name"], payload["model"], payload["public_key_pem"],
details["project_codename"], details["installed_by"],
)
return {"id": implant_id, "cert_pem": certificate["cert_pem"]}
def list_owned(connection, owner_id):
return {"implants": [dict(row) for row in repositories.list_implants(connection, owner_id)]}
def telemetry(connection, owner_id):
return {"telemetry": [dict(row) for row in repositories.list_telemetry(connection, owner_id)]}
def passport(connection, ledger, implant_id, viewer_id):
row = access.implant(connection, implant_id, viewer_id)
result = {name: row[name] for name in ("id", "display_name", "model", "created_at")}
result["owner"] = row["owner"]
certificate = repositories.get_latest_certificate(connection, implant_id)
result["certificate"] = certificates.describe(certificate, ledger.ca)
result["cert_pem"] = certificate["cert_pem"]
result["user_id"] = row["user_id"]
return result
def check_certificate(connection, ledger, implant_id, owner_id, payload=None):
result = access.challenge(connection, ledger, implant_id, owner_id) if payload is None else access.read_details(connection, ledger, implant_id, owner_id, payload)
result["certificate"] = certificates.describe(result["certificate"], ledger.ca)
return result
def reissue(connection, ledger, implant_id, payload):
key, digest = certificates.signing_request(payload)
with connection:
connection.execute("BEGIN IMMEDIATE")
row = access.implant(connection, implant_id)
current = repositories.get_current_certificate(connection, implant_id)
if current is None:
raise LedgerError(409, "Implant has no valid certificate")
if payload.get("certificate_serial") != current["serial"]:
raise LedgerError(401, "Specify the current certificate serial number")
previous = load_certificate(current["cert_pem"])
if not valid(previous, ledger.ca):
raise LedgerError(409, "Implant has no valid certificate")
message = f"reissue:{implant_id}:{current['serial']}:{digest}"
signature = payload.get("signature")
if not isinstance(signature, str):
raise LedgerError(401, "Invalid signature for the current key")
current_key_authorized = keys.verify_implant_signature(previous.public_key(), signature, message)
if not current_key_authorized and not keys.verify_implant_signature(key, signature, message):
raise LedgerError(401, "Invalid signature for the current key")
now = utc_now()
details = json.loads(envelopes.decode_envelope(ledger.master_key, row["details"], implant_id))
certificate = current
if current_key_authorized:
issued = certificates.issue(ledger, implant_id, key, now, row["display_name"])
repositories.revoke_certificates(connection, implant_id, now.isoformat())
repositories.create_certificate(connection, implant_id, issued)
certificate = repositories.get_certificate(connection, implant_id, issued["serial"])
result = {name: row[name] for name in ("id", "display_name", "model", "created_at", "owner", "user_id")}
result.update(success=True, cert_pem=certificate["cert_pem"], **details)
result["certificate"] = certificates.describe(certificate, ledger.ca)
return result
def registry(connection, ledger):
results = {}
for row in repositories.list_registry(connection):
if row["id"] not in results:
results[row["id"]] = {name: row[name] for name in ("id", "display_name", "model", "created_at", "owner")}
results[row["id"]]["certificates"] = []
results[row["id"]]["certificates"].append(certificates.describe(row, ledger.ca))
return {"results": list(results.values())}
+85
View File
@@ -0,0 +1,85 @@
import os
import sqlite3
from contextlib import closing
from pathlib import Path
from types import SimpleNamespace
from Crypto.Random import get_random_bytes
from flask import Flask
from werkzeug.exceptions import HTTPException
from werkzeug.security import generate_password_hash
from backend.app.common.constants import LIFETIME
from backend.app.common.errors import LedgerError
from backend.app.common.utils import utc_now
from backend.app.infrastructure.security.certificates import load_or_create_ca
from backend.app.infrastructure.persistence.connection import close_database, database_path, initialize
from backend.app.api import views
from backend.app.api.session import load_identity
from backend.app.api.routes import auth, implants, registry
def load_key(state_dir, name, size=32):
path = state_dir / name
if path.is_file():
key = path.read_bytes()
if len(key) != size:
raise RuntimeError(f"Invalid state key: {name}")
return key
key = get_random_bytes(size)
with path.open("xb") as handle:
os.chmod(path, 0o600)
handle.write(key)
return key
def create_app(database_path_override=None):
db_path = Path(database_path_override or database_path())
initialize(db_path)
state_dir = db_path.parent / "state"
state_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
with closing(sqlite3.connect(db_path)) as connection:
has_implants = connection.execute("SELECT EXISTS(SELECT 1 FROM implants)").fetchone()[0]
required = ("master.key", "ca.key.pem", "ca.cert.pem")
if has_implants and any(not (state_dir / name).is_file() for name in required):
raise RuntimeError("Existing implants require the original master key and CA files; restore the state directory")
if (state_dir / "ca.key.pem").is_file() != (state_dir / "ca.cert.pem").is_file():
raise RuntimeError("Both CA key and certificate must be present")
master_key = load_key(state_dir, "master.key")
ca_key, ca = load_or_create_ca(state_dir, utc_now())
app = Flask(__name__, static_folder=None)
app.config.update(
DATABASE=str(db_path),
MAX_CONTENT_LENGTH=65_536,
)
app.extensions["ledger"] = SimpleNamespace(
ca_key=ca_key, ca=ca, master_key=master_key,
obsigil_key=load_key(state_dir, "obsigil.key", 64),
dummy_hash=generate_password_hash(get_random_bytes(32).hex(), method="scrypt"),
challenge_lifetime=LIFETIME,
static_root=Path(__file__).resolve().parents[3] / "frontend",
)
app.before_request(load_identity)
for blueprint in (auth.bp, implants.bp, registry.bp, views.bp):
app.register_blueprint(blueprint)
app.teardown_appcontext(close_database)
@app.errorhandler(LedgerError)
def service_error(error):
return {"error": str(error)}, error.status
@app.errorhandler(HTTPException)
def http_error(error):
response = error.get_response()
response.set_data(app.json.dumps({"error": error.description}))
response.mimetype = "application/json"
return response
@app.after_request
def protect_private_responses(response):
if response.is_json:
response.headers["Cache-Control"] = "no-store"
return response
return app
+10
View File
@@ -0,0 +1,10 @@
import re
from datetime import timedelta
LIFETIME = timedelta(seconds=60)
AUTH_LIFETIME = timedelta(hours=12)
AUTH_AUDIENCE = "chrome-ledger"
HEX_CHALLENGE = re.compile(r"[0-9a-fA-F]{64}")
+4
View File
@@ -0,0 +1,4 @@
class LedgerError(Exception):
def __init__(self, status, message):
super().__init__(message)
self.status = status
+17
View File
@@ -0,0 +1,17 @@
import unicodedata
from datetime import UTC, datetime
def utc_now():
return datetime.now(UTC)
def account_namespace(username):
return unicodedata.normalize("NFKC", username).casefold()
def valid_text(value, minimum, maximum):
if not isinstance(value, str):
return False
if len(value) < minimum or len(value) > maximum:
return False
return value.isascii()
@@ -0,0 +1,37 @@
import os
import sqlite3
from contextlib import closing
from pathlib import Path
from flask import current_app, g
from backend.app.infrastructure.persistence.schema import SCHEMA
def database_path():
default = Path(__file__).resolve().parents[4] / "ledger_data" / "ledger.sqlite3"
return Path(os.environ.get("LEDGER_DB", default)).resolve()
def initialize(path):
path = Path(path)
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
with closing(sqlite3.connect(path)) as connection:
connection.execute("PRAGMA auto_vacuum = INCREMENTAL")
connection.execute("PRAGMA journal_mode = WAL")
connection.execute("PRAGMA busy_timeout = 5000")
connection.execute("PRAGMA foreign_keys = ON")
connection.executescript(SCHEMA)
connection.execute("PRAGMA user_version = 9")
def database():
if "database" not in g:
connection = sqlite3.connect(current_app.config["DATABASE"], timeout=5)
connection.row_factory = sqlite3.Row
connection.execute("PRAGMA busy_timeout = 5000")
connection.execute("PRAGMA foreign_keys = ON")
g.database = connection
return g.database
def close_database(_error):
connection = g.pop("database", None)
if connection is not None:
connection.close()
@@ -0,0 +1,126 @@
from backend.app.common.constants import LIFETIME
def get_user_by_username(connection, username):
return connection.execute(
"SELECT id, username, namespace, password_hash FROM users WHERE username = ?", (username,),
).fetchone()
def create_auth_session(connection, tid, user_id, expires_at):
connection.execute(
"INSERT INTO auth_sessions (tid, user_id, expires_at) VALUES (?, ?, ?)",
(tid, user_id, expires_at),
)
def get_auth_user(connection, tid, user_id, expires_at, now):
return connection.execute(
"SELECT u.id, u.username FROM auth_sessions s JOIN users u ON u.id = s.user_id "
"WHERE s.tid = ? AND s.user_id = ? AND s.expires_at = ? AND s.expires_at > ?",
(tid, user_id, expires_at, now),
).fetchone()
def delete_auth_session(connection, tid):
connection.execute("DELETE FROM auth_sessions WHERE tid = ?", (tid,))
def create_user(connection, user_id, username, namespace, password_hash, created_at):
connection.execute(
"INSERT INTO users (id, username, namespace, password_hash, created_at) VALUES (?, ?, ?, ?, ?)",
(user_id, username, namespace, password_hash, created_at),
)
def create_implant(connection, implant_id, user_id, display_name, model, details, created_at):
connection.execute(
"INSERT INTO implants "
"(id, user_id, display_name, model, details, created_at) "
"VALUES (?, ?, ?, ?, ?, ?)",
(implant_id, user_id, display_name, model, details, created_at),
)
def create_implant_telemetry(connection, implant_id, display_name, model, public_key_pem, project_codename, installed_by):
connection.execute(
"INSERT INTO implant_telemetry "
"(implant_id, display_name, model, public_key_pem, project_codename, installed_by) VALUES (?, ?, ?, ?, ?, ?)",
(implant_id, display_name, model, public_key_pem, project_codename, installed_by),
)
def get_implant(connection, implant_id):
return connection.execute(
"SELECT i.*, u.username AS owner "
"FROM implants i JOIN users u ON u.id = i.user_id WHERE i.id = ?", (implant_id,),
).fetchone()
def list_implants(connection, owner_id):
return connection.execute(
"SELECT i.id, i.display_name, i.model, i.created_at, u.username AS owner "
"FROM implants i JOIN users u ON u.id = i.user_id "
"WHERE i.user_id = ? ORDER BY i.created_at DESC, i.id DESC", (owner_id,),
).fetchall()
def list_telemetry(connection, owner_id):
return connection.execute(
"SELECT t.display_name, t.model, t.public_key_pem, t.project_codename, t.installed_by "
"FROM implants i JOIN implant_telemetry t ON t.implant_id = i.id "
"WHERE i.user_id = ? ORDER BY i.created_at DESC, i.id DESC", (owner_id,),
).fetchall()
def list_registry(connection):
return connection.execute(
"SELECT i.id, i.display_name, i.model, i.created_at, u.username AS owner, "
"c.cert_pem, c.fingerprint, c.revoked_at "
"FROM implants i JOIN users u ON u.id = i.user_id "
"JOIN implant_certificates c ON c.implant_id = i.id "
"ORDER BY i.created_at DESC, i.id DESC, c.rowid DESC",
).fetchall()
def create_certificate(connection, implant_id, certificate):
connection.execute(
"INSERT INTO implant_certificates "
"(serial, implant_id, cert_pem, fingerprint, created_at, not_after) VALUES (?, ?, ?, ?, ?, ?)",
(certificate["serial"], implant_id, certificate["cert_pem"], certificate["fingerprint"],
certificate["created_at"], certificate["not_after"]),
)
def revoke_certificates(connection, implant_id, now):
connection.execute(
"UPDATE implant_certificates SET revoked_at = ? WHERE implant_id = ? AND revoked_at IS NULL",
(now, implant_id),
)
def get_current_certificate(connection, implant_id):
return connection.execute(
"SELECT * FROM implant_certificates WHERE implant_id = ? AND revoked_at IS NULL "
"ORDER BY rowid DESC LIMIT 1", (implant_id,),
).fetchone()
def get_latest_certificate(connection, implant_id):
return connection.execute(
"SELECT * FROM implant_certificates WHERE implant_id = ? ORDER BY rowid DESC LIMIT 1",
(implant_id,),
).fetchone()
def get_certificate(connection, implant_id, serial):
return connection.execute(
"SELECT * FROM implant_certificates WHERE implant_id = ? AND serial = ?",
(implant_id, serial),
).fetchone()
def create_implant_challenge(connection, nonce, implant_id, serial, now):
connection.execute(
"DELETE FROM implant_challenges WHERE created_at <= ?", ((now - LIFETIME).isoformat(),),
)
connection.execute(
"INSERT INTO implant_challenges (nonce, implant_id, certificate_serial, created_at) "
"VALUES (?, ?, ?, ?)", (nonce, implant_id, serial, now.isoformat()),
)
def consume_implant_challenge(connection, nonce, implant_id, certificate_serial, cutoff):
return connection.execute(
"DELETE FROM implant_challenges WHERE nonce = ? AND implant_id = ? AND certificate_serial = ? AND created_at > ?",
(nonce, implant_id, certificate_serial, cutoff),
).rowcount
@@ -0,0 +1,51 @@
SCHEMA = """
CREATE TABLE IF NOT EXISTS users (
id TEXT PRIMARY KEY,
username TEXT NOT NULL UNIQUE,
namespace TEXT NOT NULL DEFAULT '',
password_hash TEXT NOT NULL,
created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS users_created_at ON users (created_at);
CREATE TABLE IF NOT EXISTS auth_sessions (
tid TEXT PRIMARY KEY,
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
expires_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS auth_sessions_user_id ON auth_sessions (user_id);
CREATE INDEX IF NOT EXISTS auth_sessions_expires_at ON auth_sessions (expires_at);
CREATE TABLE IF NOT EXISTS implants (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL REFERENCES users(id),
display_name TEXT NOT NULL CHECK(length(trim(display_name)) BETWEEN 1 AND 80),
model TEXT NOT NULL DEFAULT '',
details TEXT NOT NULL,
created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS implants_user_id ON implants (user_id);
CREATE INDEX IF NOT EXISTS implants_created_at ON implants (created_at);
CREATE TABLE IF NOT EXISTS implant_telemetry (
implant_id TEXT PRIMARY KEY REFERENCES implants(id) ON DELETE CASCADE,
display_name TEXT NOT NULL,
model TEXT NOT NULL,
public_key_pem TEXT NOT NULL,
project_codename TEXT NOT NULL,
installed_by TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS implant_certificates (
serial TEXT PRIMARY KEY,
implant_id TEXT NOT NULL REFERENCES implants(id) ON DELETE CASCADE,
cert_pem TEXT NOT NULL,
fingerprint TEXT NOT NULL UNIQUE,
created_at TEXT NOT NULL,
not_after TEXT NOT NULL,
revoked_at TEXT
);
CREATE TABLE IF NOT EXISTS implant_challenges (
nonce TEXT PRIMARY KEY,
implant_id TEXT NOT NULL REFERENCES implants(id) ON DELETE CASCADE,
certificate_serial TEXT NOT NULL REFERENCES implant_certificates(serial),
created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS implant_challenges_created_at ON implant_challenges (created_at);
"""
@@ -0,0 +1,105 @@
import os
from datetime import timedelta
from cryptography import x509
from cryptography.exceptions import InvalidSignature, UnsupportedAlgorithm
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.x509.oid import NameOID
from backend.app.common.utils import utc_now
ORGANIZATION = "Chrome Ledger"
def certificate_builder(subject, issuer, public_key, now, days):
return (
x509.CertificateBuilder()
.subject_name(subject)
.issuer_name(issuer)
.public_key(public_key)
.serial_number(x509.random_serial_number())
.not_valid_before(now)
.not_valid_after(now + timedelta(days=days))
)
def create_ca(now):
key = ec.generate_private_key(ec.SECP256R1())
name = x509.Name([
x509.NameAttribute(NameOID.COMMON_NAME, "Chrome Ledger Root CA"),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, ORGANIZATION),
])
certificate = (
certificate_builder(name, name, key.public_key(), now, 365)
.add_extension(x509.BasicConstraints(ca=True, path_length=0), critical=True)
.sign(key, hashes.SHA256())
)
return key, certificate
def load_or_create_ca(state_dir, now):
key_path = state_dir / "ca.key.pem"
cert_path = state_dir / "ca.cert.pem"
if key_path.is_file() and cert_path.is_file():
key = serialization.load_pem_private_key(key_path.read_bytes(), password=None)
ca = x509.load_pem_x509_certificate(cert_path.read_bytes())
key_bytes = key.public_key().public_bytes(serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo)
ca_bytes = ca.public_key().public_bytes(serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo)
if key_bytes != ca_bytes:
raise ValueError("CA key does not match its certificate")
return key, ca
key, ca = create_ca(now)
key_path.write_bytes(
key.private_bytes(
serialization.Encoding.PEM,
serialization.PrivateFormat.PKCS8,
serialization.NoEncryption(),
)
)
os.chmod(key_path, 0o600)
cert_path.write_bytes(ca.public_bytes(serialization.Encoding.PEM))
return key, ca
def issue_certificate(ca_key, ca, implant_id, public_key, now, display_name=""):
common_name = display_name[:64]
subject = x509.Name([
x509.NameAttribute(NameOID.COMMON_NAME, common_name),
x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, implant_id),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, ORGANIZATION),
])
certificate = (
certificate_builder(subject, ca.subject, public_key, now, 30)
.add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True)
.add_extension(x509.SubjectAlternativeName([
x509.UniformResourceIdentifier(f"urn:chrome-ledger:implant:{implant_id}"),
]), critical=False)
.sign(ca_key, hashes.SHA256())
)
return certificate.public_bytes(serialization.Encoding.PEM).decode("ascii")
def load_certificate(pem):
return x509.load_pem_x509_certificate(pem.encode("ascii"))
def subject_implant_id(certificate):
attributes = certificate.subject.get_attributes_for_oid(NameOID.ORGANIZATIONAL_UNIT_NAME)
return attributes[0].value if len(attributes) == 1 else ""
def valid(certificate, ca):
now = utc_now()
if not (certificate.not_valid_before_utc <= now <= certificate.not_valid_after_utc
and ca.not_valid_before_utc <= now <= ca.not_valid_after_utc):
return False
try:
certificate.verify_directly_issued_by(ca)
except (InvalidSignature, ValueError, UnsupportedAlgorithm):
return False
return True
def describe(certificate, ca):
return {
"subject": certificate.subject.rfc4514_string(),
"issuer": certificate.issuer.rfc4514_string(),
"serial": format(certificate.serial_number, "x"),
"not_before": certificate.not_valid_before_utc.isoformat(),
"not_after": certificate.not_valid_after_utc.isoformat(),
"valid": valid(certificate, ca),
}
@@ -0,0 +1,34 @@
import base64
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
NONCE_SIZE = 16
TAG_SIZE = 16
def seal(key, plaintext, associated_data):
cipher = AES.new(key, AES.MODE_GCM, nonce=get_random_bytes(NONCE_SIZE))
cipher.update(associated_data)
ciphertext, tag = cipher.encrypt_and_digest(plaintext)
return cipher.nonce + ciphertext + tag
def unseal(key, envelope, associated_data):
cipher = AES.new(key, AES.MODE_GCM, nonce=envelope[:NONCE_SIZE])
cipher.update(associated_data)
plaintext = cipher.decrypt_and_verify(
envelope[NONCE_SIZE:-TAG_SIZE],
envelope[-TAG_SIZE:],
)
return plaintext
def encode_envelope(key, secret, implant_id):
associated_data = implant_id.encode("ascii")
envelope = seal(key, secret, associated_data)
return base64.b64encode(envelope).decode("ascii")
def decode_envelope(key, envelope, implant_id):
associated_data = implant_id.encode("ascii")
decoded = base64.b64decode(envelope, validate=True)
return unseal(key, decoded, associated_data).decode("utf-8")
+34
View File
@@ -0,0 +1,34 @@
import base64
from cryptography.exceptions import InvalidSignature, UnsupportedAlgorithm
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec, padding, rsa
class UnsupportedKeyType(ValueError):
pass
def parse_public_key(pem):
if not isinstance(pem, str):
raise ValueError("PEM must be a string")
try:
key = serialization.load_pem_public_key(pem.encode("utf-8"))
except (ValueError, UnsupportedAlgorithm):
raise ValueError("Invalid PEM public key") from None
if isinstance(key, rsa.RSAPublicKey) and key.key_size >= 2048:
return key
if isinstance(key, ec.EllipticCurvePublicKey) and isinstance(key.curve, ec.SECP256R1):
return key
raise UnsupportedKeyType("Unsupported public key type")
def verify_implant_signature(public_key, signature, nonce):
try:
signed = base64.b64decode(signature, validate=True)
if isinstance(public_key, ec.EllipticCurvePublicKey):
public_key.verify(signed, nonce.encode("ascii"), ec.ECDSA(hashes.SHA256()))
else:
public_key.verify(signed, nonce.encode("ascii"), padding.PKCS1v15(), hashes.SHA256())
except (InvalidSignature, ValueError):
return False
return True
+6
View File
@@ -0,0 +1,6 @@
Flask==3.1.3
Werkzeug==3.1.9
gunicorn==27.0.1
pycryptodome==4.5.0
cryptography==50.0.2
obsigil==1.0.0