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:
commit
13f936bee9
1222 files changed
+21280
No files matched your search
@@ -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")
|
||||
@@ -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
|
||||
Reference in new issue
Block a user