Skip to main content

gitpoulpi_hosting/updates/
signing.rs

1//! Release signatures (the security-hardening design, item 4): the check every
2//! file GitPoulpi fetches from a release goes through before it is trusted.
3//!
4//! The release workflow signs each asset with minisign and writes
5//! `<asset>.minisig` next to it, with the trusted comment
6//! `file:<name> version:<v>`. [`verify`] checks the signature against the
7//! compiled-in keys **and** that comment against the file name and version
8//! the caller expects, so a valid signature cannot be moved onto another file
9//! or onto an older release.
10//!
11//! This lives in the hosting crate (and `gitpoulpi-update::signing` re-wraps
12//! it) because the manifest and the security notices are verified here, below
13//! the update engine. It never reads a key from the environment: callers pass
14//! the keys in, and production passes `gitpoulpi_update::signing::release_keys()`.
15
16pub use minisign_verify::PublicKey;
17use minisign_verify::Signature;
18
19/// Why a signature was refused.
20#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
21pub enum SignError {
22    /// No signature file, or one that is not a minisign signature.
23    #[error("the release has no valid signature file, so it is not trusted")]
24    NoSignature,
25    /// The signature does not match the bytes, or no accepted key made it.
26    #[error("the signature does not match (not signed by a GitPoulpi release key): not trusted")]
27    BadSignature,
28    /// A valid signature, but for another file or another version.
29    #[error("the signature is for {found}, expected {expected}: not trusted")]
30    OtherFile { expected: String, found: String },
31}
32
33/// The trusted comment a release signature carries for `name` at `version`.
34pub fn trusted_comment(name: &str, version: &str) -> String {
35    format!("file:{name} version:{version}")
36}
37
38/// What the trusted comment must say about the version.
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub enum VersionRule<'a> {
41    /// Exactly this version (an archive, the manifest).
42    Exactly(&'a str),
43    /// A version that is not older than this one (`security.json`, which is
44    /// republished for the latest release: an old copy must not replace it).
45    NotOlderThan(&'a str),
46}
47
48/// Parses the text of a public key file (`untrusted comment: ...` and the
49/// base64 line).
50pub fn parse_key(text: &str) -> Option<PublicKey> {
51    PublicKey::decode(text).ok()
52}
53
54/// The version a trusted comment names.
55fn comment_version(comment: &str, name: &str) -> Result<String, SignError> {
56    let other = |found: &str| SignError::OtherFile {
57        expected: format!("file:{name}"),
58        found: found.to_string(),
59    };
60    let mut file = None;
61    let mut version = None;
62    for part in comment.split_whitespace() {
63        if let Some(f) = part.strip_prefix("file:") {
64            file = Some(f);
65        } else if let Some(v) = part.strip_prefix("version:") {
66            version = Some(v);
67        }
68    }
69    match (file, version) {
70        (Some(f), Some(v)) if f == name => Ok(v.to_string()),
71        _ => Err(other(comment)),
72    }
73}
74
75/// Verifies `bytes` against the `.minisig` text `sig_text` with any of `keys`,
76/// and the signature's trusted comment against `name` and `rule`.
77pub fn verify_with(
78    bytes: &[u8],
79    sig_text: &str,
80    name: &str,
81    rule: VersionRule<'_>,
82    keys: &[PublicKey],
83) -> Result<(), SignError> {
84    let signature = Signature::decode(sig_text).map_err(|_| SignError::NoSignature)?;
85    if !keys
86        .iter()
87        .any(|key| key.verify(bytes, &signature, false).is_ok())
88    {
89        return Err(SignError::BadSignature);
90    }
91    // The comment is covered by the signature (checked above), so it can be
92    // trusted now: it must name this file and the version asked for.
93    let comment = signature.trusted_comment();
94    let found = comment_version(comment, name)?;
95    let fits = match rule {
96        VersionRule::Exactly(want) => same_version(&found, want),
97        VersionRule::NotOlderThan(floor) => {
98            match (super::Version::parse(&found), super::Version::parse(floor)) {
99                (Some(found), Some(floor)) => found >= floor,
100                _ => false,
101            }
102        }
103    };
104    if fits {
105        Ok(())
106    } else {
107        Err(SignError::OtherFile {
108            expected: match rule {
109                VersionRule::Exactly(v) => trusted_comment(name, v),
110                VersionRule::NotOlderThan(v) => format!("file:{name} version:{v} or newer"),
111            },
112            found: comment.to_string(),
113        })
114    }
115}
116
117/// [`verify_with`] for one exact version.
118pub fn verify(
119    bytes: &[u8],
120    sig_text: &str,
121    name: &str,
122    version: &str,
123    keys: &[PublicKey],
124) -> Result<(), SignError> {
125    verify_with(bytes, sig_text, name, VersionRule::Exactly(version), keys)
126}
127
128fn same_version(a: &str, b: &str) -> bool {
129    let trim = |v: &str| v.trim().trim_start_matches(['v', 'V']).to_string();
130    trim(a) == trim(b)
131}
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136    use gitpoulpi_testkit::signing::TestSigner;
137
138    fn keys(signer: &TestSigner) -> Vec<PublicKey> {
139        vec![parse_key(&signer.public_key_text()).expect("the test key parses")]
140    }
141
142    #[test]
143    fn a_signature_for_this_file_and_version_is_accepted() {
144        let signer = TestSigner::new();
145        let sig = signer.sign("a.tar.gz", "1.2.3", b"bytes");
146        assert_eq!(
147            verify(b"bytes", &sig, "a.tar.gz", "1.2.3", &keys(&signer)),
148            Ok(())
149        );
150        // A leading `v` on the expected version is the same version.
151        assert_eq!(
152            verify(b"bytes", &sig, "a.tar.gz", "v1.2.3", &keys(&signer)),
153            Ok(())
154        );
155    }
156
157    #[test]
158    fn no_signature_text_is_no_signature() {
159        let signer = TestSigner::new();
160        for text in [
161            "",
162            "<html>404</html>",
163            "untrusted comment: x\nnot base64!!\n",
164        ] {
165            assert_eq!(
166                verify(b"bytes", text, "a", "1.0.0", &keys(&signer)),
167                Err(SignError::NoSignature),
168                "{text:?}"
169            );
170        }
171    }
172
173    #[test]
174    fn tampered_bytes_and_another_key_are_bad_signatures() {
175        let signer = TestSigner::new();
176        let sig = signer.sign("a", "1.0.0", b"bytes");
177        assert_eq!(
178            verify(b"tampered", &sig, "a", "1.0.0", &keys(&signer)),
179            Err(SignError::BadSignature)
180        );
181        let stranger = TestSigner::new();
182        assert_eq!(
183            verify(b"bytes", &sig, "a", "1.0.0", &keys(&stranger)),
184            Err(SignError::BadSignature)
185        );
186        assert_eq!(
187            verify(b"bytes", &sig, "a", "1.0.0", &[]),
188            Err(SignError::BadSignature),
189            "no keys accept nothing"
190        );
191    }
192
193    #[test]
194    fn a_signature_for_another_file_or_version_is_refused() {
195        let signer = TestSigner::new();
196        let sig = signer.sign("other.tar.gz", "1.0.0", b"bytes");
197        let err = verify(b"bytes", &sig, "a.tar.gz", "1.0.0", &keys(&signer)).unwrap_err();
198        assert!(matches!(err, SignError::OtherFile { .. }), "{err:?}");
199        let sig = signer.sign("a.tar.gz", "0.9.0", b"bytes");
200        let err = verify(b"bytes", &sig, "a.tar.gz", "1.0.0", &keys(&signer)).unwrap_err();
201        assert!(matches!(err, SignError::OtherFile { .. }), "{err:?}");
202        // No comment at all is not a signature for anything in particular.
203        let sig = signer.sign_with_comment("hello", b"bytes");
204        let err = verify(b"bytes", &sig, "a.tar.gz", "1.0.0", &keys(&signer)).unwrap_err();
205        assert!(matches!(err, SignError::OtherFile { .. }), "{err:?}");
206    }
207
208    #[test]
209    fn a_rotated_key_list_accepts_either_key() {
210        let (old, next) = (TestSigner::new(), TestSigner::new());
211        let both = vec![
212            parse_key(&old.public_key_text()).unwrap(),
213            parse_key(&next.public_key_text()).unwrap(),
214        ];
215        for signer in [&old, &next] {
216            let sig = signer.sign("a", "1.0.0", b"x");
217            assert_eq!(verify(b"x", &sig, "a", "1.0.0", &both), Ok(()));
218        }
219    }
220
221    #[test]
222    fn a_notice_signed_for_an_older_release_than_the_floor_is_refused() {
223        let signer = TestSigner::new();
224        let k = keys(&signer);
225        let rule = VersionRule::NotOlderThan("1.4.0");
226        for (signed, ok) in [("1.4.0", true), ("1.5.0", true), ("1.3.9", false)] {
227            let sig = signer.sign("security.json", signed, b"{}");
228            let got = verify_with(b"{}", &sig, "security.json", rule, &k);
229            assert_eq!(got.is_ok(), ok, "{signed}: {got:?}");
230        }
231    }
232}