Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions ssh-key/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ sha2 = { version = "0.11", optional = true, default-features = false }
hex-literal = "1"
chacha20 = { version = "0.10", features = ["rng"] }
getrandom = { version = "0.4", features = ["sys_rng"] }
serde_test = "1.0.177"

[features]
default = ["ecdsa", "rand_core", "sha2", "std"]
Expand Down
18 changes: 14 additions & 4 deletions ssh-key/tests/authorized_keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,19 @@

#![cfg(all(feature = "ecdsa", feature = "std"))]

use ssh_key::AuthorizedKeys;
use ssh_key::{
AuthorizedKeys,
authorized_keys::{ConfigOpts, Entry},
};

// TODO(tarcieri): test file permissions
#[test]
fn read_example_file() {
let authorized_keys = AuthorizedKeys::read_file("./tests/examples/authorized_keys").unwrap();
assert_eq!(authorized_keys.len(), 5);
for entry in &authorized_keys {
assert_eq!(&entry.to_string().parse::<Entry>().unwrap(), entry);
}

assert_eq!(authorized_keys[0].config_opts().to_string(), "");
assert_eq!(
Expand Down Expand Up @@ -43,9 +49,13 @@ fn read_example_file() {
b"user3@example.com"
);

assert_eq!(
authorized_keys[3].config_opts().to_string(),
"from=\"10.0.0.?,*.example.com\",no-X11-forwarding"
let opts: ConfigOpts = r#"from="10.0.0.?,*.example.com",no-X11-forwarding"#
.parse()
.unwrap();
assert_eq!(authorized_keys[3].config_opts(), &opts);
assert!(
opts.iter()
.eq([r#"from="10.0.0.?,*.example.com""#, "no-X11-forwarding"])
);
assert_eq!(
authorized_keys[3].public_key().to_string(),
Expand Down
77 changes: 49 additions & 28 deletions ssh-key/tests/certificate_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,20 @@
#![cfg(all(
feature = "alloc",
feature = "rand_core",
any(feature = "ed25519", feature = "p256")
any(
feature = "ed25519",
feature = "p256",
feature = "p384",
feature = "p521"
)
))]

use chacha20::{ChaCha8Rng, rand_core::SeedableRng};
#[cfg(any(feature = "ed25519", feature = "p256"))]
use hex_literal::hex;
use ssh_key::{Algorithm, PrivateKey, certificate};

#[cfg(feature = "p256")]
#[cfg(any(feature = "p256", feature = "p384", feature = "p521"))]
use ssh_key::EcdsaCurve;

#[cfg(all(feature = "ed25519", feature = "rsa"))]
Expand Down Expand Up @@ -103,34 +109,49 @@ fn ed25519_sign_and_verify() {
decoded.verify_signature().unwrap();
}

#[cfg(feature = "p256")]
#[test]
fn ecdsa_nistp256_sign_and_verify() {
let mut rng = ChaCha8Rng::from_seed(PRNG_SEED);

let algorithm = Algorithm::Ecdsa {
curve: EcdsaCurve::NistP256,
};
let ca_key = PrivateKey::random(&mut rng, algorithm.clone()).unwrap();
let subject_key = PrivateKey::random(&mut rng, algorithm.clone()).unwrap();
let mut cert_builder = certificate::Builder::new_with_random_nonce(
&mut rng,
subject_key.public_key(),
ISSUED_AT,
EXPIRES_AT,
)
.unwrap();
cert_builder.all_principals_valid().unwrap();
let cert = cert_builder.sign(&ca_key).unwrap();

assert_eq!(cert.algorithm(), algorithm);
assert!(cert.valid_principals().is_empty());
assert_eq!(cert.nonce(), &hex!("321fdf7e0a2afe803308f394f54c6abe"));
assert_eq!(cert.public_key(), subject_key.public_key().key_data());
assert_eq!(cert.signature_key(), ca_key.public_key().key_data());
fn generated_keys_sign_certificates() {
for algorithm in [
#[cfg(feature = "ed25519")]
Algorithm::Ed25519,
#[cfg(feature = "p256")]
Algorithm::from(EcdsaCurve::NistP256),
#[cfg(feature = "p384")]
Algorithm::from(EcdsaCurve::NistP384),
#[cfg(feature = "p521")]
Algorithm::from(EcdsaCurve::NistP521),
#[cfg(all(feature = "mldsa", feature = "ed25519"))]
Algorithm::MlDsa44Ed25519,
] {
let mut rng = ChaCha8Rng::from_seed(PRNG_SEED);
let ca = PrivateKey::random(&mut rng, algorithm.clone()).unwrap();
let subject = PrivateKey::random(&mut rng, algorithm.clone()).unwrap();
let mut builder = certificate::Builder::new_with_random_nonce(
&mut rng,
subject.public_key(),
ISSUED_AT,
EXPIRES_AT,
)
.unwrap();
builder.all_principals_valid().unwrap();
builder.cert_type(certificate::CertType::Host).unwrap();

let ca_fingerprint = ca_key.fingerprint(Default::default());
assert!(cert.validate_at(VALID_AT, &[ca_fingerprint]).is_ok());
let cert = builder.sign(&ca).unwrap();
let decoded = ssh_key::Certificate::from_openssh(&cert.to_openssh().unwrap()).unwrap();
assert_eq!(decoded.algorithm(), algorithm);
assert_eq!(decoded.cert_type(), certificate::CertType::Host);
assert!(decoded.valid_principals().is_empty());
assert_eq!(decoded, cert);
#[cfg(feature = "p256")]
if algorithm == EcdsaCurve::NistP256.into() {
assert_eq!(decoded.nonce(), &hex!("321fdf7e0a2afe803308f394f54c6abe"));
}
assert_eq!(decoded.public_key(), subject.public_key().key_data());
assert_eq!(decoded.signature_key(), ca.public_key().key_data());
decoded
.validate_at(VALID_AT, &[ca.fingerprint(Default::default())])
.unwrap();
}
}

#[cfg(feature = "ed25519")]
Expand Down
5 changes: 4 additions & 1 deletion ssh-key/tests/known_hosts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,16 @@

#![cfg(all(feature = "ecdsa", feature = "std"))]

use ssh_key::known_hosts::{HostPatterns, KnownHosts, Marker};
use ssh_key::known_hosts::{Entry, HostPatterns, KnownHosts, Marker};

// TODO(tarcieri): test file permissions
#[test]
fn read_example_file() {
let known_hosts = KnownHosts::read_file("./tests/examples/known_hosts").unwrap();
assert_eq!(known_hosts.len(), 4);
for entry in &known_hosts {
assert_eq!(&entry.to_string().parse::<Entry>().unwrap(), entry);
}

assert_eq!(known_hosts[0].marker(), None);
assert_eq!(
Expand Down
98 changes: 82 additions & 16 deletions ssh-key/tests/private_key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ use ssh_key::{Algorithm, Cipher, KdfAlg, PrivateKey};
#[cfg(any(feature = "p256", feature = "p384", feature = "p521"))]
use ssh_key::EcdsaCurve;
#[cfg(feature = "alloc")]
use ssh_key::{LineEnding, PublicKey};
use ssh_key::LineEnding;
#[cfg(any(feature = "alloc", feature = "ed25519"))]
use ssh_key::PublicKey;
#[cfg(all(feature = "sha2", feature = "std"))]
use std::{io, path::PathBuf, process};

Expand Down Expand Up @@ -133,6 +135,16 @@ fn validate_dsa(key: PrivateKey) {
assert!(key.kdf().is_none());

let dsa_keypair = key.key_data().dsa().unwrap();
#[cfg(feature = "dsa")]
{
let native = dsa::SigningKey::try_from(dsa_keypair.clone()).unwrap();
check_native_public(
ssh_key::public::DsaPublicKey::try_from(native.verifying_key()).unwrap(),
include_str!("examples/id_dsa_1024.pub"),
);
let imported = ssh_key::private::DsaKeypair::try_from(native).unwrap();
assert_eq!(PrivateKey::from(imported).key_data(), key.key_data());
}
assert_eq!(
&hex!(
"dc3d89250ed9462114cb2c8d4816e3a511aaff1b06b0e01de17c1cb04e581bcab97176471d89fd7ca1817
Expand Down Expand Up @@ -348,6 +360,16 @@ fn validate_ed25519(key: PrivateKey) {
assert!(key.kdf().is_none());

let ed25519_keypair = key.key_data().ed25519().unwrap();
#[cfg(feature = "ed25519")]
{
let native = ed25519_dalek::SigningKey::try_from(ed25519_keypair.clone()).unwrap();
check_native_public(
ssh_key::public::Ed25519PublicKey::from(native.verifying_key()),
include_str!("examples/id_ed25519.pub"),
);
let imported = ssh_key::private::Ed25519Keypair::from(native);
assert_eq!(PrivateKey::from(imported).key_data(), key.key_data());
}
assert_eq!(
&hex!("b33eaef37ea2df7caa010defdea34e241f65f1b529a4f43ed14327f5c54aab62"),
ed25519_keypair.public.as_ref(),
Expand Down Expand Up @@ -560,21 +582,27 @@ fn decode_rsa_4096_openssh() {
#[test]
fn round_trip_rsa_3072() {
let private_key = PrivateKey::from_openssh(OPENSSH_RSA_3072_EXAMPLE).unwrap();
let rsa_keypair = match private_key.key_data() {
ssh_key::private::KeypairData::Rsa(k) => k,
_ => unreachable!(),
};

let rsa_private_key = rsa::PrivateKey::try_from(rsa_keypair).unwrap();
let rsa_keypair2 = ssh_key::private::RsaKeypair::try_from(&rsa_private_key).unwrap();
assert_eq!(rsa_keypair, &rsa_keypair2);
let rsa_keypair = private_key.key_data().rsa().unwrap();
let native = rsa::PrivateKey::try_from(rsa_keypair.clone()).unwrap();
check_native_public(
ssh_key::public::RsaPublicKey::try_from(native.to_public_key()).unwrap(),
include_str!("examples/id_rsa_3072.pub"),
);
let imported = ssh_key::private::RsaKeypair::try_from(native).unwrap();
assert_eq!(
PrivateKey::from(imported).key_data(),
private_key.key_data()
);
}

#[cfg(feature = "alloc")]
#[test]
fn decode_security_key_private_fields() {
use encoding::{Decode, Decoder, Encode};
use ssh_key::private::KeypairData;
use ssh_key::{
private::{self, KeypairData},
public::KeyData,
};

for fixture in [
include_str!("examples/id_sk_ed25519.pub"),
Expand All @@ -585,6 +613,25 @@ fn decode_security_key_private_fields() {
let mut bytes = public.to_bytes().unwrap();
0x05u8.encode(&mut bytes).unwrap();
b"handle".as_slice().encode(&mut bytes).unwrap();

// New handles have an empty reserved field. Imported keys can carry reserved data.
let registered: PrivateKey = match public.key_data() {
KeyData::SkEd25519(sk) => private::SkEd25519::new(sk.clone(), 0x05, b"handle")
.unwrap()
.into(),
#[cfg(feature = "ecdsa")]
KeyData::SkEcdsaSha2NistP256(sk) => {
private::SkEcdsaSha2NistP256::new(sk.clone(), 0x05, b"handle")
.unwrap()
.into()
}
_ => unreachable!(),
};
let mut expected = bytes.clone();
b"".as_slice().encode(&mut expected).unwrap();
assert_eq!(registered.key_data().encode_vec().unwrap(), expected);
assert_eq!(registered.public_key().key_data(), public.key_data());

b"reserved".as_slice().encode(&mut bytes).unwrap();

let mut reader = Decoder::from_bytes(&bytes).unwrap();
Expand All @@ -599,6 +646,7 @@ fn decode_security_key_private_fields() {
assert_eq!(key_handle, b"handle");
assert!(reader.is_finished());
assert_eq!(keypair.encode_vec().unwrap(), bytes);
round_trip_keypair(keypair, &public);
}
}

Expand All @@ -613,14 +661,17 @@ fn decode_custom_algorithm_openssh() {
assert_eq!(KdfAlg::None, key.kdf().algorithm());
assert!(key.kdf().is_none());

let opaque_keypair = key.key_data().other().unwrap();
assert_eq!(
&hex!("888f24ee17adfed0091e67e485fb9844cfed6072cac1d06390e4005f5015b44f"),
opaque_keypair.public.as_ref(),
let public = ssh_key::public::OpaquePublicKey::new(
hex!("888f24ee17adfed0091e67e485fb9844cfed6072cac1d06390e4005f5015b44f").to_vec(),
Algorithm::new("name@example.com").unwrap(),
);
let expected = ssh_key::private::OpaqueKeypair::new(
hex!("986c953b4b5efb3285ff207c1ca5ee39a59047bc488fbc3b1ef036efc7575c75").to_vec(),
public,
);
assert_eq!(
&hex!("986c953b4b5efb3285ff207c1ca5ee39a59047bc488fbc3b1ef036efc7575c75"),
opaque_keypair.private.as_ref(),
key.key_data(),
&ssh_key::private::KeypairData::Other(expected)
);

assert_eq!(key.comment().as_bytes(), b"comment@example.com");
Expand Down Expand Up @@ -711,9 +762,24 @@ fn round_trip_test(private_key: &str) -> PrivateKey {
let key2 = PrivateKey::from_openssh(&*pem).unwrap();
assert_eq!(key, key2);

round_trip_keypair(key.key_data().clone(), key.public_key());
key
}

#[cfg(feature = "alloc")]
fn round_trip_keypair(keypair: ssh_key::private::KeypairData, public: &PublicKey) {
let key = PrivateKey::new(keypair, public.comment().clone()).unwrap();
let decoded = PrivateKey::from_bytes(&key.to_bytes().unwrap()).unwrap();
assert_eq!(decoded.public_key(), public);
assert_eq!(decoded, key);
}

#[cfg(any(feature = "dsa", feature = "ed25519", feature = "rsa"))]
fn check_native_public(public: impl Into<PublicKey>, fixture: &str) {
let expected = PublicKey::from_openssh(fixture).unwrap();
assert_eq!(public.into().key_data(), expected.key_data());
}

/// Parse PEM encoded using `PrivateKey::to_openssh` using the `ssh-keygen` utility.
#[cfg(all(feature = "sha2", feature = "std"))]
fn encoding_integration_test(private_key: PrivateKey) {
Expand Down
Loading