Skip to main content

mur_common/agent/
ssh_fingerprint.rs

1//! OpenSSH `SHA256:` fingerprints, for the CLI that writes `entitlements.ssh`.
2//!
3//! The runtime matches on these strings and nothing else, so the CLI must
4//! produce exactly the form `ssh-keygen -lf` prints: `SHA256:` followed by the
5//! unpadded base64 of the SHA-256 of the key blob.
6
7use base64::Engine as _;
8use sha2::{Digest, Sha256};
9
10/// Prefix of every fingerprint the policy accepts.
11pub const FINGERPRINT_PREFIX: &str = "SHA256:";
12
13/// Length of the unpadded base64 of a 32-byte digest.
14const DIGEST_B64_LEN: usize = 43;
15
16/// Fingerprint of a raw public key blob.
17pub fn fingerprint_of_blob(blob: &[u8]) -> String {
18    let digest = Sha256::digest(blob);
19    format!(
20        "{FINGERPRINT_PREFIX}{}",
21        base64::engine::general_purpose::STANDARD_NO_PAD.encode(digest)
22    )
23}
24
25/// Fingerprint of the base64 key field of a `known_hosts` / `ssh-add -L`
26/// line. `None` when the field is not valid base64.
27pub fn fingerprint_of_base64(key_base64: &str) -> Option<String> {
28    base64::engine::general_purpose::STANDARD
29        .decode(key_base64)
30        .ok()
31        .map(|blob| fingerprint_of_blob(&blob))
32}
33
34/// Whether `s` is a well-formed fingerprint (the same rule the proxy policy
35/// applies; a malformed entry makes the whole policy refuse).
36pub fn is_fingerprint(s: &str) -> bool {
37    s.strip_prefix(FINGERPRINT_PREFIX).is_some_and(|b| {
38        b.len() == DIGEST_B64_LEN
39            && base64::engine::general_purpose::STANDARD_NO_PAD
40                .decode(b)
41                .is_ok_and(|d| d.len() == 32)
42    })
43}
44
45#[cfg(test)]
46mod tests {
47    use super::*;
48
49    /// `ssh-keygen -lf` on this ed25519 key prints exactly this fingerprint.
50    const ED25519_B64: &str =
51        "AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl";
52    const ED25519_FP: &str = "SHA256:+DiY3wvvV6TuJJhbpZisF/zLDA0zPMSvHdkr4UvCOqU";
53
54    #[test]
55    fn matches_ssh_keygen_output() {
56        assert_eq!(
57            fingerprint_of_base64(ED25519_B64).as_deref(),
58            Some(ED25519_FP)
59        );
60        assert!(is_fingerprint(ED25519_FP));
61    }
62
63    #[test]
64    fn rejects_malformed_fingerprints_and_base64() {
65        for bad in [
66            "SHA256:short",
67            "MD5:aa",
68            ED25519_FP.trim_start_matches("SHA256:"),
69            "",
70        ] {
71            assert!(!is_fingerprint(bad), "{bad}");
72        }
73        assert_eq!(fingerprint_of_base64("not base64!"), None);
74    }
75}