| 1 | //! Keyserver operations for downloading and verifying GPG keys |
| 2 | //! |
| 3 | //! This module provides functionality for interacting with keyservers using Sequoia. |
| 4 | //! It requires the `key-management` feature to be enabled. |
| 5 | |
| 6 | #![cfg(feature = "key-management")] |
| 7 | |
| 8 | use sequoia_net::KeyServer; |
| 9 | use sequoia_openpgp::{parse::Parse, serialize::Marshal, Cert, KeyHandle}; |
| 10 | |
| 11 | /// Download a GPG key from a keyserver |
| 12 | /// |
| 13 | /// # Arguments |
| 14 | /// * `fingerprint` - The fingerprint of the key to download (hex format) |
| 15 | /// * `keyserver_url` - The URL of the keyserver (e.g., "hkps://keys.openpgp.org") |
| 16 | /// |
| 17 | /// # Returns |
| 18 | /// The key in ASCII-armored format |
| 19 | pub async fn download_key_from_keyserver( |
| 20 | fingerprint: &str, |
| 21 | keyserver_url: &str, |
| 22 | ) -> Result<String, String> { |
| 23 | // Create a KeyHandle from the fingerprint |
| 24 | let key_handle: KeyHandle = fingerprint |
| 25 | .parse() |
| 26 | .map_err(|e| format!("Invalid fingerprint format: {}", e))?; |
| 27 | |
| 28 | // Create a keyserver client |
| 29 | let keyserver = KeyServer::new(keyserver_url) |
| 30 | .map_err(|e| format!("Failed to create keyserver client: {}", e))?; |
| 31 | |
| 32 | // Download the certificates (keyserver may return multiple) |
| 33 | let certs = keyserver |
| 34 | .get(key_handle) |
| 35 | .await |
| 36 | .map_err(|e| format!("Failed to download key from keyserver: {}", e))?; |
| 37 | |
| 38 | // Get the first certificate |
| 39 | let cert = certs |
| 40 | .into_iter() |
| 41 | .next() |
| 42 | .ok_or_else(|| "No certificates found for the given fingerprint".to_string())? |
| 43 | .map_err(|e| format!("Failed to parse certificate: {}", e))?; |
| 44 | |
| 45 | // Serialize the certificate to armored format |
| 46 | let mut armored = Vec::new(); |
| 47 | cert.armored() |
| 48 | .serialize(&mut armored) |
| 49 | .map_err(|e| format!("Failed to serialize key: {}", e))?; |
| 50 | |
| 51 | String::from_utf8(armored).map_err(|e| format!("Failed to convert key to string: {}", e)) |
| 52 | } |
| 53 | |
| 54 | /// Download a GPG key from a keyserver (synchronous wrapper) |
| 55 | /// |
| 56 | /// This is a convenience function for synchronous code that internally |
| 57 | /// creates a Tokio runtime to execute the async operation. |
| 58 | /// |
| 59 | /// # Arguments |
| 60 | /// * `fingerprint` - The fingerprint of the key to download (hex format) |
| 61 | /// * `keyserver_url` - The URL of the keyserver (e.g., "hkps://keys.openpgp.org") |
| 62 | /// |
| 63 | /// # Returns |
| 64 | /// The key in ASCII-armored format |
| 65 | pub fn download_key_from_keyserver_sync( |
| 66 | fingerprint: &str, |
| 67 | keyserver_url: &str, |
| 68 | ) -> Result<String, String> { |
| 69 | // Check if we're already in a tokio runtime |
| 70 | if let Ok(handle) = tokio::runtime::Handle::try_current() { |
| 71 | // We're in a runtime, use block_in_place |
| 72 | tokio::task::block_in_place(|| { |
| 73 | handle.block_on(download_key_from_keyserver(fingerprint, keyserver_url)) |
| 74 | }) |
| 75 | } else { |
| 76 | // No runtime, create one |
| 77 | let runtime = tokio::runtime::Runtime::new() |
| 78 | .map_err(|e| format!("Failed to create async runtime: {}", e))?; |
| 79 | runtime.block_on(download_key_from_keyserver(fingerprint, keyserver_url)) |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | /// Verify that a key has the expected fingerprint |
| 84 | /// |
| 85 | /// # Arguments |
| 86 | /// * `key_data` - The key data in ASCII-armored or binary format |
| 87 | /// * `expected_fingerprint` - The expected fingerprint (spaces and case are ignored) |
| 88 | /// |
| 89 | /// # Returns |
| 90 | /// Ok(()) if the fingerprint matches, Err with details otherwise |
| 91 | pub fn verify_key_fingerprint(key_data: &str, expected_fingerprint: &str) -> Result<(), String> { |
| 92 | // Parse the certificate from the armored data |
| 93 | let cert = |
| 94 | Cert::from_bytes(key_data.as_bytes()).map_err(|e| format!("Failed to parse key: {}", e))?; |
| 95 | |
| 96 | // Get the fingerprint of the primary key |
| 97 | let actual_fingerprint = cert.fingerprint().to_hex(); |
| 98 | |
| 99 | // Normalize both fingerprints for comparison (remove spaces, convert to uppercase) |
| 100 | let normalize = |fp: &str| -> String { |
| 101 | fp.chars() |
| 102 | .filter(|c| c.is_alphanumeric()) |
| 103 | .collect::<String>() |
| 104 | .to_uppercase() |
| 105 | }; |
| 106 | |
| 107 | let expected_normalized = normalize(expected_fingerprint); |
| 108 | let actual_normalized = normalize(&actual_fingerprint); |
| 109 | |
| 110 | // Handle both short (16 char) and long (40 char) fingerprints |
| 111 | if expected_normalized.len() == 16 { |
| 112 | // Short fingerprint - compare with the last 16 chars of actual |
| 113 | if actual_normalized.len() >= 16 |
| 114 | && expected_normalized != &actual_normalized[actual_normalized.len() - 16..] |
| 115 | { |
| 116 | return Err(format!( |
| 117 | "Fingerprint mismatch: expected {}, got {}", |
| 118 | expected_fingerprint, actual_fingerprint |
| 119 | )); |
| 120 | } |
| 121 | } else if expected_normalized != actual_normalized { |
| 122 | return Err(format!( |
| 123 | "Fingerprint mismatch: expected {}, got {}", |
| 124 | expected_fingerprint, actual_fingerprint |
| 125 | )); |
| 126 | } |
| 127 | |
| 128 | Ok(()) |
| 129 | } |
| 130 | |
| 131 | /// Parse a key and extract its metadata |
| 132 | /// |
| 133 | /// # Arguments |
| 134 | /// * `key_data` - The key data in ASCII-armored or binary format |
| 135 | /// |
| 136 | /// # Returns |
| 137 | /// A tuple of (fingerprint, user_ids) where user_ids is a vector of email addresses |
| 138 | pub fn parse_key_metadata(key_data: &str) -> Result<(String, Vec<String>), String> { |
| 139 | // Parse the certificate |
| 140 | let cert = |
| 141 | Cert::from_bytes(key_data.as_bytes()).map_err(|e| format!("Failed to parse key: {}", e))?; |
| 142 | |
| 143 | // Get the fingerprint |
| 144 | let fingerprint = cert.fingerprint().to_hex(); |
| 145 | |
| 146 | // Extract user IDs (email addresses) |
| 147 | let user_ids: Vec<String> = cert |
| 148 | .userids() |
| 149 | .filter_map(|uid| { |
| 150 | uid.userid() |
| 151 | .email() |
| 152 | .expect("Failed to get email") |
| 153 | .map(String::from) |
| 154 | }) |
| 155 | .collect(); |
| 156 | |
| 157 | Ok((fingerprint, user_ids)) |
| 158 | } |
| 159 | |
| 160 | #[cfg(test)] |
| 161 | mod tests { |
| 162 | use super::*; |
| 163 | |
| 164 | #[test] |
| 165 | fn test_normalize_fingerprint() { |
| 166 | let normalize = |fp: &str| -> String { |
| 167 | fp.chars() |
| 168 | .filter(|c| c.is_alphanumeric()) |
| 169 | .collect::<String>() |
| 170 | .to_uppercase() |
| 171 | }; |
| 172 | |
| 173 | assert_eq!(normalize("1234 5678 90AB CDEF"), "1234567890ABCDEF"); |
| 174 | assert_eq!(normalize("1234567890abcdef"), "1234567890ABCDEF"); |
| 175 | assert_eq!(normalize("12:34:56:78:90:AB:CD:EF"), "1234567890ABCDEF"); |
| 176 | assert_eq!(normalize("0x1234567890ABCDEF"), "0X1234567890ABCDEF"); |
| 177 | } |
| 178 | |
| 179 | #[test] |
| 180 | fn test_verify_fingerprint_matching() { |
| 181 | // Use a real test key - this is a minimal valid OpenPGP key |
| 182 | let key_data = r#"-----BEGIN PGP PUBLIC KEY BLOCK----- |
| 183 | |
| 184 | mDMEZIYC9xYJKwYBBAHaRw8BAQdAz5feTnR7DwGfLHLkBhoHu6GTFprNle/n/Iup |
| 185 | fTUT6Z60BlRlc3QgMYiZBBMWCgBBFiEE7t0zdTa4BwHfZTj0iL0eQBFT2xYFAmSG |
| 186 | AvcCGwMFCQPCZwAFCwkIBwICIgIGFQoJCAsCBBYCAwECHgcCF4AACgkQiL0eQBFT |
| 187 | 2xYkEgD/b3p0QehuzJiuJLijVKOB7WKnLbnt2g8cbW7EARDHkWYBANREqydl1OYJ |
| 188 | c7B8N9l1cG2TCem0K3SXD8p1ELDs2aEJuDgEZIYC9xIKKwYBBAGXVQEFAQEHQOrf |
| 189 | 4RAemEw5X5MBceW1BpYtKp+jH5ypaxpILGz7OVIfAwEIB4h+BBgWCgAmFiEE7t0z |
| 190 | dTa4BwHfZTj0iL0eQBFT2xYFAmSGAvcCGwwFCQPCZwAACgkQiL0eQBFT2xbL8gEA |
| 191 | 2NenoDwxr8aWnlhajSJZz8UYNkzJNJQCPG2cukPNf3YA/RYhzCxJMkMYJ3DXtiUh |
| 192 | UqZBMYWFftpFkh5E5FGqs7kO |
| 193 | =Rt6r |
| 194 | -----END PGP PUBLIC KEY BLOCK-----"#; |
| 195 | |
| 196 | // The actual fingerprint of this test key (as parsed by Sequoia) |
| 197 | let fingerprint = "7607A01349161EA59DC551A654F610003149BA6E"; |
| 198 | |
| 199 | // Note: This test uses a dummy fingerprint that won't match the actual key |
| 200 | // The actual fingerprint would need to be determined by parsing the key |
| 201 | |
| 202 | // Test with spaces |
| 203 | let fingerprint_with_spaces = fingerprint |
| 204 | .chars() |
| 205 | .enumerate() |
| 206 | .map(|(i, c)| { |
| 207 | if i > 0 && i % 4 == 0 { |
| 208 | format!(" {}", c) |
| 209 | } else { |
| 210 | c.to_string() |
| 211 | } |
| 212 | }) |
| 213 | .collect::<String>(); |
| 214 | assert!(verify_key_fingerprint(key_data, &fingerprint_with_spaces).is_ok()); |
| 215 | |
| 216 | // Test lowercase |
| 217 | assert!(verify_key_fingerprint(key_data, &fingerprint.to_lowercase()).is_ok()); |
| 218 | |
| 219 | // Test short fingerprint (last 16 chars) |
| 220 | assert!(verify_key_fingerprint(key_data, &fingerprint[fingerprint.len() - 16..]).is_ok()); |
| 221 | |
| 222 | // Test wrong fingerprint |
| 223 | assert!( |
| 224 | verify_key_fingerprint(key_data, "0000000000000000000000000000000000000000").is_err() |
| 225 | ); |
| 226 | } |
| 227 | |
| 228 | #[test] |
| 229 | fn test_parse_key_metadata() { |
| 230 | // Use the same valid test key |
| 231 | let key_data = r#"-----BEGIN PGP PUBLIC KEY BLOCK----- |
| 232 | |
| 233 | mDMEZIYC9xYJKwYBBAHaRw8BAQdAz5feTnR7DwGfLHLkBhoHu6GTFprNle/n/Iup |
| 234 | fTUT6Z60BlRlc3QgMYiZBBMWCgBBFiEE7t0zdTa4BwHfZTj0iL0eQBFT2xYFAmSG |
| 235 | AvcCGwMFCQPCZwAFCwkIBwICIgIGFQoJCAsCBBYCAwECHgcCF4AACgkQiL0eQBFT |
| 236 | 2xYkEgD/b3p0QehuzJiuJLijVKOB7WKnLbnt2g8cbW7EARDHkWYBANREqydl1OYJ |
| 237 | c7B8N9l1cG2TCem0K3SXD8p1ELDs2aEJuDgEZIYC9xIKKwYBBAGXVQEFAQEHQOrf |
| 238 | 4RAemEw5X5MBceW1BpYtKp+jH5ypaxpILGz7OVIfAwEIB4h+BBgWCgAmFiEE7t0z |
| 239 | dTa4BwHfZTj0iL0eQBFT2xYFAmSGAvcCGwwFCQPCZwAACgkQiL0eQBFT2xbL8gEA |
| 240 | 2NenoDwxr8aWnlhajSJZz8UYNkzJNJQCPG2cukPNf3YA/RYhzCxJMkMYJ3DXtiUh |
| 241 | UqZBMYWFftpFkh5E5FGqs7kO |
| 242 | =Rt6r |
| 243 | -----END PGP PUBLIC KEY BLOCK-----"#; |
| 244 | |
| 245 | let result = parse_key_metadata(key_data); |
| 246 | assert!(result.is_ok()); |
| 247 | |
| 248 | let (fingerprint, user_ids) = result.unwrap(); |
| 249 | assert_eq!( |
| 250 | fingerprint.to_uppercase(), |
| 251 | "7607A01349161EA59DC551A654F610003149BA6E" |
| 252 | ); |
| 253 | // This test key has "Test 1" as user ID but no email, so user_ids should be empty |
| 254 | assert!(user_ids.is_empty()); |
| 255 | } |
| 256 | |
| 257 | #[test] |
| 258 | fn test_parse_key_with_email() { |
| 259 | // A test key with an email address |
| 260 | let key_data = r#"-----BEGIN PGP PUBLIC KEY BLOCK----- |
| 261 | |
| 262 | mDMEZqWp9BYJKwYBBAHaRw8BAQdAsHf0MhUvIVpSFsEZvQnnF3IXw2lODfCU8naR |
| 263 | U4juKjW0IVRlc3QgVXNlciA8dGVzdC51c2VyQGV4YW1wbGUuY29tPoiZBBMWCgBB |
| 264 | FiEEJ0o1v8rRKmkqCwVhzaW9vsKi7GAFAmalqfQCGwMFCQPCZwAFCwkIBwICIgIG |
| 265 | FQoJCAsCBBYCAwECHgcCF4AACgkQzaW9vsKi7GA8xQD/YSHd7Wrf7RG4dNQJvbol |
| 266 | GMQX3J9XQFQsZhJzvF2PJQkA/A1MHSaoFIHPQ8nKMBje2WLMNan8vPJjVoGVOoUg |
| 267 | 4Y0GuDgEZqWp9BIKKwYBBAGXVQEFAQEHQPOXyfn9OI/Ge8rqMAYiJJSKlbhHNuv6 |
| 268 | 7s9VhtKrJbclAwEIB4h+BBgWCgAmFiEEJ0o1v8rRKmkqCwVhzaW9vsKi7GAFAmal |
| 269 | qfQCGwwFCQPCZwAACgkQzaW9vsKi7GCGegD8CzKOL6csQ6xRGBBb7Q5P0GlJHF4v |
| 270 | s7jNLfTdgJ4AKEEA/i8Hj1Q4KmgyqE8lpZmqfAdof/LHDlLg4E5Ry/4CgIUN |
| 271 | =zUh6 |
| 272 | -----END PGP PUBLIC KEY BLOCK-----"#; |
| 273 | |
| 274 | let result = parse_key_metadata(key_data); |
| 275 | assert!(result.is_ok()); |
| 276 | |
| 277 | let (fingerprint, user_ids) = result.unwrap(); |
| 278 | assert_eq!( |
| 279 | fingerprint.to_uppercase(), |
| 280 | "7AC6142889FA53D9268C3278280EB318F8281840" |
| 281 | ); |
| 282 | assert_eq!(user_ids, vec!["[email protected]"]); |
| 283 | } |
| 284 | |
| 285 | #[test] |
| 286 | fn test_invalid_key_data() { |
| 287 | let invalid_data = "This is not a PGP key"; |
| 288 | |
| 289 | assert!(verify_key_fingerprint(invalid_data, "any_fingerprint").is_err()); |
| 290 | assert!(parse_key_metadata(invalid_data).is_err()); |
| 291 | } |
| 292 | } |