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    // Name the file: an error about a key that says only "not found"
49    // does not say which of a command's files was meant.
50    let size = std::fs::metadata(path).map_err(|e| KuteError::InvalidConfig(format!("the private key {}: {e}", path.display())))?.len();
51    if size > 16 * 1024 {
52        return Err(bad_key("the file is larger than a key"));
53    }
54    let text = std::fs::read_to_string(path).map_err(|_| bad_key("the file is not text"))?;
55    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"))?;
56    let der = b64().decode(body.split_whitespace().collect::<String>()).map_err(|_| bad_key("the PEM body is not base64"))?;
57    Ed25519KeyPair::from_pkcs8(&der).map_err(|_| bad_key("not an Ed25519 key in PKCS#8"))
58}
59
60fn public_of(text: &str) -> kute::Result<Vec<u8>> {
61    let key = b64().decode(text.trim()).map_err(|_| KuteError::InvalidInput(format!("a trusted key is not base64: {text:?}")))?;
62    if key.len() != 32 {
63        return Err(KuteError::InvalidInput(format!("a trusted key is {} bytes; an Ed25519 public key is 32", key.len())));
64    }
65    Ok(key)
66}
67
68/// Make a key and write its private half to `output`, which must not exist.
69pub fn keygen(output: &Path) -> kute::Result<Value> {
70    let random = ring::rand::SystemRandom::new();
71    let document = Ed25519KeyPair::generate_pkcs8(&random).map_err(|_| KuteError::Backend("the system gave no randomness".into()))?;
72    let pair = Ed25519KeyPair::from_pkcs8(document.as_ref()).map_err(|_| KuteError::Backend("the key just made cannot be read back".into()))?;
73    let encoded = b64().encode(document.as_ref());
74    let mut pem = String::from(PEM_HEAD);
75    pem.push('\n');
76    for line in encoded.as_bytes().chunks(64) {
77        pem.push_str(std::str::from_utf8(line).expect("base64 is ASCII"));
78        pem.push('\n');
79    }
80    pem.push_str(PEM_TAIL);
81    pem.push('\n');
82    let mut options = std::fs::OpenOptions::new();
83    options.write(true).create_new(true);
84    #[cfg(unix)]
85    {
86        use std::os::unix::fs::OpenOptionsExt;
87        options.mode(0o600);
88    }
89    use std::io::Write;
90    options.open(output)?.write_all(pem.as_bytes())?;
91    let public = pair.public_key().as_ref();
92    Ok(json!({
93        "private_key_file": output,
94        "public_key": b64().encode(public),
95        "key_id": key_id(public),
96        "algorithm": ALGORITHM,
97        "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.",
98    }))
99}
100
101/// Add this key's signature to the vocabulary and write it to `output`.
102/// What signing did to a vocabulary: its digest, the key's name, whether
103/// this key's signature was already there, and how many entries under
104/// its name were replaced.
105struct Signed {
106    digest: String,
107    key_id: String,
108    already: bool,
109    replaced: usize,
110}
111
112/// Seal `vocabulary` and add this key's signature of its digest.
113fn attach(vocabulary: &mut kute::Vocabulary, pair: &Ed25519KeyPair) -> kute::Result<Signed> {
114    // The digest of what is there, not the digest the file states.
115    let digest = vocabulary.compute_digest()?;
116    vocabulary.seal()?;
117    let id = key_id(pair.public_key().as_ref());
118    let integrity = vocabulary.integrity.as_mut().expect("sealed");
119    // An entry under this key's name is only a claim until it is checked:
120    // anyone can write one. The signature is made again and takes the place
121    // of whatever was there, so a file that arrives with a false entry
122    // under the signer's name leaves with a true one. Ed25519 gives the
123    // same bytes for the same key and message, so a true entry is unchanged.
124    let signature = b64().encode(pair.sign(&message(&digest)).as_ref());
125    let before = integrity.signatures.len();
126    let already = integrity.signatures.iter().any(|s| s.key_id == id && s.algorithm == ALGORITHM && s.signature == signature);
127    integrity.signatures.retain(|s| s.key_id != id);
128    let replaced = before - integrity.signatures.len() - usize::from(already);
129    if integrity.signatures.len() >= MAX_SIGNATURES {
130        return Err(KuteError::LimitExceeded(format!("the vocabulary already carries {MAX_SIGNATURES} signatures")));
131    }
132    integrity.signatures.push(kute::Signature { key_id: id.clone(), algorithm: ALGORITHM.into(), signature });
133    Ok(Signed { digest, key_id: id, already, replaced })
134}
135
136/// For `kute peer send --sign-with`: signs, with the key in `key_path`,
137/// the vocabulary a proposal derives. The key is read now, so that a
138/// key that cannot be read is told before anything is sent.
139pub fn signer(key_path: &Path) -> kute::Result<impl Fn(&mut kute::Vocabulary) -> kute::Result<()> + use<>> {
140    let pair = load_key(key_path)?;
141    Ok(move |vocabulary: &mut kute::Vocabulary| attach(vocabulary, &pair).map(|_| ()))
142}
143
144pub fn sign(vocab_path: &Path, key_path: &Path, output: &Path, force: bool) -> kute::Result<Value> {
145    let pair = load_key(key_path)?;
146    let mut vocabulary = vocab::load(vocab_path)?;
147    let Signed { digest, key_id: id, already, replaced } = attach(&mut vocabulary, &pair)?;
148    vocab::save(&vocabulary, output, force)?;
149    let written = vocab::load(output)?;
150    Ok(json!({
151        "output": output,
152        "digest": digest,
153        "digest_unchanged": written.digest()? == digest,
154        "key_id": id,
155        "already_signed_by_this_key": already,
156        "entries_under_this_key_replaced": replaced,
157        "signatures": written.integrity.map_or(0, |i| i.signatures.len()),
158    }))
159}
160
161/// Check the vocabulary's signatures against the keys the caller trusts.
162/// Returns the report and whether at least one trusted key's signature holds.
163pub fn verify(vocab_path: &Path, trusted: &[String]) -> kute::Result<(Value, bool)> {
164    if trusted.is_empty() {
165        return Err(KuteError::InvalidConfig("verify needs at least one --trusted-key: a signature is only worth the key it is checked against".into()));
166    }
167    let keys = trusted.iter().map(|t| public_of(t)).collect::<kute::Result<Vec<_>>>()?;
168    let vocabulary = vocab::load(vocab_path)?;
169    let (digest, rows, held) = check(&vocabulary, &keys)?;
170    let verified = held > 0;
171    Ok((
172        json!({
173            "vocabulary": vocab_path,
174            "digest": digest,
175            "signatures": rows,
176            "trusted_keys_given": keys.iter().map(|k| key_id(k)).collect::<Vec<_>>(),
177            "trusted_keys_with_a_valid_signature": held,
178            "verified": verified,
179            "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.",
180        }),
181        verified,
182    ))
183}
184
185/// A test for `kute peer serve --require-signature-from`: passes a
186/// vocabulary that carries a valid signature from one of `trusted`.
187pub fn gate(trusted: &[String]) -> kute::Result<impl Fn(&kute::Vocabulary) -> Result<(), String> + Send + 'static + use<>> {
188    let keys = trusted.iter().map(|t| public_of(t)).collect::<kute::Result<Vec<_>>>()?;
189    Ok(move |vocabulary: &kute::Vocabulary| match check(vocabulary, &keys) {
190        Ok((_, _, held)) if held > 0 => Ok(()),
191        Ok((_, rows, _)) if rows.is_empty() => Err("it carries no signature, and this peer requires one from a key it trusts".to_string()),
192        Ok(_) => Err("none of its signatures is a valid one from a key this peer trusts".to_string()),
193        Err(e) => Err(e.to_string()),
194    })
195}
196
197/// The digest computed from content, each signature's standing against
198/// `keys`, and how many of the keys have a valid signature.
199fn check(vocabulary: &kute::Vocabulary, keys: &[Vec<u8>]) -> kute::Result<(String, Vec<Value>, usize)> {
200    let digest = vocabulary.compute_digest()?;
201    let signatures = vocabulary.integrity.as_ref().map(|i| i.signatures.clone()).unwrap_or_default();
202    if signatures.len() > MAX_SIGNATURES {
203        return Err(KuteError::LimitExceeded(format!("the vocabulary carries {} signatures; at most {MAX_SIGNATURES} are read", signatures.len())));
204    }
205    let mut rows = Vec::new();
206    // Keys, not entries: the same signature written sixteen times is one
207    // key vouching once.
208    let mut holding: Vec<&Vec<u8>> = Vec::new();
209    for signature in &signatures {
210        let status = if signature.algorithm != ALGORITHM {
211            "unsupported algorithm"
212        } else {
213            match keys.iter().find(|k| key_id(k) == signature.key_id) {
214                None => "not from a trusted key",
215                Some(key) => match b64().decode(&signature.signature) {
216                    Ok(bytes) if UnparsedPublicKey::new(&ED25519, key).verify(&message(&digest), &bytes).is_ok() => {
217                        if holding.contains(&key) {
218                            "valid, repeats an earlier entry"
219                        } else {
220                            holding.push(key);
221                            "valid"
222                        }
223                    }
224                    _ => "INVALID",
225                },
226            }
227        };
228        rows.push(json!({ "key_id": signature.key_id, "algorithm": signature.algorithm, "status": status }));
229    }
230    let held = holding.len();
231    Ok((digest, rows, held))
232}