commit b37c30b413a70b69fae6a5d5b9bbd65e03e699c9 Author: mnovak Date: Tue Nov 17 11:12:12 2026 +0100 [docs] domi-pki: CLAUDE.md, design (docs/01), README, MPL-2.0 licence, pre-commit hook diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..6313b56 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +* text=auto eol=lf diff --git a/.githooks/pre-commit b/.githooks/pre-commit new file mode 100644 index 0000000..ca40a21 --- /dev/null +++ b/.githooks/pre-commit @@ -0,0 +1,175 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: MPL-2.0 +# +# Pre-commit hook (shared with Ianitor). Rejects staged files that must never be in git: +# - binaries: any NUL byte anywhere in the staged blob (git attributes do not matter) +# - private keys: PEM/PKCS#8/OpenSSH/PGP blocks, SSH2 (RFC 4716) keys, PuTTY .ppk, +# age secret keys, JWK private keys (an object with "kty" RSA/EC/OKP and "d"), +# WireGuard private keys (wg-quick `PrivateKey =` or YAML `private_key:`), and +# key-store file names +# - files over 5 MB (5,000,000 bytes, as CLAUDE.md says) +# - build output and dependencies: target/, node_modules/, dist/, .svelte-kit/ anywhere; +# build/ at the repository root, in apps//, or next to a package.json +# Name checks are case-insensitive. Paths are read NUL-separated, so quotes, tabs, +# backslashes or newlines in file names cannot slip past. A staged file that cannot be read, +# or any git command that fails, blocks the commit. +# +# Contents are checked in a few batch passes over the index (one `git cat-file`, two +# `git grep`), not with processes per file. +# +# Enable once per clone: git config core.hooksPath .githooks +# Test it: bash .githooks/test-pre-commit.sh + +if [ -z "${BASH_VERSINFO:-}" ] || [ "${BASH_VERSINFO[0]}" -lt 4 ]; then + echo "pre-commit: needs bash 4 or newer (this is ${BASH_VERSION:-not bash}); commit blocked." >&2 + echo "pre-commit: use Git Bash on Windows, any Linux, or a newer bash on macOS." >&2 + exit 1 +fi + +set -u +LIMIT=5000000 + +# Patterns are written so that this file does not match them itself. They are matched +# case-insensitively. +KEY_PATTERNS=( + '-----BEGIN [A-Z0-9 ]*PRIVATE KEY( BLOCK)?-----' + '---- BEGIN SSH2 ENCRYPTED PRIVATE KEY[ ]----' + '---- BEGIN SSH2 PRIVATE KEY[ ]----' + 'PuTTY-User-Key-File-[0-9]+:' + 'AGE-SECRET-KEY-[1][0-9A-Z]+' + '^[[:space:]]*(-[[:space:]]*)?["'\'']?private_?key["'\'']?[[:space:]]*[:=][[:space:]]*["'\'']?[A-Za-z0-9+/]{42,43}=?["'\'']?[[:space:]]*,?[[:space:]]*$' +) +# One flat JSON object (JWK members are flat) holding a private-key parameter set. +JWK_OBJECT='\{[^{}]*\}' +JWK_KTY='"kt[y]"[[:space:]]*:[[:space:]]*"(RSA|EC|OKP)"' +JWK_D='"[d]"[[:space:]]*:[[:space:]]*"' + +failed=0 +reject() { + # %q keeps odd characters in names visible and harmless. + printf 'pre-commit: rejected %q: %s\n' "$1" "$2" >&2 + failed=1 +} +die() { + echo "pre-commit: $1; commit blocked." >&2 + exit 1 +} + +tmp=$(mktemp -d 2>/dev/null || { d="${TMPDIR:-/tmp}/ianitor-pre-commit.$$"; mkdir -p "$d" && echo "$d"; }) || + die "cannot create a temporary directory" +trap 'rm -rf "$tmp"' EXIT + +git diff --cached --raw -z --no-abbrev --no-renames --diff-filter=ACMT >"$tmp/list" || + die "cannot list the staged files" +git ls-files -z -- ':(glob)**/package.json' >"$tmp/packages" || + die "cannot list package.json files" + +declare -A staged=() pkgdir=() +paths=() shas=() + +while IFS= read -r -d '' p; do + d=${p%package.json} + d=${d%/} + # The root package.json needs no entry: build/ at the root is always output. + [ -n "$d" ] && pkgdir[${d,,}]=1 +done <"$tmp/packages" + +# build/ is output only at the root, in apps// or beside a package.json. +is_build_output() { + local lower=$1 prefix= + [[ $lower == build/* || $lower =~ ^apps/[^/]+/build/ ]] && return 0 + local rest=$lower part + while [[ $rest == */* ]]; do + part=${rest%%/*} + rest=${rest#*/} + if [[ $part == build && -n $prefix && -n ${pkgdir[${prefix%/}]+x} ]]; then + return 0 + fi + prefix+="$part/" + done + return 1 +} + +# --raw -z gives ": " NUL "" NUL. +while IFS= read -r -d '' meta && IFS= read -r -d '' path; do + read -r -a f <<<"${meta#:}" + mode=${f[1]} sha=${f[3]} + lower=${path,,} + + case "/$lower" in + */target/*|*/node_modules/*|*/dist/*|*/.svelte-kit/*) + reject "$path" "build output or dependency directory" ;; + esac + if is_build_output "$lower"; then + reject "$path" "build output directory" + fi + + base=${lower##*/} + case "$base" in + *.pub) ;; + *.key|*.p12|*.pfx|*.jks|*.keystore|*.ppk|id_rsa|id_dsa|id_ecdsa|id_ed25519|id_rsa.*|id_dsa.*|id_ecdsa.*|id_ed25519.*) + reject "$path" "private key file name" ;; + esac + + # Submodule entries have no blob to inspect. + [ "$mode" = 160000 ] && continue + staged[$path]=$sha + paths+=("$path") + shas+=("$sha") +done <"$tmp/list" + +if [ "${#paths[@]}" -gt 0 ]; then + # Sizes: one batch for every blob, in order. + printf '%s\n' "${shas[@]}" | git cat-file --batch-check='%(objectname) %(objecttype) %(objectsize)' >"$tmp/sizes" || + die "cannot read the staged blobs" + i=0 + while read -r _ type size; do + p=${paths[$i]} + if [ "$type" != blob ] || ! [[ $size =~ ^[0-9]+$ ]]; then + reject "$p" "the staged content cannot be read" + elif (( size > LIMIT )); then + reject "$p" "$size bytes is over the 5 MB limit (5,000,000 bytes)" + fi + i=$((i + 1)) + done <"$tmp/sizes" + [ "$i" -eq "${#paths[@]}" ] || die "cannot read the size of every staged blob" + + # Contents: git grep over the index, every file read as text (-a), names NUL-separated, + # then kept only when staged. Exit 1 means no match; anything above blocks the commit. + search() { + local out=$1 rc + shift + git -c grep.fullName=true -c color.grep=never grep --cached --no-recurse-submodules \ + -a -l -z "$@" >"$out" + rc=$? + [ "$rc" -le 1 ] || die "git grep failed (exit $rc)" + } + + search "$tmp/nul" -P '\x00' + while IFS= read -r -d '' p; do + [ -n "${staged[$p]+x}" ] && reject "$p" "binary file (contains NUL bytes)" + done <"$tmp/nul" + + args=() + for pattern in "${KEY_PATTERNS[@]}"; do args+=(-e "$pattern"); done + search "$tmp/keys" -i -E "${args[@]}" + while IFS= read -r -d '' p; do + [ -n "${staged[$p]+x}" ] && reject "$p" "contains a private key" + done <"$tmp/keys" + + # JWK members may span lines, so candidates are flattened and split into objects. + search "$tmp/jwk" -F -e '"kt''y"' + while IFS= read -r -d '' p; do + [ -n "${staged[$p]+x}" ] || continue + if git cat-file blob "${staged[$p]}" | tr '\r\n\t' ' ' | grep -a -o -E "$JWK_OBJECT" | + grep -a -E "$JWK_KTY" | grep -a -q -E "$JWK_D"; then + reject "$p" "contains a JWK private key" + fi + done <"$tmp/jwk" +fi + +if [ "$failed" -ne 0 ]; then + echo 'pre-commit: commit blocked. Unstage the files above (git rm --cached ).' >&2 + exit 1 +fi +exit 0 diff --git a/.githooks/test-pre-commit.sh b/.githooks/test-pre-commit.sh new file mode 100644 index 0000000..771e14a --- /dev/null +++ b/.githooks/test-pre-commit.sh @@ -0,0 +1,255 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: MPL-2.0 +# +# Self-test for .githooks/pre-commit. Creates a throw-away repository, points it at the +# hook and checks that every forbidden case is rejected and normal files are accepted. +# Includes every bypass QC found (odd file names, attributes, NULs late in a file, 5 MB +# boundary, other key formats). Usage: bash .githooks/test-pre-commit.sh (Git Bash or Linux) + +set -u +HOOKS=$(cd "$(dirname "$0")" && pwd) +WORK=$(mktemp -d 2>/dev/null || mktemp -d -t ianitor-hook) +trap 'rm -rf "$WORK"' EXIT INT TERM + +cd "$WORK" || exit 2 +git init -q . +git config user.name hook-test +git config user.email hook-test@invalid +git config core.hooksPath "$HOOKS" +git config core.autocrlf false +# Allow index entries Windows cannot check out ("quotes", tabs, backslashes) so the hook +# itself is what rejects them. +git config core.protectNTFS false +git commit -q --allow-empty -m base --no-gpg-sign + +pass=0 +fail=0 + +commit_and_check() { + local want=$1 what=$2 got + if git commit -q -m "$what" --no-gpg-sign >/dev/null 2>"$WORK/.err"; then + got=accept + elif grep -q 'pre-commit: rejected' "$WORK/.err"; then + got=reject + else + got="error ($(head -c 200 "$WORK/.err"))" # failed, but not because of the hook + fi + if [ "$got" = "$want" ]; then + pass=$((pass + 1)); printf 'ok %-7s %s\n' "$want" "$what" + else + fail=$((fail + 1)); printf 'FAIL wanted %s, got %s: %s\n' "$want" "$got" "$what"; cat "$WORK/.err" + fi + git reset -q --hard HEAD >/dev/null 2>&1 + git clean -q -fdx -e .err >/dev/null 2>&1 +} + +# expect (file must exist in the work tree) +expect() { + git add -f -- "$3" + commit_and_check "$1" "$2" +} + +# expect_staged +# Stages content under a path that may be impossible to create on this file system +# (quotes, tabs or backslashes in names on Windows). +expect_staged() { + local sha + sha=$(git hash-object -w -- "$4") + if ! git update-index --add --cacheinfo "100644,$sha,$3"; then + fail=$((fail + 1)); printf 'FAIL could not stage the test path: %s +' "$2" + return + fi + commit_and_check "$1" "$2" +} + +B='-----BEGIN' +E='-----END' +# An absolute path next to $WORK (not "$WORK/..", which no longer resolves once $WORK is gone), +# removed first. +SRC="$(dirname "$WORK")/ianitor-hook-src.$$" +mkdir -p "$SRC" || exit 2 +trap 'rm -rf "$SRC" "$WORK"' EXIT INT TERM +printf '%s RSA PRIVATE KEY-----\nMIIBOgIBAAJBAK\n%s RSA PRIVATE KEY-----\n' "$B" "$E" > "$SRC/pem" +head -c 6291456 /dev/zero | tr '\000' 'a' > "$SRC/six-mb" + +printf 'hello\n' > readme.txt +expect accept "plain text file" readme.txt + +printf 'fn main() {}\n' > main.rs +expect accept "source file" main.rs + +printf '\000\001\002\003binary\000' > blob.bin +expect reject "binary file" blob.bin + +{ head -c 10000 /dev/zero | tr '\000' 'a'; printf '\000tail'; } > late-nul.txt +expect reject "NUL byte after the first 8000 bytes" late-nul.txt + +printf '*.dat diff\n' > .gitattributes +expect accept ".gitattributes marking *.dat as text" .gitattributes +printf 'abc\000def' > forced.dat +expect reject "binary file that .gitattributes calls text" forced.dat + +cp "$SRC/pem" notes.txt +expect reject "PEM RSA private key in a .txt file" notes.txt + +printf '%s PRIVATE KEY-----\nMIGHAgEAMBMG\n%s PRIVATE KEY-----\n' "$B" "$E" > pkcs8.pem +expect reject "PKCS#8 private key" pkcs8.pem + +printf '%s ENCRYPTED PRIVATE KEY-----\nMIIFHDBOBgkq\n%s ENCRYPTED PRIVATE KEY-----\n' "$B" "$E" > enc.pem +expect reject "encrypted PKCS#8 private key" enc.pem + +printf '%s EC PRIVATE KEY-----\nMHcCAQEEI\n%s EC PRIVATE KEY-----\n' "$B" "$E" > ec.txt +expect reject "EC private key" ec.txt + +printf '%s OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjEAAAAA\n%s OPENSSH PRIVATE KEY-----\n' "$B" "$E" > deploy +expect reject "OpenSSH private key" deploy + +printf -- '---- BEGIN SSH2 ENCRYPTED PRIVATE %s ----\nP2/56wAAA\n' KEY > ssh2.txt +expect reject "SSH2 (RFC 4716) encrypted private key" ssh2.txt + +printf 'PuTTY-User-Key-File-%s: ssh-ed25519\nEncryption: none\n' 3 > putty.txt +expect reject "PuTTY private key content" putty.txt + +printf 'not really a key\n' > me.ppk +expect reject "*.ppk file name" me.ppk + +printf '# created: 2026\nage-secret-key-%s\n' 1qyz8xrfk3w6j9p2m4n5l7kxqzj5s8tvh3r2w6y9 > lower.txt +expect reject "age secret key in lower case" lower.txt + +printf '# created: 2026\nAGE-SECRET-KEY-%s\n' 1QYZ8XRFK3W6J9P2M4N5L7KXQZJ5S8TVH3R2W6Y9 > identity.txt +expect reject "age secret key" identity.txt + +printf '{"k%s":"EC","crv":"P-256","x":"f83O","y":"x_FE","d":"jpsQ"}\n' ty > key.json +expect reject "JWK private key" key.json + +printf '{"k%s":"EC","crv":"P-256","x":"f83O","y":"x_FE"}\n' ty > pub.json +expect accept "JWK public key" pub.json + +printf '{\n "k%s"\n : "RSA",\n "n": "0vx7",\n "e": "AQAB",\n "d"\n :\n "X4cT"\n}\n' ty > rsa.json +expect reject "JWK private key across lines, newline before the colon" rsa.json + +printf '{"keys":[{"k%s":"OKP","crv":"Ed25519","x":"11qY","d":"nWGx"}]}\n' ty > jwks.json +expect reject "OKP private key inside a JWKS" jwks.json + +printf '{"jwk":{"k%s":"EC","x":"f83O","y":"x_FE"},"meta":{"d":"2026-11-07"}}\n' ty > mixed.json +expect accept "JWK public key with an unrelated \"d\" in another object" mixed.json + +printf '{"k%s":"oct","k":"GawgguFy","d":"not a private-key parameter"}\n' ty > oct.json +expect accept "\"d\" with kty oct is not an RSA/EC/OKP private key" oct.json + +printf '[Interface]\nPrivate%s = %s\nAddress = 10.0.0.2/32\n' Key yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk= > wg0.conf +expect reject "WireGuard private key" wg0.conf + +printf 'wireguard:\n interface:\n private_%s: yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=\n' key > wg.yaml +expect reject "WireGuard private_key in YAML" wg.yaml + +printf 'peers:\n - private_%s: "yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk="\n' key > wg2.yml +expect reject "WireGuard private_key in a YAML list, quoted" wg2.yml + +printf 'private_%s_file: /run/secrets/wg\n' key > wg3.yaml +expect accept "WireGuard private_key_file path (no key)" wg3.yaml + +printf '*.txt binary\n' > .gitattributes && cp "$SRC/pem" attr.txt && git add .gitattributes +expect reject "PEM key in a file .gitattributes marks binary" attr.txt + +printf 'not really a key\n' > server.key +expect reject "*.key file name" server.key + +printf 'not really a key\n' > SERVER.KEY +expect reject "*.KEY file name in upper case" SERVER.KEY + +printf 'not really a key\n' > id_ed25519 +expect reject "id_ed25519 file name" id_ed25519 + +printf 'ssh-ed25519 AAAAC3Nza test\n' > id_ed25519.pub +expect accept "public key id_ed25519.pub" id_ed25519.pub + +printf '%s CERTIFICATE-----\nMIIBszCCAVmg\n%s CERTIFICATE-----\n' "$B" "$E" > cert.pem +expect accept "certificate (public) PEM" cert.pem + +cp "$SRC/six-mb" big.txt +expect reject "6 MB text file" big.txt + +head -c 5000001 /dev/zero | tr '\000' 'a' > over.txt +expect reject "5,000,001 bytes" over.txt + +head -c 5242880 /dev/zero | tr '\000' 'a' > mib.txt +expect reject "5 MiB (5,242,880 bytes)" mib.txt + +head -c 5000000 /dev/zero | tr '\000' 'a' > exact.txt +expect accept "exactly 5,000,000 bytes" exact.txt + +mkdir -p crates/x/target/debug && printf 'x\n' > crates/x/target/debug/out.txt +expect reject "file under target/" crates/x/target/debug/out.txt + +mkdir -p TARGET && printf 'x\n' > TARGET/out.txt +expect reject "file under TARGET/ (upper case)" TARGET/out.txt + +mkdir -p apps/web/node_modules/pkg && printf 'x\n' > apps/web/node_modules/pkg/index.js +expect reject "file under node_modules/" apps/web/node_modules/pkg/index.js + +mkdir -p apps/web/dist && printf 'x\n' > apps/web/dist/index.html +expect reject "file under dist/" apps/web/dist/index.html + +mkdir -p apps/web/build && printf 'x\n' > apps/web/build/index.html +expect reject "file under apps//build/" apps/web/build/index.html + +mkdir -p build && printf 'x\n' > build/out.js +expect reject "file under build/ at the root" build/out.js + +mkdir -p crates/x/src/build && printf 'pub mod x;\n' > crates/x/src/build/mod.rs +expect accept "source module named build (crates/x/src/build/mod.rs)" crates/x/src/build/mod.rs + +mkdir -p apps/web/src/build && printf 'x\n' > apps/web/src/build/x.ts +expect accept "apps/web/src/build/ is not output" apps/web/src/build/x.ts + +mkdir -p packages/ui/build && printf '{}\n' > packages/ui/package.json && printf 'x\n' > packages/ui/build/ui.js +git add packages/ui/package.json +expect reject "build/ next to a package.json" packages/ui/build/ui.js + +mkdir -p docs/build && printf 'x\n' > docs/build/notes.md +expect accept "build/ with no package.json beside it" docs/build/notes.md + +mkdir -p apps/web/.svelte-kit && printf 'x\n' > apps/web/.svelte-kit/env.js +expect reject "file under .svelte-kit/" apps/web/.svelte-kit/env.js + +# Names git would C-quote: only reachable through the index on Windows. +expect_staged reject "PEM key in a file named with a double quote" 'a"b.txt' "$SRC/pem" +expect_staged reject "PEM key in a file named with a tab" "$(printf 'tab\tx.txt')" "$SRC/pem" +expect_staged reject "6 MB file named with a backslash" 'big\file.txt' "$SRC/six-mb" +expect_staged reject "*.key named with a backslash" 'srv\x.key' "$SRC/pem" +expect_staged reject "PEM key in a file named with a newline" "$(printf 'new\nline.txt')" "$SRC/pem" +printf 'fine\n' > "$SRC/fine" +expect_staged accept "harmless file named with a double quote" 'say"hi".txt' "$SRC/fine" + +# Bash 3 or a POSIX sh: the hook refuses with a clear message. Only testable where sh is +# not bash (dash on Debian); Git Bash's sh is bash. +if [ -z "$(sh -c 'echo "${BASH_VERSION:-}"')" ]; then + printf 'x\n' > shtest.txt && git add shtest.txt + if sh "$HOOKS/pre-commit" 2>"$WORK/.err"; then + fail=$((fail + 1)); echo "FAIL the hook ran under a shell that is not bash 4" + elif grep -q 'needs bash 4' "$WORK/.err"; then + pass=$((pass + 1)); echo "ok reject run by sh (not bash): clear message" + else + fail=$((fail + 1)); echo "FAIL no clear message under sh:"; cat "$WORK/.err" + fi + git reset -q --hard HEAD; git clean -q -fdx -e .err +else + echo "skip sh is bash here; the bash-4 check is exercised where sh is dash" +fi + +# Speed: 300 ordinary files in one commit. +mkdir -p many +for n in $(seq 1 300); do printf 'line %d\n' "$n" > "many/f$n.txt"; done +git add many +start=$(date +%s%N) +commit_and_check accept "300 ordinary files in one commit" +ms=$(( ($(date +%s%N) - start) / 1000000 )) +printf ' (300 files: %d ms)\n' "$ms" +if [ "$ms" -gt 10000 ]; then + fail=$((fail + 1)); echo "FAIL 300 files took over 10 s" +fi + +printf '\nhook: %d passed, %d failed\n' "$pass" "$fail" +[ "$fail" -eq 0 ] diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..964596b --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +target/ +*.key +*.p12 +*.pfx +.env +.env.* +*.log +.idea/ +.vscode/ diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..92e0f8d --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,35 @@ +# CLAUDE.md — domi-pki + +The Domi CA as one pure Rust crate: the root's certificate, intermediates, server, device and agent certificates, and +the checks on them. Moved out of Ianitor core (T3a of Fabrica's `docs/32_coherence.md`) so Fabrica can issue Legatus +agent certificates without Ianitor. MPL-2.0. Read docs/01_domi_pki.md first. + +## Layout +src/signer.rs the `Signer` trait (the root lives in Custos and signs through it) and the local `KeyPair` +src/ca.rs root certificate, intermediate CSR and signing, `Intermediate`, issuing server/device/agent leaves +src/inspect.rs reading certificates and CSRs: `CertInfo`, `issued_by`, `intermediate_problem`, match codes +src/verify.rs chain checks (rustls-webpki) and `verify_agent`: who an agent certificate names, or why it is refused +src/testing.rs certificates the CA itself never makes, for tests (doc-hidden) +tests/ chains, expiry, wrong issuer, foreign agents, hostile input + +## Commands +cargo test # quote the test count; an exit code alone is not green +cargo clippy --all-targets -- -D warnings +On Mark's PC: CARGO_HOME=F:\C-Drive-Migration\future-caches\cargo, CARGO_TARGET_DIR=D:\cargo-target\domi-pki. +One-time per clone: git config core.hooksPath .githooks (self-test: bash .githooks/test-pre-commit.sh) + +## Rules +- Pure: no file, network or clock access. The caller passes `now` (unix seconds) and does every read and write. + Randomness (serials, keys) comes from ring's `SystemRandom`. +- The root key is never in this crate's hands in production: anything the root signs goes through `Signer`, which + Custos implements after a match-code approval. `create_root_local` is for tests and the offline machine only. +- Certificates, CSRs and chains are hostile input: typed `Result`, no `unwrap()`/`expect()`/`panic!` outside tests + (clippy denies them), never a panic on garbage. +- Tests first for anything that issues or checks a certificate. +- Public API changes are semver: a breaking change is a major version. Ianitor and Fabrica pin a tag. +- Commits: `[pki] : `. No AI attribution, no trailers, ever. +- Never in git: target/, binaries, private keys, files over 5 MB (the pre-commit hook enforces it). +- $GITEA_TOKEN is never echoed or written anywhere. +- Workflow: branch → Gitea PR via API → short adversarial self-review in the PR body → merge --no-ff → push → + `git rev-parse HEAD origin/main`. +- Disks on Mark's PC: nothing on C:. Build output on D:\cargo-target. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d0a1fa1 --- /dev/null +++ b/LICENSE @@ -0,0 +1,373 @@ +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at https://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/README.md b/README.md new file mode 100644 index 0000000..004ebfc --- /dev/null +++ b/README.md @@ -0,0 +1,17 @@ +# domi-pki + +The Domi CA as a pure Rust crate: the root's certificate, intermediates, server, device and agent certificates, and +the checks on them. Used by [Ianitor](https://gitea.marek-novak.cz/mnovak/Ianitor) and by Fabrica for its +[Legatus](https://gitea.marek-novak.cz/mnovak/Legatus) agents. + +- **Pure:** no files, no network, no clock. You pass `now` and do the I/O. +- **The root never touches this crate:** anything the root signs goes through the `Signer` trait, which Custos + implements behind an approval. +- **Hostile input in, typed errors out:** certificates, chains and CSRs never panic the crate. + +```toml +[dependencies] +domi-pki = { git = "https://gitea.marek-novak.cz/mnovak/domi-pki", tag = "v1.0.0" } +``` + +Design and rules: [docs/01_domi_pki.md](docs/01_domi_pki.md). Licence: MPL-2.0. diff --git a/docs/01_domi_pki.md b/docs/01_domi_pki.md new file mode 100644 index 0000000..c139ade --- /dev/null +++ b/docs/01_domi_pki.md @@ -0,0 +1,99 @@ +# 01 · domi-pki: the Domi CA as a shared crate + +Phase T3a of the coherence roadmap (Fabrica `docs/32_coherence.md`, 2.3): *"The Domi CA code moved out of Ianitor +core into a shared public crate, so Fabrica can issue agent certificates even without Ianitor. Root key stays in +Custos."* + +## Why + +Until now the Domi CA lived in `ianitor-core::pki`. Fabrica needs the same CA for Legatus, its agent: every agent gets +a client certificate for mTLS, and Fabrica must issue and check those whether or not Ianitor is installed (roadmap +decision 4: Ianitor is optional). Two copies of CA code would drift; one crate, pinned by tag, does not. + +## The hierarchy + +```text +Domi PKI Root 10 years, pathLen 1 key in Custos, signs through `Signer` + ├ Ianitor Domi Intermediate 1 year, pathLen 0 Ianitor control (key encrypted at rest) + │ ├ 90 days, serverAuth tls = "domi" hosts + │ └ 1 year, clientAuth mTLS devices + └ Fabrica Domi Agents Intermediate 1 year, pathLen 0 the Fabrica server + ├ 90 days, serverAuth the agents' endpoint + └ 30 days, clientAuth one Legatus agent, URI urn:domi:agent:: +``` + +Every intermediate is signed from a CSR of which only the public key and the CN are used; the CN must start with the +name of the intermediate being made (`IANITOR_INTERMEDIATE_CN` or `AGENTS_INTERMEDIATE_CN`). No leaf outlives its +issuer. Keys are ECDSA P-256 (Ed25519 is accepted from a `Signer` for the root, not for leaves). + +### Agent certificates (new) + +- The agent makes its own key and sends a CSR; the key never leaves the agent. `issue_agent` uses only the CSR's + public key (ECDSA P-256 only) and checks the CSR's own signature (proof the agent holds the key). +- Subject: CN = agent id, O = Fabrica Domi, OU = Domi agents. SAN: exactly one URI `urn:domi:agent::`. + Ids are 1–40 of `a-z 0-9 -`, not starting or ending with `-`. +- clientAuth only, digitalSignature only. 30 days; Legatus renews when 10 are left (`AGENT_RENEW_DAYS`), over its + existing mTLS connection. A short life bounds how long a stolen agent key is useful even before revocation. + +### Why agents get their own intermediate + +Ianitor device certificates are also clientAuth certificates under the same root. If agents shared Ianitor's +intermediate, a phone's device certificate would chain to the root for client auth just as an agent's does. +`verify_agent` therefore requires the chain to go through an intermediate named `AGENTS_INTERMEDIATE_CN`, and the +leaf to carry the agent URI. A device certificate, a server certificate, an agent certificate of another root, or one +whose chain skips the agents intermediate is *foreign* and refused. + +## The signer interface (the root stays in Custos) + +```rust +pub trait Signer { + /// SubjectPublicKeyInfo DER of the signing key (ECDSA P-256 or Ed25519). + fn spki_der(&self) -> Vec; + /// Sign `msg`: ECDSA P-256 with SHA-256 (ASN.1 DER signature) or Ed25519. + fn sign(&self, msg: &[u8]) -> Result, SignerError>; +} +``` + +`create_root(&dyn Signer, now)` builds the root's self-signed certificate and `sign_intermediate(root_pem, +&dyn Signer, csr, prefix, now)` signs an intermediate: in both, the crate builds the to-be-signed bytes and asks the +signer once. Custos implements `Signer` behind a match-code approval (its signing service, T1); the crate never sees +the root's private key. `KeyPair` (a local P-256 key) also implements `Signer`: it is what intermediates use, and what +tests and the offline machine use for a root (`create_root_local`). + +The signer is synchronous: an adapter that waits for an approval blocks the calling thread. That is fine for the rare +root operations (a root once, an intermediate a year); agents are issued by the intermediate, not the root. + +## Checking certificates + +- `verify_chain(chain_der, root_der, now, Usage)`: rustls-webpki path building and signature checks plus + validity at `now`, for server or client use. Errors are typed: `Expired`, `NotYetValid`, `UnknownIssuer`, + `BadSignature`, `WrongUsage`, `NotCa`, `BadCertificate`. +- `verify_agent(chain_der, root_der, now)`: `verify_chain` for client use, then the Domi rules above; returns the + `AgentIdentity` (team, agent, serial, fingerprint, notAfter). What it does *not* know: whether the agent is still + registered and whether this serial is its current one. That registry is the caller's (Legatus protocol, Fabrica). +- `inspect`, `issued_by`, `intermediate_problem(cert, root, prefix, now)`: what Ianitor already used. + +## Moved from Ianitor, unchanged + +Profiles, lifetimes, the CSR rules, `match_code`, `INTERMEDIATE_OPENSSL_EXT` and `openssl_sign_command`, the +placeholder leaf for Caddy's allow list, the test helpers. Ianitor keeps its encrypted-key format (`IANITOR ENCRYPTED +PRIVATE KEY`): that is Ianitor's storage, not the CA. `ianitor-core::pki` becomes a thin layer over this crate with +the same public API and the same error messages, so Ianitor's behaviour and tests do not change. + +## Tests (first) + +- chains: server and device and agent chains validate to the root; a leaf cannot sign; pathLen 0 holds; +- expiry: expired and not-yet-valid leaves and intermediates are refused; an expired issuer issues nothing; +- wrong issuer: a leaf of another root with identical names, a chain missing its intermediate, a self-signed leaf; +- agents: issue from a CSR, the CSR's wishes ignored, a tampered CSR refused, a non-P-256 key refused, a device or + server certificate refused as an agent, another root's agent refused, bad ids refused; +- the signer: a root made through a counting signer is used exactly once per operation and never exposes a key; + a signer whose key does not match the root certificate is refused; +- hostile input: garbage PEM/DER never panics. + +## Risks and gaps + +- No CRL or OCSP: revocation of agents is the registry's job (Fabrica keeps the current serial per agent), of devices + Ianitor's allow list. Short agent lifetimes bound the gap. +- `Signer` is synchronous (see above). +- The agents intermediate's key is held by the Fabrica server; how it is stored at rest is Fabrica's (T3b).