From 049b0590040ebf08338b05f9483663dd280c1ca5 Mon Sep 17 00:00:00 2001 From: "Neal H. Walfield" Date: Fri, 12 Jan 2024 17:20:26 +0100 Subject: openpgp: Reject short key IDs. - When parsing a key ID string, reject short key IDs. - Note: we can't reject short key IDs in `KeyID::from_bytes`, because that function in infallible. But, that function does return `KeyID::Invalid` when presented with a short key ID. - Fixes #388. --- openpgp/NEWS | 1 + openpgp/src/keyid.rs | 17 +++++++++++++++-- openpgp/src/lib.rs | 4 ++++ 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/openpgp/NEWS b/openpgp/NEWS index d5b7debf..c68fd0d8 100644 --- a/openpgp/NEWS +++ b/openpgp/NEWS @@ -17,6 +17,7 @@ - Cert::exportable - CertBuilder::set_exportable - UserID::from_static_bytes + - Error::ShortKeyID * Changes in 1.17.0 ** Notable fixes - Sequoia now ignores some formatting errors when reading secret diff --git a/openpgp/src/keyid.rs b/openpgp/src/keyid.rs index 2d880706..1dc08fe8 100644 --- a/openpgp/src/keyid.rs +++ b/openpgp/src/keyid.rs @@ -107,6 +107,8 @@ impl std::str::FromStr for KeyID { // A KeyID is exactly 8 bytes long. if bytes.len() == 8 { Ok(KeyID::from_bytes(&bytes[..])) + } else if bytes.len() == 4 { + Err(Error::ShortKeyID(s.to_string()).into()) } else { // Maybe a fingerprint was given. Try to parse it and // convert it to a KeyID. @@ -456,8 +458,19 @@ mod test { "GB3751F1587DAEF1".parse::().unwrap_err(); "EFB3751F1587DAEF1".parse::().unwrap_err(); "%FB3751F1587DAEF1".parse::().unwrap_err(); - assert_match!(KeyID::Invalid(_) = "587DAEF1".parse().unwrap()); - assert_match!(KeyID::Invalid(_) = "0x587DAEF1".parse().unwrap()); + } + + #[test] + fn from_hex_short_keyid() { + for s in &[ "FB3751F1", "0xFB3751F1", "fb3751f1", "0xfb3751f1" ] { + match s.parse::() { + Ok(_) => panic!("Failed to reject short Key ID."), + Err(err) => { + let err = err.downcast_ref::().unwrap(); + assert!(matches!(err, Error::ShortKeyID(_))); + } + } + } } #[test] diff --git a/openpgp/src/lib.rs b/openpgp/src/lib.rs index 6f792c88..09e1bfca 100644 --- a/openpgp/src/lib.rs +++ b/openpgp/src/lib.rs @@ -345,6 +345,10 @@ pub enum Error { }) .unwrap_or_else(|| "".into()))] PolicyViolation(String, Option), + + /// Short key IDs are insecure, and not supported. + #[error("Short key IDs are insecure, and not supported: {0}")] + ShortKeyID(String), } assert_send_and_sync!(Error); -- cgit v1.2.3