Skip to main content

bitwarden_ssh/
import.rs

1use bitwarden_crypto_primitives::{p256 as p256_primitives, rsa as rsa_primitives};
2use ed25519;
3use pem_rfc7468::PemLabel;
4use pkcs8::{
5    DecodePrivateKey, ObjectIdentifier, PrivateKeyInfo, SecretDocument, der::Decode, pkcs5,
6};
7use ssh_key::{
8    Algorithm, Mpint,
9    private::{Ed25519Keypair, RsaKeypair},
10    public::EcdsaPublicKey,
11    sec1,
12};
13
14use crate::{SshKeyData, error::SshKeyImportError, ssh_private_key_to_data};
15
16/// PKCS#1 `rsaEncryption` algorithm OID (RFC 8017).
17const RSA_ENCRYPTION_OID: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.1");
18
19/// Import a PKCS8 or OpenSSH encoded private key, and returns a decoded [SshKeyData],
20/// with the public key and fingerprint, and the private key in OpenSSH format.
21/// A password can be provided for encrypted keys.
22/// # Returns
23/// - [SshKeyImportError::PasswordRequired] if the key is encrypted and no password is provided
24/// - [SshKeyImportError::WrongPassword] if the password provided is incorrect
25/// - [SshKeyImportError::UnsupportedKeyType] if the key type is not supported
26/// - [SshKeyImportError::Parsing] if the key is otherwise malformed and cannot be parsed
27pub fn import_key(
28    encoded_key: String,
29    password: Option<String>,
30) -> Result<SshKeyData, SshKeyImportError> {
31    let label = pem_rfc7468::decode_label(encoded_key.as_bytes())
32        .map_err(|_| SshKeyImportError::Parsing)?;
33
34    match label {
35        pkcs8::PrivateKeyInfo::<(), (), ()>::PEM_LABEL => import_pkcs8_key(encoded_key, None),
36        pkcs8::EncryptedPrivateKeyInfo::<()>::PEM_LABEL => import_pkcs8_key(
37            encoded_key,
38            Some(password.ok_or(SshKeyImportError::PasswordRequired)?),
39        ),
40        ssh_key::PrivateKey::PEM_LABEL => import_openssh_key(encoded_key, password),
41        _ => Err(SshKeyImportError::UnsupportedKeyType),
42    }
43}
44
45fn import_pkcs8_key(
46    encoded_key: String,
47    password: Option<String>,
48) -> Result<SshKeyData, SshKeyImportError> {
49    match parse_pkcs8_pem(&encoded_key, password.as_deref()) {
50        // Some exporters (e.g. 1Password's 1PUX) emit the base64 body on a single line, which the
51        // strict RFC 7468 parser rejects. Re-wrap to 64-character lines and retry once. Only
52        // `Parsing` failures are retried, so keys that import successfully today are unaffected.
53        Err(SshKeyImportError::Parsing) => {
54            let rewrapped = rewrap_pem(&encoded_key).ok_or(SshKeyImportError::Parsing)?;
55            parse_pkcs8_pem(&rewrapped, password.as_deref())
56        }
57        result => result,
58    }
59}
60
61fn parse_pkcs8_pem(
62    encoded_key: &str,
63    password: Option<&str>,
64) -> Result<SshKeyData, SshKeyImportError> {
65    let doc = if let Some(password) = password {
66        SecretDocument::from_pkcs8_encrypted_pem(encoded_key, password.as_bytes()).map_err(
67            |err| match err {
68                pkcs8::Error::EncryptedPrivateKey(pkcs5::Error::DecryptFailed) => {
69                    SshKeyImportError::WrongPassword
70                }
71                _ => SshKeyImportError::Parsing,
72            },
73        )?
74    } else {
75        SecretDocument::from_pkcs8_pem(encoded_key).map_err(|_| SshKeyImportError::Parsing)?
76    };
77
78    import_pkcs8_der_key(doc.as_bytes())
79}
80
81/// Re-wrap the base64 body of a PEM document to 64-character lines.
82///
83/// The strict RFC 7468 parser requires the body wrapped at 64 characters, but some exporters emit
84/// it on a single line. Returns [None] if the input is not a single well-formed PEM block, in which
85/// case the caller keeps the original parse error.
86fn rewrap_pem(pem: &str) -> Option<String> {
87    let mut lines = pem.lines();
88
89    let header = lines
90        .by_ref()
91        .find(|line| line.starts_with("-----BEGIN "))?;
92
93    // Concatenate the body (whitespace stripped) until the closing boundary.
94    let mut body = String::new();
95    let mut footer = None;
96    for line in lines.by_ref() {
97        if line.starts_with("-----END ") {
98            footer = Some(line);
99            break;
100        }
101        body.extend(line.split_whitespace());
102    }
103    let footer = footer?;
104
105    let mut out = String::with_capacity(body.len() + body.len() / 64 + header.len() + 16);
106    out.push_str(header);
107    out.push('\n');
108    // Char-based chunking keeps this panic-free even if the (already-rejected) body is non-ASCII.
109    let mut chars = body.chars();
110    loop {
111        let chunk: String = chars.by_ref().take(64).collect();
112        if chunk.is_empty() {
113            break;
114        }
115        out.push_str(&chunk);
116        out.push('\n');
117    }
118    out.push_str(footer);
119    out.push('\n');
120
121    Some(out)
122}
123
124/// Import a DER encoded private key, and returns a decoded [SshKeyData]. This is primarily used for
125/// importing SSH keys from other Credential Managers through Credential Exchange.
126pub fn import_pkcs8_der_key(encoded_key: &[u8]) -> Result<SshKeyData, SshKeyImportError> {
127    let private_key_info =
128        PrivateKeyInfo::from_der(encoded_key).map_err(|_| SshKeyImportError::Parsing)?;
129
130    let private_key = match private_key_info.algorithm.oid {
131        ed25519::pkcs8::ALGORITHM_OID => {
132            let private_key: ed25519::KeypairBytes = private_key_info
133                .try_into()
134                .map_err(|_| SshKeyImportError::Parsing)?;
135
136            ssh_key::private::PrivateKey::from(Ed25519Keypair::from(&private_key.secret_key.into()))
137        }
138        RSA_ENCRYPTION_OID => import_rsa_pkcs8_der(encoded_key)?,
139        sec1::ALGORITHM_OID => import_ecdsa_pkcs8_der(encoded_key)?,
140        _ => return Err(SshKeyImportError::UnsupportedKeyType),
141    };
142
143    ssh_private_key_to_data(private_key).map_err(|_| SshKeyImportError::Parsing)
144}
145
146fn import_openssh_key(
147    encoded_key: String,
148    password: Option<String>,
149) -> Result<SshKeyData, SshKeyImportError> {
150    let private_key =
151        ssh_key::private::PrivateKey::from_openssh(&encoded_key).map_err(|err| match err {
152            ssh_key::Error::AlgorithmUnknown | ssh_key::Error::AlgorithmUnsupported { .. } => {
153                SshKeyImportError::UnsupportedKeyType
154            }
155            _ => SshKeyImportError::Parsing,
156        })?;
157
158    if !is_supported_algorithm(&private_key.algorithm()) {
159        return Err(SshKeyImportError::UnsupportedKeyType);
160    }
161
162    let private_key = if private_key.is_encrypted() {
163        let password = password.ok_or(SshKeyImportError::PasswordRequired)?;
164        private_key
165            .decrypt(password.as_bytes())
166            .map_err(|_| SshKeyImportError::WrongPassword)?
167    } else {
168        private_key
169    };
170
171    ssh_private_key_to_data(private_key).map_err(|_| SshKeyImportError::Parsing)
172}
173
174/// True if a key of this algorithm can be used once it is in the vault.
175fn is_supported_algorithm(algorithm: &Algorithm) -> bool {
176    matches!(
177        algorithm,
178        Algorithm::Ed25519 | Algorithm::Rsa { .. } | Algorithm::Ecdsa { .. }
179    )
180}
181
182fn import_rsa_pkcs8_der(encoded_key: &[u8]) -> Result<ssh_key::PrivateKey, SshKeyImportError> {
183    let private_key = rsa_primitives::PrivateKey::from_pkcs8_der(encoded_key)
184        .map_err(|_| SshKeyImportError::Parsing)?;
185
186    // Cross from primitives into ssh-key via the big-endian components.
187    let c = private_key.components();
188    let public = ssh_key::public::RsaPublicKey::new(
189        Mpint::from_positive_bytes(&c.e),
190        Mpint::from_positive_bytes(&c.n),
191    )
192    .map_err(|_| SshKeyImportError::Parsing)?;
193    let private = ssh_key::private::RsaPrivateKey::new(
194        Mpint::from_positive_bytes(&c.d),
195        Mpint::from_positive_bytes(&c.iqmp),
196        Mpint::from_positive_bytes(&c.p),
197        Mpint::from_positive_bytes(&c.q),
198    )
199    .map_err(|_| SshKeyImportError::Parsing)?;
200    let keypair = RsaKeypair::new(public, private).map_err(|_| SshKeyImportError::Parsing)?;
201
202    Ok(ssh_key::PrivateKey::from(keypair))
203}
204
205fn import_ecdsa_pkcs8_der(encoded_key: &[u8]) -> Result<ssh_key::PrivateKey, SshKeyImportError> {
206    use pkcs8::DecodePrivateKey as _;
207
208    if let Ok(sk) = p256_primitives::SecretKey::from_pkcs8_der(encoded_key) {
209        // Cross from primitives into ssh-key via the SEC1 point and the raw scalar.
210        let public_key = sk.public_key().to_sec1_uncompressed();
211        let Ok(EcdsaPublicKey::NistP256(public)) = EcdsaPublicKey::from_sec1_bytes(&public_key)
212        else {
213            return Err(SshKeyImportError::Parsing);
214        };
215        let keypair = ssh_key::private::EcdsaKeypair::NistP256 {
216            public,
217            private: ssh_key::private::EcdsaPrivateKey::from(*sk.to_bytes()),
218        };
219        return ssh_key::PrivateKey::new(ssh_key::private::KeypairData::Ecdsa(keypair), "")
220            .map_err(|_| SshKeyImportError::Parsing);
221    }
222    if let Ok(sk) = p384::SecretKey::from_pkcs8_der(encoded_key) {
223        let public_key = sk.public_key();
224        let keypair = ssh_key::private::EcdsaKeypair::NistP384 {
225            public: public_key.into(),
226            private: ssh_key::private::EcdsaPrivateKey::from(sk),
227        };
228        return ssh_key::PrivateKey::new(ssh_key::private::KeypairData::Ecdsa(keypair), "")
229            .map_err(|_| SshKeyImportError::Parsing);
230    }
231    if let Ok(sk) = p521::SecretKey::from_pkcs8_der(encoded_key) {
232        let public_key = sk.public_key();
233        let keypair = ssh_key::private::EcdsaKeypair::NistP521 {
234            public: public_key.into(),
235            private: ssh_key::private::EcdsaPrivateKey::from(sk),
236        };
237        return ssh_key::PrivateKey::new(ssh_key::private::KeypairData::Ecdsa(keypair), "")
238            .map_err(|_| SshKeyImportError::Parsing);
239    }
240    Err(SshKeyImportError::UnsupportedKeyType)
241}
242
243#[cfg(test)]
244mod tests {
245    use super::*;
246
247    #[test]
248    fn import_key_ed25519_openssh_unencrypted() {
249        let private_key = include_str!("../resources/import/ed25519_openssh_unencrypted");
250        let public_key = include_str!("../resources/import/ed25519_openssh_unencrypted.pub").trim();
251        let result = import_key(private_key.to_string(), Some("".to_string())).unwrap();
252        assert_eq!(result.public_key, public_key);
253    }
254
255    #[test]
256    fn import_key_ed25519_openssh_encrypted() {
257        let private_key = include_str!("../resources/import/ed25519_openssh_encrypted");
258        let public_key = include_str!("../resources/import/ed25519_openssh_encrypted.pub").trim();
259        let result = import_key(private_key.to_string(), Some("password".to_string())).unwrap();
260        assert_eq!(result.public_key, public_key);
261    }
262
263    #[test]
264    fn import_key_rsa_openssh_unencrypted() {
265        let private_key = include_str!("../resources/import/rsa_openssh_unencrypted");
266        let public_key = include_str!("../resources/import/rsa_openssh_unencrypted.pub").trim();
267        let result = import_key(private_key.to_string(), Some("".to_string())).unwrap();
268        assert_eq!(result.public_key, public_key);
269    }
270
271    #[test]
272    fn import_key_rsa_openssh_encrypted() {
273        let private_key = include_str!("../resources/import/rsa_openssh_encrypted");
274        let public_key = include_str!("../resources/import/rsa_openssh_encrypted.pub").trim();
275        let result = import_key(private_key.to_string(), Some("password".to_string())).unwrap();
276        assert_eq!(result.public_key, public_key);
277    }
278
279    #[test]
280    fn import_key_ed25519_pkcs8_unencrypted() {
281        let private_key = include_str!("../resources/import/ed25519_pkcs8_unencrypted");
282        let public_key = include_str!("../resources/import/ed25519_pkcs8_unencrypted.pub")
283            .replace("testkey", "");
284        let public_key = public_key.trim();
285        let result = import_key(private_key.to_string(), Some("".to_string())).unwrap();
286        assert_eq!(result.public_key, public_key);
287    }
288
289    #[test]
290    fn import_key_rsa_pkcs8_unencrypted() {
291        let private_key = include_str!("../resources/import/rsa_pkcs8_unencrypted");
292        // for whatever reason pkcs8 + rsa does not include the comment in the public key
293        let public_key =
294            include_str!("../resources/import/rsa_pkcs8_unencrypted.pub").replace("testkey", "");
295        let public_key = public_key.trim();
296        let result = import_key(private_key.to_string(), Some("".to_string())).unwrap();
297        assert_eq!(result.public_key, public_key);
298    }
299
300    #[test]
301    fn import_key_rsa_pkcs8_encrypted() {
302        let private_key = include_str!("../resources/import/rsa_pkcs8_encrypted");
303        let public_key =
304            include_str!("../resources/import/rsa_pkcs8_encrypted.pub").replace("testkey", "");
305        let public_key = public_key.trim();
306        let result = import_key(private_key.to_string(), Some("password".to_string())).unwrap();
307        assert_eq!(result.public_key, public_key);
308    }
309
310    #[test]
311    fn import_key_ed25519_openssh_encrypted_wrong_password() {
312        let private_key = include_str!("../resources/import/ed25519_openssh_encrypted");
313        let result = import_key(private_key.to_string(), Some("wrongpassword".to_string()));
314        assert_eq!(result.unwrap_err(), SshKeyImportError::WrongPassword);
315    }
316
317    /// 1Password's 1PUX export re-encodes Ed25519 keys as PKCS#8 (`BEGIN PRIVATE KEY`) with the
318    /// whole base64 body on a single line. The strict RFC 7468 parser (`pem-rfc7468`) rejects this
319    /// which will result in SshKeyImportError::Parsing ("Failed to parse key")
320    /// https://github.com/bitwarden/clients/issues/20432
321    #[test]
322    fn import_key_ed25519_pkcs8_unencrypted_single_line() {
323        // the private key used below was created by modifying ed25519_pkcs8_unencrypted to match
324        // 1pux export format where key contents span a single line
325        let private_key =
326            include_str!("../resources/import/ed25519_pkcs8_1password_single_line_unencrypted");
327        let public_key = include_str!("../resources/import/ed25519_pkcs8_unencrypted.pub").trim();
328
329        let result = import_key(private_key.to_string(), None).unwrap();
330        assert_eq!(result.public_key, public_key);
331    }
332
333    #[test]
334    fn import_non_key_error() {
335        let result = import_key("not a key".to_string(), Some("".to_string()));
336        assert_eq!(result.unwrap_err(), SshKeyImportError::Parsing);
337    }
338
339    #[test]
340    fn import_wrong_label_error() {
341        let private_key = include_str!("../resources/import/wrong_label");
342        let result = import_key(private_key.to_string(), Some("".to_string()));
343        assert_eq!(result.unwrap_err(), SshKeyImportError::UnsupportedKeyType);
344    }
345
346    #[test]
347    fn import_ecdsa_p256_openssh_unencrypted() {
348        let private_key = include_str!("../resources/import/ecdsa_openssh_unencrypted");
349        let public_key = include_str!("../resources/import/ecdsa_openssh_unencrypted.pub").trim();
350        let result = import_key(private_key.to_string(), Some("".to_string())).unwrap();
351        assert_eq!(result.public_key, public_key);
352    }
353
354    #[test]
355    fn import_ecdsa_p384_openssh_unencrypted() {
356        let private_key = include_str!("../resources/import/ecdsa_p384_openssh_unencrypted");
357        let public_key =
358            include_str!("../resources/import/ecdsa_p384_openssh_unencrypted.pub").trim();
359        let result = import_key(private_key.to_string(), Some("".to_string())).unwrap();
360        assert_eq!(result.public_key, public_key);
361    }
362
363    #[test]
364    fn import_ecdsa_p521_openssh_unencrypted() {
365        let private_key = include_str!("../resources/import/ecdsa_p521_openssh_unencrypted");
366        let public_key =
367            include_str!("../resources/import/ecdsa_p521_openssh_unencrypted.pub").trim();
368        let result = import_key(private_key.to_string(), Some("".to_string())).unwrap();
369        assert_eq!(result.public_key, public_key);
370    }
371
372    #[test]
373    fn import_key_ed25519_putty() {
374        let private_key = include_str!("../resources/import/ed25519_putty_openssh_unencrypted");
375        let public_key =
376            include_str!("../resources/import/ed25519_putty_openssh_unencrypted.pub").trim();
377        let result = import_key(private_key.to_string(), Some("".to_string())).unwrap();
378        assert_eq!(result.public_key, public_key);
379    }
380
381    #[test]
382    fn import_key_rsa_openssh_putty() {
383        let private_key = include_str!("../resources/import/rsa_putty_openssh_unencrypted");
384        let public_key =
385            include_str!("../resources/import/rsa_putty_openssh_unencrypted.pub").trim();
386        let result = import_key(private_key.to_string(), Some("".to_string())).unwrap();
387        assert_eq!(result.public_key, public_key);
388    }
389
390    #[test]
391    fn import_key_rsa_pkcs8_putty() {
392        let private_key = include_str!("../resources/import/rsa_putty_pkcs1_unencrypted");
393        let result = import_key(private_key.to_string(), Some("".to_string()));
394        assert_eq!(result.unwrap_err(), SshKeyImportError::UnsupportedKeyType);
395    }
396
397    #[test]
398    fn import_ed25519_key_regression_17028() {
399        // https://github.com/bitwarden/clients/issues/17028#issuecomment-3455975763
400        let private_key = include_str!("../resources/import/ed25519_regression_17028");
401        let public_key = include_str!("../resources/import/ed25519_regression_17028.pub").trim();
402        let result = import_key(private_key.to_string(), None).unwrap();
403        assert_eq!(result.public_key, public_key);
404    }
405
406    #[test]
407    fn import_sk_ed25519_openssh_unencrypted_is_unsupported() {
408        let private_key = include_str!("../resources/import/sk_ed25519_openssh_unencrypted");
409        let result = import_key(private_key.to_string(), None);
410        assert_eq!(result.unwrap_err(), SshKeyImportError::UnsupportedKeyType);
411    }
412
413    #[test]
414    fn supported_algorithms_are_accepted() {
415        for algorithm in [
416            Algorithm::Ed25519,
417            Algorithm::Rsa { hash: None },
418            Algorithm::Ecdsa {
419                curve: ssh_key::EcdsaCurve::NistP256,
420            },
421            Algorithm::Ecdsa {
422                curve: ssh_key::EcdsaCurve::NistP384,
423            },
424            Algorithm::Ecdsa {
425                curve: ssh_key::EcdsaCurve::NistP521,
426            },
427        ] {
428            assert!(
429                is_supported_algorithm(&algorithm),
430                "{algorithm:?} should be supported"
431            );
432        }
433    }
434
435    #[test]
436    fn unsupported_algorithms_are_rejected() {
437        for algorithm in [
438            Algorithm::Dsa,
439            Algorithm::SkEd25519,
440            Algorithm::SkEcdsaSha2NistP256,
441            Algorithm::new("[email protected]").expect("unknown names map to Algorithm::Other"),
442        ] {
443            assert!(
444                !is_supported_algorithm(&algorithm),
445                "{algorithm:?} should not be supported"
446            );
447        }
448    }
449}