Skip to main content

kute_cli/
sign.rs

1//! Signatures on vocabularies: `kute keygen`, `kute sign`, `kute verify`.
2//!
3//! A signature says that the holder of a key vouches for a vocabulary's
4//! content. It is Ed25519 over a fixed prefix and the vocabulary's
5//! digest, kept in the file beside the digest and outside what the digest
6//! covers, so signing changes neither the digest nor anything that
7//! refers to the vocabulary by it.
8//!
9//! Verifying needs the signer's public key from somewhere the file is
10//! not: a signature in a file proves nothing to someone who takes the key
11//! from the same file. There is no registry and no chain of keys here;
12//! whoever verifies says which keys they trust.
13
14use base64::Engine as _;
15use kute::{vocab, KuteError};
16use ring::signature::{Ed25519KeyPair, KeyPair, UnparsedPublicKey, ED25519};
17use serde_json::{json, Value};
18use std::path::Path;
19
20pub const ALGORITHM: &str = "ed25519";
21/// Most signatures one vocabulary may carry.
22pub const MAX_SIGNATURES: usize = 16;
23/// What is signed is this line followed by the digest. The prefix keeps a
24/// signature made here from being a valid signature of anything else the
25/// same key signs.
26const CONTEXT: &str = "kute-vocabulary-signature-v1\n";
27const PEM_HEAD: &str = "-----BEGIN PRIVATE KEY-----";
28const PEM_TAIL: &str = "-----END PRIVATE KEY-----";
29
30fn b64() -> base64::engine::GeneralPurpose {
31    base64::engine::general_purpose::STANDARD
32}
33
34fn message(digest: &str) -> Vec<u8> {
35    format!("{CONTEXT}{digest}").into_bytes()
36}
37
38/// A key is named by the hash of its public half.
39pub fn key_id(public: &[u8]) -> String {
40    format!("{ALGORITHM}:{}", kute::sha256_tagged(public).trim_start_matches("sha256:"))
41}
42
43fn bad_key(why: &str) -> KuteError {
44    KuteError::InvalidInput(format!("not a usable signing key: {why}"))
45}
46
47fn load_key(path: &Path) -> kute::Result<Ed25519KeyPair> {
48    if std::fs::metadata(path)?.len() > 16 * 1024 {
49        return Err(bad_key("the file is larger than a key"));
50    }
51    let text = std::fs::read_to_string(path).map_err(|_| bad_key("the file is not text"))?;
52    let body = text.trim().strip_prefix(PEM_HEAD).and_then(|rest| rest.strip_suffix(PEM_TAIL)).ok_or_else(|| bad_key("expected one PEM block labelled PRIVATE KEY"))?;
53    let der = b64().decode(body.split_whitespace().collect::<String>()).map_err(|_| bad_key("the PEM body is not base64"))?;
54    Ed25519KeyPair::from_pkcs8(&der).map_err(|_| bad_key("not an Ed25519 key in PKCS#8"))
55}
56
57fn public_of(text: &str) -> kute::Result<Vec<u8>> {
58    let key = b64().decode(text.trim()).map_err(|_| KuteError::InvalidInput(format!("a trusted key is not base64: {text:?}")))?;
59    if key.len() != 32 {
60        return Err(KuteError::InvalidInput(format!("a trusted key is {} bytes; an Ed25519 public key is 32", key.len())));
61    }
62    Ok(key)
63}
64
65/// Make a key and write its private half to `output`, which must not exist.
66pub fn keygen(output: &Path) -> kute::Result<Value> {
67    let random = ring::rand::SystemRandom::new();
68    let document = Ed25519KeyPair::generate_pkcs8(&random).map_err(|_| KuteError::Backend("the system gave no randomness".into()))?;
69    let pair = Ed25519KeyPair::from_pkcs8(document.as_ref()).map_err(|_| KuteError::Backend("the key just made cannot be read back".into()))?;
70    let encoded = b64().encode(document.as_ref());
71    let mut pem = String::from(PEM_HEAD);
72    pem.push('\n');
73    for line in encoded.as_bytes().chunks(64) {
74        pem.push_str(std::str::from_utf8(line).expect("base64 is ASCII"));
75        pem.push('\n');
76    }
77    pem.push_str(PEM_TAIL);
78    pem.push('\n');
79    let mut options = std::fs::OpenOptions::new();
80    options.write(true).create_new(true);
81    #[cfg(unix)]
82    {
83        use std::os::unix::fs::OpenOptionsExt;
84        options.mode(0o600);
85    }
86    use std::io::Write;
87    options.open(output)?.write_all(pem.as_bytes())?;
88    let public = pair.public_key().as_ref();
89    Ok(json!({
90        "private_key_file": output,
91        "public_key": b64().encode(public),
92        "key_id": key_id(public),
93        "algorithm": ALGORITHM,
94        "keep": "the private key file is not encrypted. On Unix it is readable by its owner only; on Windows it has the permissions of its folder.",
95    }))
96}
97
98/// Add this key's signature to the vocabulary and write it to `output`.
99pub fn sign(vocab_path: &Path, key_path: &Path, output: &Path, force: bool) -> kute::Result<Value> {
100    let pair = load_key(key_path)?;
101    let mut vocabulary = vocab::load(vocab_path)?;
102    // The digest of what is there, not the digest the file states.
103    let digest = vocabulary.compute_digest()?;
104    vocabulary.seal()?;
105    let id = key_id(pair.public_key().as_ref());
106    let integrity = vocabulary.integrity.as_mut().expect("sealed");
107    // An entry under this key's name is only a claim until it is checked:
108    // anyone can write one. The signature is made again and takes the place
109    // of whatever was there, so a file that arrives with a false entry
110    // under the signer's name leaves with a true one. Ed25519 gives the
111    // same bytes for the same key and message, so a true entry is unchanged.
112    let signature = b64().encode(pair.sign(&message(&digest)).as_ref());
113    let before = integrity.signatures.len();
114    let already = integrity.signatures.iter().any(|s| s.key_id == id && s.algorithm == ALGORITHM && s.signature == signature);
115    integrity.signatures.retain(|s| s.key_id != id);
116    let replaced = before - integrity.signatures.len() - usize::from(already);
117    if integrity.signatures.len() >= MAX_SIGNATURES {
118        return Err(KuteError::LimitExceeded(format!("the vocabulary already carries {MAX_SIGNATURES} signatures")));
119    }
120    integrity.signatures.push(kute::Signature { key_id: id.clone(), algorithm: ALGORITHM.into(), signature });
121    vocab::save(&vocabulary, output, force)?;
122    let written = vocab::load(output)?;
123    Ok(json!({
124        "output": output,
125        "digest": digest,
126        "digest_unchanged": written.digest()? == digest,
127        "key_id": id,
128        "already_signed_by_this_key": already,
129        "entries_under_this_key_replaced": replaced,
130        "signatures": written.integrity.map_or(0, |i| i.signatures.len()),
131    }))
132}
133
134/// Check the vocabulary's signatures against the keys the caller trusts.
135/// Returns the report and whether at least one trusted key's signature holds.
136pub fn verify(vocab_path: &Path, trusted: &[String]) -> kute::Result<(Value, bool)> {
137    if trusted.is_empty() {
138        return Err(KuteError::InvalidConfig("verify needs at least one --trusted-key: a signature is only worth the key it is checked against".into()));
139    }
140    let keys = trusted.iter().map(|t| public_of(t)).collect::<kute::Result<Vec<_>>>()?;
141    let vocabulary = vocab::load(vocab_path)?;
142    let (digest, rows, held) = check(&vocabulary, &keys)?;
143    let verified = held > 0;
144    Ok((
145        json!({
146            "vocabulary": vocab_path,
147            "digest": digest,
148            "signatures": rows,
149            "trusted_keys_given": keys.iter().map(|k| key_id(k)).collect::<Vec<_>>(),
150            "trusted_keys_with_a_valid_signature": held,
151            "verified": verified,
152            "means": "a valid signature says the holder of that key signed this exact content. It says nothing about whether the content is good, and nothing about who holds the key.",
153        }),
154        verified,
155    ))
156}
157
158/// A test for `kute peer serve --require-signature-from`: passes a
159/// vocabulary that carries a valid signature from one of `trusted`.
160pub fn gate(trusted: &[String]) -> kute::Result<impl Fn(&kute::Vocabulary) -> Result<(), String> + Send + 'static> {
161    let keys = trusted.iter().map(|t| public_of(t)).collect::<kute::Result<Vec<_>>>()?;
162    Ok(move |vocabulary: &kute::Vocabulary| match check(vocabulary, &keys) {
163        Ok((_, _, held)) if held > 0 => Ok(()),
164        Ok((_, rows, _)) if rows.is_empty() => Err("it carries no signature, and this peer requires one from a key it trusts".to_string()),
165        Ok(_) => Err("none of its signatures is a valid one from a key this peer trusts".to_string()),
166        Err(e) => Err(e.to_string()),
167    })
168}
169
170/// The digest computed from content, each signature's standing against
171/// `keys`, and how many of the keys have a valid signature.
172fn check(vocabulary: &kute::Vocabulary, keys: &[Vec<u8>]) -> kute::Result<(String, Vec<Value>, usize)> {
173    let digest = vocabulary.compute_digest()?;
174    let signatures = vocabulary.integrity.as_ref().map(|i| i.signatures.clone()).unwrap_or_default();
175    if signatures.len() > MAX_SIGNATURES {
176        return Err(KuteError::LimitExceeded(format!("the vocabulary carries {} signatures; at most {MAX_SIGNATURES} are read", signatures.len())));
177    }
178    let mut rows = Vec::new();
179    // Keys, not entries: the same signature written sixteen times is one
180    // key vouching once.
181    let mut holding: Vec<&Vec<u8>> = Vec::new();
182    for signature in &signatures {
183        let status = if signature.algorithm != ALGORITHM {
184            "unsupported algorithm"
185        } else {
186            match keys.iter().find(|k| key_id(k) == signature.key_id) {
187                None => "not from a trusted key",
188                Some(key) => match b64().decode(&signature.signature) {
189                    Ok(bytes) if UnparsedPublicKey::new(&ED25519, key).verify(&message(&digest), &bytes).is_ok() => {
190                        if holding.contains(&key) {
191                            "valid, repeats an earlier entry"
192                        } else {
193                            holding.push(key);
194                            "valid"
195                        }
196                    }
197                    _ => "INVALID",
198                },
199            }
200        };
201        rows.push(json!({ "key_id": signature.key_id, "algorithm": signature.algorithm, "status": status }));
202    }
203    let held = holding.len();
204    Ok((digest, rows, held))
205}