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
2 changes: 1 addition & 1 deletion ssh-key/Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -46,7 +46,7 @@ default = ["ecdsa", "rand_core", "std"]
alloc = [
"encoding/alloc",
"signature/alloc",
"zeroize/alloc"
"zeroize/alloc",
]
std = [
"alloc",
Expand Down
30 changes: 27 additions & 3 deletions ssh-key/src/algorithm.rs
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
//! Algorithm support.

#[cfg(feature = "alloc")]
mod name;

use crate::{Error, Result};
use core::{fmt, str};
use encoding::{Label, LabelError};
Expand All@@ -10,6 +13,9 @@ use {
sha2::{Digest, Sha256, Sha512},
};

#[cfg(feature = "alloc")]
pub use name::AlgorithmName;

/// bcrypt-pbkdf
const BCRYPT: &str = "bcrypt";

Expand DownExpand Up@@ -80,7 +86,7 @@ const SK_SSH_ED25519: &str = "sk-ssh-ed25519@openssh.com";
///
/// This type provides a registry of supported digital signature algorithms
/// used for SSH keys.
#[derive(Copy, Clone, Debug, Default, Eq, Hash, PartialEq, PartialOrd, Ord)]
#[derive(Clone, Debug, Default, Eq, Hash, PartialEq, PartialOrd, Ord)]
#[non_exhaustive]
pub enum Algorithm {
/// Digital Signature Algorithm
Expand DownExpand Up@@ -113,6 +119,10 @@ pub enum Algorithm {

/// FIDO/U2F key with Ed25519
SkEd25519,

/// Other
#[cfg(feature = "alloc")]
Other(AlgorithmName),
}

impl Algorithm {
Expand All@@ -127,6 +137,8 @@ impl Algorithm {
/// - `ssh-rsa`
/// - `sk-ecdsa-sha2-nistp256@openssh.com` (FIDO/U2F key)
/// - `sk-ssh-ed25519@openssh.com` (FIDO/U2F key)
///
/// Any other algorithms are mapped to the [`Algorithm::Other`] variant.
pub fn new(id: &str) -> Result<Self> {
Ok(id.parse()?)
}
Expand All@@ -147,6 +159,8 @@ impl Algorithm {
/// - `sk-ecdsa-sha2-nistp256-cert-v01@openssh.com` (FIDO/U2F key)
/// - `sk-ssh-ed25519-cert-v01@openssh.com` (FIDO/U2F key)
///
/// Any other algorithms are mapped to the [`Algorithm::Other`] variant.
///
/// [PROTOCOL.certkeys]: https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.certkeys?annotate=HEAD
pub fn new_certificate(id: &str) -> Result<Self> {
match id {
Expand All@@ -164,12 +178,15 @@ impl Algorithm {
CERT_RSA => Ok(Algorithm::Rsa { hash: None }),
CERT_SK_ECDSA_SHA2_P256 => Ok(Algorithm::SkEcdsaSha2NistP256),
CERT_SK_SSH_ED25519 => Ok(Algorithm::SkEd25519),
#[cfg(feature = "alloc")]
_ => Ok(Algorithm::Other(AlgorithmName::from_certificate_str(id)?)),
#[cfg(not(feature = "alloc"))]
_ => Err(Error::AlgorithmUnknown),
}
}

/// Get the string identifier which corresponds to this algorithm.
pub fn as_str(self) -> &'static str {
pub fn as_str(&self) -> &str {
match self {
Algorithm::Dsa => SSH_DSA,
Algorithm::Ecdsa { curve } => match curve {
Expand All@@ -185,6 +202,8 @@ impl Algorithm {
},
Algorithm::SkEcdsaSha2NistP256 => SK_ECDSA_SHA2_P256,
Algorithm::SkEd25519 => SK_SSH_ED25519,
#[cfg(feature = "alloc")]
Algorithm::Other(algorithm) => algorithm.as_str(),
}
}

Expand All@@ -195,7 +214,7 @@ impl Algorithm {
/// See [PROTOCOL.certkeys] for more information.
///
/// [PROTOCOL.certkeys]: https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.certkeys?annotate=HEAD
pub fn as_certificate_str(self) -> &'static str {
pub fn as_certificate_str(&self) -> &str {
match self {
Algorithm::Dsa => CERT_DSA,
Algorithm::Ecdsa { curve } => match curve {
Expand All@@ -207,6 +226,8 @@ impl Algorithm {
Algorithm::Rsa { .. } => CERT_RSA,
Algorithm::SkEcdsaSha2NistP256 => CERT_SK_ECDSA_SHA2_P256,
Algorithm::SkEd25519 => CERT_SK_SSH_ED25519,
#[cfg(feature = "alloc")]
Algorithm::Other(algorithm) => algorithm.certificate_str(),
}
}

Expand DownExpand Up@@ -276,6 +297,9 @@ impl str::FromStr for Algorithm {
SSH_RSA => Ok(Algorithm::Rsa { hash: None }),
SK_ECDSA_SHA2_P256 => Ok(Algorithm::SkEcdsaSha2NistP256),
SK_SSH_ED25519 => Ok(Algorithm::SkEd25519),
#[cfg(feature = "alloc")]
_ => Ok(Algorithm::Other(AlgorithmName::from_str(id)?)),
#[cfg(not(feature = "alloc"))]
_ => Err(LabelError::new(id)),
}
}
Expand Down
109 changes: 109 additions & 0 deletions ssh-key/src/algorithm/name.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
use alloc::string::String;
use core::str::{self, FromStr};
use encoding::LabelError;

/// The suffix added to the `name` in a `name@domainname` algorithm string identifier.
const CERT_STR_SUFFIX: &str = "-cert-v01";

/// According to [RFC4251 § 6], algorithm names are ASCII strings that are at most 64
/// characters long.
///
/// [RFC4251 § 6]: https://www.rfc-editor.org/rfc/rfc4251.html#section-6
const MAX_ALGORITHM_NAME_LEN: usize = 64;

/// The maximum length of the certificate string identifier is [`MAX_ALGORITHM_NAME_LEN`] +
/// `"-cert-v01".len()` (the certificate identifier is obtained by inserting `"-cert-v01"` in the
/// algorithm name).
const MAX_CERT_STR_LEN: usize = MAX_ALGORITHM_NAME_LEN + CERT_STR_SUFFIX.len();

/// A string representing an additional algorithm name in the `name@domainname` format (see
/// [RFC4251 § 6]).
///
/// Additional algorithm names must be non-empty printable ASCII strings no longer than 64
/// characters.
///
/// This also provides a `name-cert-v01@domainnname` string identifier for the corresponding
/// OpenSSH certificate format, derived from the specified `name@domainname` string.
///
/// NOTE: RFC4251 specifies additional validation criteria for algorithm names, but we do not
/// implement all of them here.
///
/// [RFC4251 § 6]: https://www.rfc-editor.org/rfc/rfc4251.html#section-6
#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub struct AlgorithmName {
/// The string identifier which corresponds to this algorithm.
id: String,
/// The string identifier which corresponds to the OpenSSH certificate format.
///
/// This is derived from the algorithm name by inserting `"-cert-v01"` immediately after the
/// name preceding the at-symbol (`@`).
certificate_str: String,
}

impl AlgorithmName {
/// Get the string identifier which corresponds to this algorithm name.
pub fn as_str(&self) -> &str {
&self.id
}

/// Get the string identifier which corresponds to the OpenSSH certificate format.
pub fn certificate_str(&self) -> &str {
&self.certificate_str
}

/// Create a new [`AlgorithmName`] from an OpenSSH certificate format string identifier.
pub fn from_certificate_str(id: &str) -> Result<Self, LabelError> {
validate_algorithm_id(id, MAX_CERT_STR_LEN)?;

// Derive the algorithm name from the certificate format string identifier:
let (name, domain) = split_algorithm_id(id)?;
let name = name
.strip_suffix(CERT_STR_SUFFIX)
.ok_or_else(|| LabelError::new(id))?;

let algorithm_name = format!("{name}@{domain}");

Ok(Self {
id: algorithm_name,
certificate_str: id.into(),
})
}
}

impl FromStr for AlgorithmName {
type Err = LabelError;

fn from_str(id: &str) -> Result<Self, LabelError> {
validate_algorithm_id(id, MAX_ALGORITHM_NAME_LEN)?;

// Derive the certificate format string identifier from the algorithm name:
let (name, domain) = split_algorithm_id(id)?;
let certificate_str = format!("{name}{CERT_STR_SUFFIX}@{domain}");

Ok(Self {
id: id.into(),
certificate_str,
})
}
}

/// Check if the length of `id` is at most `n`, and that `id` only consists of ASCII characters.
fn validate_algorithm_id(id: &str, n: usize) -> Result<(), LabelError> {
if id.len() > n || !id.is_ascii() {
return Err(LabelError::new(id));
}

Ok(())
}

/// Split a `name@domainname` algorithm string identifier into `(name, domainname)`.
fn split_algorithm_id(id: &str) -> Result<(&str, &str), LabelError> {
let (name, domain) = id.split_once('@').ok_or_else(|| LabelError::new(id))?;

// TODO: validate name and domain_name according to the criteria from RFC4251
if name.is_empty() || domain.is_empty() || domain.contains('@') {
return Err(LabelError::new(id));
}

Ok((name, domain))
}
1 change: 1 addition & 0 deletions ssh-key/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -174,6 +174,7 @@ pub use sha2;

#[cfg(feature = "alloc")]
pub use crate::{
algorithm::AlgorithmName,
certificate::Certificate,
known_hosts::KnownHosts,
mpint::Mpint,
Expand Down
3 changes: 3 additions & 0 deletions ssh-key/src/private.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -111,6 +111,8 @@ mod ecdsa;
mod ed25519;
mod keypair;
#[cfg(feature = "alloc")]
mod opaque;
#[cfg(feature = "alloc")]
mod rsa;
#[cfg(feature = "alloc")]
mod sk;
Expand All@@ -124,6 +126,7 @@ pub use self::{
pub use crate::{
private::{
dsa::{DsaKeypair, DsaPrivateKey},
opaque::{OpaqueKeypair, OpaqueKeypairBytes, OpaquePrivateKeyBytes},
rsa::{RsaKeypair, RsaPrivateKey},
sk::SkEd25519,
},
Expand Down
37 changes: 36 additions & 1 deletion ssh-key/src/private/keypair.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,7 +7,7 @@ use subtle::{Choice, ConstantTimeEq};

#[cfg(feature = "alloc")]
use {
super::{DsaKeypair, RsaKeypair, SkEd25519},
super::{DsaKeypair, OpaqueKeypair, RsaKeypair, SkEd25519},
alloc::vec::Vec,
};

Expand DownExpand Up@@ -55,6 +55,10 @@ pub enum KeypairData {
/// [PROTOCOL.u2f]: https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.u2f?annotate=HEAD
#[cfg(feature = "alloc")]
SkEd25519(SkEd25519),

/// Opaque keypair.
#[cfg(feature = "alloc")]
Other(OpaqueKeypair),
}

impl KeypairData {
Expand All@@ -74,6 +78,8 @@ impl KeypairData {
Self::SkEcdsaSha2NistP256(_) => Algorithm::SkEcdsaSha2NistP256,
#[cfg(feature = "alloc")]
Self::SkEd25519(_) => Algorithm::SkEd25519,
#[cfg(feature = "alloc")]
Self::Other(key) => key.algorithm(),
})
}

Expand DownExpand Up@@ -140,6 +146,15 @@ impl KeypairData {
}
}

/// Get the custom, opaque private key if this key is the correct type.
#[cfg(feature = "alloc")]
pub fn other(&self) -> Option<&OpaqueKeypair> {
match self {
Self::Other(key) => Some(key),
_ => None,
}
}

/// Is this key a DSA key?
#[cfg(feature = "alloc")]
pub fn is_dsa(&self) -> bool {
Expand DownExpand Up@@ -187,6 +202,12 @@ impl KeypairData {
matches!(self, Self::SkEd25519(_))
}

/// Is this a key with a custom algorithm?
#[cfg(feature = "alloc")]
pub fn is_other(&self) -> bool {
matches!(self, Self::Other(_))
}

/// Compute a deterministic "checkint" for this private key.
///
/// This is a sort of primitive pseudo-MAC used by the OpenSSH key format.
Expand All@@ -206,6 +227,8 @@ impl KeypairData {
Self::SkEcdsaSha2NistP256(sk) => sk.key_handle(),
#[cfg(feature = "alloc")]
Self::SkEd25519(sk) => sk.key_handle(),
#[cfg(feature = "alloc")]
Self::Other(key) => key.private.as_ref(),
};

let mut n = 0u32;
Expand DownExpand Up@@ -243,6 +266,8 @@ impl ConstantTimeEq for KeypairData {
// The key structs contain all public data.
Choice::from((a == b) as u8)
}
#[cfg(feature = "alloc")]
(Self::Other(a), Self::Other(b)) => a.ct_eq(b),
#[allow(unreachable_patterns)]
_ => Choice::from(0),
}
Expand DownExpand Up@@ -278,6 +303,10 @@ impl Decode for KeypairData {
}
#[cfg(feature = "alloc")]
Algorithm::SkEd25519 => SkEd25519::decode(reader).map(Self::SkEd25519),
#[cfg(feature = "alloc")]
algorithm @ Algorithm::Other(_) => {
OpaqueKeypair::decode_as(reader, algorithm).map(Self::Other)
}
#[allow(unreachable_patterns)]
_ => Err(Error::AlgorithmUnknown),
}
Expand DownExpand Up@@ -307,6 +336,8 @@ impl Encode for KeypairData {
Self::SkEcdsaSha2NistP256(sk) => sk.encoded_len()?,
#[cfg(feature = "alloc")]
Self::SkEd25519(sk) => sk.encoded_len()?,
#[cfg(feature = "alloc")]
Self::Other(key) => key.encoded_len()?,
};

[alg_len, key_len].checked_sum()
Expand All@@ -331,6 +362,8 @@ impl Encode for KeypairData {
Self::SkEcdsaSha2NistP256(sk) => sk.encode(writer)?,
#[cfg(feature = "alloc")]
Self::SkEd25519(sk) => sk.encode(writer)?,
#[cfg(feature = "alloc")]
Self::Other(key) => key.encode(writer)?,
}

Ok(())
Expand All@@ -357,6 +390,8 @@ impl TryFrom<&KeypairData> for public::KeyData {
}
#[cfg(feature = "alloc")]
KeypairData::SkEd25519(sk) => public::KeyData::SkEd25519(sk.public().clone()),
#[cfg(feature = "alloc")]
KeypairData::Other(key) => public::KeyData::Other(key.into()),
})
}
}
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Support additional SSH key algorithms by gabi-250 · Pull Request #136 · RustCrypto/SSH · GitHub
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
2 changes: 1 addition & 1 deletion ssh-key/Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -46,7 +46,7 @@ default = ["ecdsa", "rand_core", "std"]
alloc = [
"encoding/alloc",
"signature/alloc",
"zeroize/alloc"
"zeroize/alloc",
]
std = [
"alloc",
Expand Down
30 changes: 27 additions & 3 deletions ssh-key/src/algorithm.rs
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
//! Algorithm support.

#[cfg(feature = "alloc")]
mod name;

use crate::{Error, Result};
use core::{fmt, str};
use encoding::{Label, LabelError};
Expand All@@ -10,6 +13,9 @@ use {
sha2::{Digest, Sha256, Sha512},
};

#[cfg(feature = "alloc")]
pub use name::AlgorithmName;

/// bcrypt-pbkdf
const BCRYPT: &str = "bcrypt";

Expand DownExpand Up@@ -80,7 +86,7 @@ const SK_SSH_ED25519: &str = "sk-ssh-ed25519@openssh.com";
///
/// This type provides a registry of supported digital signature algorithms
/// used for SSH keys.
#[derive(Copy, Clone, Debug, Default, Eq, Hash, PartialEq, PartialOrd, Ord)]
#[derive(Clone, Debug, Default, Eq, Hash, PartialEq, PartialOrd, Ord)]
#[non_exhaustive]
pub enum Algorithm {
/// Digital Signature Algorithm
Expand DownExpand Up@@ -113,6 +119,10 @@ pub enum Algorithm {

/// FIDO/U2F key with Ed25519
SkEd25519,

/// Other
#[cfg(feature = "alloc")]
Other(AlgorithmName),
}

impl Algorithm {
Expand All@@ -127,6 +137,8 @@ impl Algorithm {
/// - `ssh-rsa`
/// - `sk-ecdsa-sha2-nistp256@openssh.com` (FIDO/U2F key)
/// - `sk-ssh-ed25519@openssh.com` (FIDO/U2F key)
///
/// Any other algorithms are mapped to the [`Algorithm::Other`] variant.
pub fn new(id: &str) -> Result<Self> {
Ok(id.parse()?)
}
Expand All@@ -147,6 +159,8 @@ impl Algorithm {
/// - `sk-ecdsa-sha2-nistp256-cert-v01@openssh.com` (FIDO/U2F key)
/// - `sk-ssh-ed25519-cert-v01@openssh.com` (FIDO/U2F key)
///
/// Any other algorithms are mapped to the [`Algorithm::Other`] variant.
///
/// [PROTOCOL.certkeys]: https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.certkeys?annotate=HEAD
pub fn new_certificate(id: &str) -> Result<Self> {
match id {
Expand All@@ -164,12 +178,15 @@ impl Algorithm {
CERT_RSA => Ok(Algorithm::Rsa { hash: None }),
CERT_SK_ECDSA_SHA2_P256 => Ok(Algorithm::SkEcdsaSha2NistP256),
CERT_SK_SSH_ED25519 => Ok(Algorithm::SkEd25519),
#[cfg(feature = "alloc")]
_ => Ok(Algorithm::Other(AlgorithmName::from_certificate_str(id)?)),
#[cfg(not(feature = "alloc"))]
_ => Err(Error::AlgorithmUnknown),
}
}

/// Get the string identifier which corresponds to this algorithm.
pub fn as_str(self) -> &'static str {
pub fn as_str(&self) -> &str {
match self {
Algorithm::Dsa => SSH_DSA,
Algorithm::Ecdsa { curve } => match curve {
Expand All@@ -185,6 +202,8 @@ impl Algorithm {
},
Algorithm::SkEcdsaSha2NistP256 => SK_ECDSA_SHA2_P256,
Algorithm::SkEd25519 => SK_SSH_ED25519,
#[cfg(feature = "alloc")]
Algorithm::Other(algorithm) => algorithm.as_str(),
}
}

Expand All@@ -195,7 +214,7 @@ impl Algorithm {
/// See [PROTOCOL.certkeys] for more information.
///
/// [PROTOCOL.certkeys]: https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.certkeys?annotate=HEAD
pub fn as_certificate_str(self) -> &'static str {
pub fn as_certificate_str(&self) -> &str {
match self {
Algorithm::Dsa => CERT_DSA,
Algorithm::Ecdsa { curve } => match curve {
Expand All@@ -207,6 +226,8 @@ impl Algorithm {
Algorithm::Rsa { .. } => CERT_RSA,
Algorithm::SkEcdsaSha2NistP256 => CERT_SK_ECDSA_SHA2_P256,
Algorithm::SkEd25519 => CERT_SK_SSH_ED25519,
#[cfg(feature = "alloc")]
Algorithm::Other(algorithm) => algorithm.certificate_str(),
}
}

Expand DownExpand Up@@ -276,6 +297,9 @@ impl str::FromStr for Algorithm {
SSH_RSA => Ok(Algorithm::Rsa { hash: None }),
SK_ECDSA_SHA2_P256 => Ok(Algorithm::SkEcdsaSha2NistP256),
SK_SSH_ED25519 => Ok(Algorithm::SkEd25519),
#[cfg(feature = "alloc")]
_ => Ok(Algorithm::Other(AlgorithmName::from_str(id)?)),
#[cfg(not(feature = "alloc"))]
_ => Err(LabelError::new(id)),
}
}
Expand Down
109 changes: 109 additions & 0 deletions ssh-key/src/algorithm/name.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
use alloc::string::String;
use core::str::{self, FromStr};
use encoding::LabelError;

/// The suffix added to the `name` in a `name@domainname` algorithm string identifier.
const CERT_STR_SUFFIX: &str = "-cert-v01";

/// According to [RFC4251 § 6], algorithm names are ASCII strings that are at most 64
/// characters long.
///
/// [RFC4251 § 6]: https://www.rfc-editor.org/rfc/rfc4251.html#section-6
const MAX_ALGORITHM_NAME_LEN: usize = 64;

/// The maximum length of the certificate string identifier is [`MAX_ALGORITHM_NAME_LEN`] +
/// `"-cert-v01".len()` (the certificate identifier is obtained by inserting `"-cert-v01"` in the
/// algorithm name).
const MAX_CERT_STR_LEN: usize = MAX_ALGORITHM_NAME_LEN + CERT_STR_SUFFIX.len();

/// A string representing an additional algorithm name in the `name@domainname` format (see
/// [RFC4251 § 6]).
///
/// Additional algorithm names must be non-empty printable ASCII strings no longer than 64
/// characters.
///
/// This also provides a `name-cert-v01@domainnname` string identifier for the corresponding
/// OpenSSH certificate format, derived from the specified `name@domainname` string.
///
/// NOTE: RFC4251 specifies additional validation criteria for algorithm names, but we do not
/// implement all of them here.
///
/// [RFC4251 § 6]: https://www.rfc-editor.org/rfc/rfc4251.html#section-6
#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub struct AlgorithmName {
/// The string identifier which corresponds to this algorithm.
id: String,
/// The string identifier which corresponds to the OpenSSH certificate format.
///
/// This is derived from the algorithm name by inserting `"-cert-v01"` immediately after the
/// name preceding the at-symbol (`@`).
certificate_str: String,
}

impl AlgorithmName {
/// Get the string identifier which corresponds to this algorithm name.
pub fn as_str(&self) -> &str {
&self.id
}

/// Get the string identifier which corresponds to the OpenSSH certificate format.
pub fn certificate_str(&self) -> &str {
&self.certificate_str
}

/// Create a new [`AlgorithmName`] from an OpenSSH certificate format string identifier.
pub fn from_certificate_str(id: &str) -> Result<Self, LabelError> {
validate_algorithm_id(id, MAX_CERT_STR_LEN)?;

// Derive the algorithm name from the certificate format string identifier:
let (name, domain) = split_algorithm_id(id)?;
let name = name
.strip_suffix(CERT_STR_SUFFIX)
.ok_or_else(|| LabelError::new(id))?;

let algorithm_name = format!("{name}@{domain}");

Ok(Self {
id: algorithm_name,
certificate_str: id.into(),
})
}
}

impl FromStr for AlgorithmName {
type Err = LabelError;

fn from_str(id: &str) -> Result<Self, LabelError> {
validate_algorithm_id(id, MAX_ALGORITHM_NAME_LEN)?;

// Derive the certificate format string identifier from the algorithm name:
let (name, domain) = split_algorithm_id(id)?;
let certificate_str = format!("{name}{CERT_STR_SUFFIX}@{domain}");

Ok(Self {
id: id.into(),
certificate_str,
})
}
}

/// Check if the length of `id` is at most `n`, and that `id` only consists of ASCII characters.
fn validate_algorithm_id(id: &str, n: usize) -> Result<(), LabelError> {
if id.len() > n || !id.is_ascii() {
return Err(LabelError::new(id));
}

Ok(())
}

/// Split a `name@domainname` algorithm string identifier into `(name, domainname)`.
fn split_algorithm_id(id: &str) -> Result<(&str, &str), LabelError> {
let (name, domain) = id.split_once('@').ok_or_else(|| LabelError::new(id))?;

// TODO: validate name and domain_name according to the criteria from RFC4251
if name.is_empty() || domain.is_empty() || domain.contains('@') {
return Err(LabelError::new(id));
}

Ok((name, domain))
}
1 change: 1 addition & 0 deletions ssh-key/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -174,6 +174,7 @@ pub use sha2;

#[cfg(feature = "alloc")]
pub use crate::{
algorithm::AlgorithmName,
certificate::Certificate,
known_hosts::KnownHosts,
mpint::Mpint,
Expand Down
3 changes: 3 additions & 0 deletions ssh-key/src/private.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -111,6 +111,8 @@ mod ecdsa;
mod ed25519;
mod keypair;
#[cfg(feature = "alloc")]
mod opaque;
#[cfg(feature = "alloc")]
mod rsa;
#[cfg(feature = "alloc")]
mod sk;
Expand All@@ -124,6 +126,7 @@ pub use self::{
pub use crate::{
private::{
dsa::{DsaKeypair, DsaPrivateKey},
opaque::{OpaqueKeypair, OpaqueKeypairBytes, OpaquePrivateKeyBytes},
rsa::{RsaKeypair, RsaPrivateKey},
sk::SkEd25519,
},
Expand Down
37 changes: 36 additions & 1 deletion ssh-key/src/private/keypair.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,7 +7,7 @@ use subtle::{Choice, ConstantTimeEq};

#[cfg(feature = "alloc")]
use {
super::{DsaKeypair, RsaKeypair, SkEd25519},
super::{DsaKeypair, OpaqueKeypair, RsaKeypair, SkEd25519},
alloc::vec::Vec,
};

Expand DownExpand Up@@ -55,6 +55,10 @@ pub enum KeypairData {
/// [PROTOCOL.u2f]: https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.u2f?annotate=HEAD
#[cfg(feature = "alloc")]
SkEd25519(SkEd25519),

/// Opaque keypair.
#[cfg(feature = "alloc")]
Other(OpaqueKeypair),
}

impl KeypairData {
Expand All@@ -74,6 +78,8 @@ impl KeypairData {
Self::SkEcdsaSha2NistP256(_) => Algorithm::SkEcdsaSha2NistP256,
#[cfg(feature = "alloc")]
Self::SkEd25519(_) => Algorithm::SkEd25519,
#[cfg(feature = "alloc")]
Self::Other(key) => key.algorithm(),
})
}

Expand DownExpand Up@@ -140,6 +146,15 @@ impl KeypairData {
}
}

/// Get the custom, opaque private key if this key is the correct type.
#[cfg(feature = "alloc")]
pub fn other(&self) -> Option<&OpaqueKeypair> {
match self {
Self::Other(key) => Some(key),
_ => None,
}
}

/// Is this key a DSA key?
#[cfg(feature = "alloc")]
pub fn is_dsa(&self) -> bool {
Expand DownExpand Up@@ -187,6 +202,12 @@ impl KeypairData {
matches!(self, Self::SkEd25519(_))
}

/// Is this a key with a custom algorithm?
#[cfg(feature = "alloc")]
pub fn is_other(&self) -> bool {
matches!(self, Self::Other(_))
}

/// Compute a deterministic "checkint" for this private key.
///
/// This is a sort of primitive pseudo-MAC used by the OpenSSH key format.
Expand All@@ -206,6 +227,8 @@ impl KeypairData {
Self::SkEcdsaSha2NistP256(sk) => sk.key_handle(),
#[cfg(feature = "alloc")]
Self::SkEd25519(sk) => sk.key_handle(),
#[cfg(feature = "alloc")]
Self::Other(key) => key.private.as_ref(),
};

let mut n = 0u32;
Expand DownExpand Up@@ -243,6 +266,8 @@ impl ConstantTimeEq for KeypairData {
// The key structs contain all public data.
Choice::from((a == b) as u8)
}
#[cfg(feature = "alloc")]
(Self::Other(a), Self::Other(b)) => a.ct_eq(b),
#[allow(unreachable_patterns)]
_ => Choice::from(0),
}
Expand DownExpand Up@@ -278,6 +303,10 @@ impl Decode for KeypairData {
}
#[cfg(feature = "alloc")]
Algorithm::SkEd25519 => SkEd25519::decode(reader).map(Self::SkEd25519),
#[cfg(feature = "alloc")]
algorithm @ Algorithm::Other(_) => {
OpaqueKeypair::decode_as(reader, algorithm).map(Self::Other)
}
#[allow(unreachable_patterns)]
_ => Err(Error::AlgorithmUnknown),
}
Expand DownExpand Up@@ -307,6 +336,8 @@ impl Encode for KeypairData {
Self::SkEcdsaSha2NistP256(sk) => sk.encoded_len()?,
#[cfg(feature = "alloc")]
Self::SkEd25519(sk) => sk.encoded_len()?,
#[cfg(feature = "alloc")]
Self::Other(key) => key.encoded_len()?,
};

[alg_len, key_len].checked_sum()
Expand All@@ -331,6 +362,8 @@ impl Encode for KeypairData {
Self::SkEcdsaSha2NistP256(sk) => sk.encode(writer)?,
#[cfg(feature = "alloc")]
Self::SkEd25519(sk) => sk.encode(writer)?,
#[cfg(feature = "alloc")]
Self::Other(key) => key.encode(writer)?,
}

Ok(())
Expand All@@ -357,6 +390,8 @@ impl TryFrom<&KeypairData> for public::KeyData {
}
#[cfg(feature = "alloc")]
KeypairData::SkEd25519(sk) => public::KeyData::SkEd25519(sk.public().clone()),
#[cfg(feature = "alloc")]
KeypairData::Other(key) => public::KeyData::Other(key.into()),
})
}
}
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Support additional SSH key algorithms by gabi-250 · Pull Request #136 · RustCrypto/SSH · GitHub
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
2 changes: 1 addition & 1 deletion ssh-key/Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -46,7 +46,7 @@ default = ["ecdsa", "rand_core", "std"]
alloc = [
"encoding/alloc",
"signature/alloc",
"zeroize/alloc"
"zeroize/alloc",
]
std = [
"alloc",
Expand Down
30 changes: 27 additions & 3 deletions ssh-key/src/algorithm.rs
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
//! Algorithm support.

#[cfg(feature = "alloc")]
mod name;

use crate::{Error, Result};
use core::{fmt, str};
use encoding::{Label, LabelError};
Expand All@@ -10,6 +13,9 @@ use {
sha2::{Digest, Sha256, Sha512},
};

#[cfg(feature = "alloc")]
pub use name::AlgorithmName;

/// bcrypt-pbkdf
const BCRYPT: &str = "bcrypt";

Expand DownExpand Up@@ -80,7 +86,7 @@ const SK_SSH_ED25519: &str = "sk-ssh-ed25519@openssh.com";
///
/// This type provides a registry of supported digital signature algorithms
/// used for SSH keys.
#[derive(Copy, Clone, Debug, Default, Eq, Hash, PartialEq, PartialOrd, Ord)]
#[derive(Clone, Debug, Default, Eq, Hash, PartialEq, PartialOrd, Ord)]
#[non_exhaustive]
pub enum Algorithm {
/// Digital Signature Algorithm
Expand DownExpand Up@@ -113,6 +119,10 @@ pub enum Algorithm {

/// FIDO/U2F key with Ed25519
SkEd25519,

/// Other
#[cfg(feature = "alloc")]
Other(AlgorithmName),
}

impl Algorithm {
Expand All@@ -127,6 +137,8 @@ impl Algorithm {
/// - `ssh-rsa`
/// - `sk-ecdsa-sha2-nistp256@openssh.com` (FIDO/U2F key)
/// - `sk-ssh-ed25519@openssh.com` (FIDO/U2F key)
///
/// Any other algorithms are mapped to the [`Algorithm::Other`] variant.
pub fn new(id: &str) -> Result<Self> {
Ok(id.parse()?)
}
Expand All@@ -147,6 +159,8 @@ impl Algorithm {
/// - `sk-ecdsa-sha2-nistp256-cert-v01@openssh.com` (FIDO/U2F key)
/// - `sk-ssh-ed25519-cert-v01@openssh.com` (FIDO/U2F key)
///
/// Any other algorithms are mapped to the [`Algorithm::Other`] variant.
///
/// [PROTOCOL.certkeys]: https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.certkeys?annotate=HEAD
pub fn new_certificate(id: &str) -> Result<Self> {
match id {
Expand All@@ -164,12 +178,15 @@ impl Algorithm {
CERT_RSA => Ok(Algorithm::Rsa { hash: None }),
CERT_SK_ECDSA_SHA2_P256 => Ok(Algorithm::SkEcdsaSha2NistP256),
CERT_SK_SSH_ED25519 => Ok(Algorithm::SkEd25519),
#[cfg(feature = "alloc")]
_ => Ok(Algorithm::Other(AlgorithmName::from_certificate_str(id)?)),
#[cfg(not(feature = "alloc"))]
_ => Err(Error::AlgorithmUnknown),
}
}

/// Get the string identifier which corresponds to this algorithm.
pub fn as_str(self) -> &'static str {
pub fn as_str(&self) -> &str {
match self {
Algorithm::Dsa => SSH_DSA,
Algorithm::Ecdsa { curve } => match curve {
Expand All@@ -185,6 +202,8 @@ impl Algorithm {
},
Algorithm::SkEcdsaSha2NistP256 => SK_ECDSA_SHA2_P256,
Algorithm::SkEd25519 => SK_SSH_ED25519,
#[cfg(feature = "alloc")]
Algorithm::Other(algorithm) => algorithm.as_str(),
}
}

Expand All@@ -195,7 +214,7 @@ impl Algorithm {
/// See [PROTOCOL.certkeys] for more information.
///
/// [PROTOCOL.certkeys]: https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.certkeys?annotate=HEAD
pub fn as_certificate_str(self) -> &'static str {
pub fn as_certificate_str(&self) -> &str {
match self {
Algorithm::Dsa => CERT_DSA,
Algorithm::Ecdsa { curve } => match curve {
Expand All@@ -207,6 +226,8 @@ impl Algorithm {
Algorithm::Rsa { .. } => CERT_RSA,
Algorithm::SkEcdsaSha2NistP256 => CERT_SK_ECDSA_SHA2_P256,
Algorithm::SkEd25519 => CERT_SK_SSH_ED25519,
#[cfg(feature = "alloc")]
Algorithm::Other(algorithm) => algorithm.certificate_str(),
}
}

Expand DownExpand Up@@ -276,6 +297,9 @@ impl str::FromStr for Algorithm {
SSH_RSA => Ok(Algorithm::Rsa { hash: None }),
SK_ECDSA_SHA2_P256 => Ok(Algorithm::SkEcdsaSha2NistP256),
SK_SSH_ED25519 => Ok(Algorithm::SkEd25519),
#[cfg(feature = "alloc")]
_ => Ok(Algorithm::Other(AlgorithmName::from_str(id)?)),
#[cfg(not(feature = "alloc"))]
_ => Err(LabelError::new(id)),
}
}
Expand Down
109 changes: 109 additions & 0 deletions ssh-key/src/algorithm/name.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
use alloc::string::String;
use core::str::{self, FromStr};
use encoding::LabelError;

/// The suffix added to the `name` in a `name@domainname` algorithm string identifier.
const CERT_STR_SUFFIX: &str = "-cert-v01";

/// According to [RFC4251 § 6], algorithm names are ASCII strings that are at most 64
/// characters long.
///
/// [RFC4251 § 6]: https://www.rfc-editor.org/rfc/rfc4251.html#section-6
const MAX_ALGORITHM_NAME_LEN: usize = 64;

/// The maximum length of the certificate string identifier is [`MAX_ALGORITHM_NAME_LEN`] +
/// `"-cert-v01".len()` (the certificate identifier is obtained by inserting `"-cert-v01"` in the
/// algorithm name).
const MAX_CERT_STR_LEN: usize = MAX_ALGORITHM_NAME_LEN + CERT_STR_SUFFIX.len();

/// A string representing an additional algorithm name in the `name@domainname` format (see
/// [RFC4251 § 6]).
///
/// Additional algorithm names must be non-empty printable ASCII strings no longer than 64
/// characters.
///
/// This also provides a `name-cert-v01@domainnname` string identifier for the corresponding
/// OpenSSH certificate format, derived from the specified `name@domainname` string.
///
/// NOTE: RFC4251 specifies additional validation criteria for algorithm names, but we do not
/// implement all of them here.
///
/// [RFC4251 § 6]: https://www.rfc-editor.org/rfc/rfc4251.html#section-6
#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub struct AlgorithmName {
/// The string identifier which corresponds to this algorithm.
id: String,
/// The string identifier which corresponds to the OpenSSH certificate format.
///
/// This is derived from the algorithm name by inserting `"-cert-v01"` immediately after the
/// name preceding the at-symbol (`@`).
certificate_str: String,
}

impl AlgorithmName {
/// Get the string identifier which corresponds to this algorithm name.
pub fn as_str(&self) -> &str {
&self.id
}

/// Get the string identifier which corresponds to the OpenSSH certificate format.
pub fn certificate_str(&self) -> &str {
&self.certificate_str
}

/// Create a new [`AlgorithmName`] from an OpenSSH certificate format string identifier.
pub fn from_certificate_str(id: &str) -> Result<Self, LabelError> {
validate_algorithm_id(id, MAX_CERT_STR_LEN)?;

// Derive the algorithm name from the certificate format string identifier:
let (name, domain) = split_algorithm_id(id)?;
let name = name
.strip_suffix(CERT_STR_SUFFIX)
.ok_or_else(|| LabelError::new(id))?;

let algorithm_name = format!("{name}@{domain}");

Ok(Self {
id: algorithm_name,
certificate_str: id.into(),
})
}
}

impl FromStr for AlgorithmName {
type Err = LabelError;

fn from_str(id: &str) -> Result<Self, LabelError> {
validate_algorithm_id(id, MAX_ALGORITHM_NAME_LEN)?;

// Derive the certificate format string identifier from the algorithm name:
let (name, domain) = split_algorithm_id(id)?;
let certificate_str = format!("{name}{CERT_STR_SUFFIX}@{domain}");

Ok(Self {
id: id.into(),
certificate_str,
})
}
}

/// Check if the length of `id` is at most `n`, and that `id` only consists of ASCII characters.
fn validate_algorithm_id(id: &str, n: usize) -> Result<(), LabelError> {
if id.len() > n || !id.is_ascii() {
return Err(LabelError::new(id));
}

Ok(())
}

/// Split a `name@domainname` algorithm string identifier into `(name, domainname)`.
fn split_algorithm_id(id: &str) -> Result<(&str, &str), LabelError> {
let (name, domain) = id.split_once('@').ok_or_else(|| LabelError::new(id))?;

// TODO: validate name and domain_name according to the criteria from RFC4251
if name.is_empty() || domain.is_empty() || domain.contains('@') {
return Err(LabelError::new(id));
}

Ok((name, domain))
}
1 change: 1 addition & 0 deletions ssh-key/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -174,6 +174,7 @@ pub use sha2;

#[cfg(feature = "alloc")]
pub use crate::{
algorithm::AlgorithmName,
certificate::Certificate,
known_hosts::KnownHosts,
mpint::Mpint,
Expand Down
3 changes: 3 additions & 0 deletions ssh-key/src/private.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -111,6 +111,8 @@ mod ecdsa;
mod ed25519;
mod keypair;
#[cfg(feature = "alloc")]
mod opaque;
#[cfg(feature = "alloc")]
mod rsa;
#[cfg(feature = "alloc")]
mod sk;
Expand All@@ -124,6 +126,7 @@ pub use self::{
pub use crate::{
private::{
dsa::{DsaKeypair, DsaPrivateKey},
opaque::{OpaqueKeypair, OpaqueKeypairBytes, OpaquePrivateKeyBytes},
rsa::{RsaKeypair, RsaPrivateKey},
sk::SkEd25519,
},
Expand Down
37 changes: 36 additions & 1 deletion ssh-key/src/private/keypair.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,7 +7,7 @@ use subtle::{Choice, ConstantTimeEq};

#[cfg(feature = "alloc")]
use {
super::{DsaKeypair, RsaKeypair, SkEd25519},
super::{DsaKeypair, OpaqueKeypair, RsaKeypair, SkEd25519},
alloc::vec::Vec,
};

Expand DownExpand Up@@ -55,6 +55,10 @@ pub enum KeypairData {
/// [PROTOCOL.u2f]: https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.u2f?annotate=HEAD
#[cfg(feature = "alloc")]
SkEd25519(SkEd25519),

/// Opaque keypair.
#[cfg(feature = "alloc")]
Other(OpaqueKeypair),
}

impl KeypairData {
Expand All@@ -74,6 +78,8 @@ impl KeypairData {
Self::SkEcdsaSha2NistP256(_) => Algorithm::SkEcdsaSha2NistP256,
#[cfg(feature = "alloc")]
Self::SkEd25519(_) => Algorithm::SkEd25519,
#[cfg(feature = "alloc")]
Self::Other(key) => key.algorithm(),
})
}

Expand DownExpand Up@@ -140,6 +146,15 @@ impl KeypairData {
}
}

/// Get the custom, opaque private key if this key is the correct type.
#[cfg(feature = "alloc")]
pub fn other(&self) -> Option<&OpaqueKeypair> {
match self {
Self::Other(key) => Some(key),
_ => None,
}
}

/// Is this key a DSA key?
#[cfg(feature = "alloc")]
pub fn is_dsa(&self) -> bool {
Expand DownExpand Up@@ -187,6 +202,12 @@ impl KeypairData {
matches!(self, Self::SkEd25519(_))
}

/// Is this a key with a custom algorithm?
#[cfg(feature = "alloc")]
pub fn is_other(&self) -> bool {
matches!(self, Self::Other(_))
}

/// Compute a deterministic "checkint" for this private key.
///
/// This is a sort of primitive pseudo-MAC used by the OpenSSH key format.
Expand All@@ -206,6 +227,8 @@ impl KeypairData {
Self::SkEcdsaSha2NistP256(sk) => sk.key_handle(),
#[cfg(feature = "alloc")]
Self::SkEd25519(sk) => sk.key_handle(),
#[cfg(feature = "alloc")]
Self::Other(key) => key.private.as_ref(),
};

let mut n = 0u32;
Expand DownExpand Up@@ -243,6 +266,8 @@ impl ConstantTimeEq for KeypairData {
// The key structs contain all public data.
Choice::from((a == b) as u8)
}
#[cfg(feature = "alloc")]
(Self::Other(a), Self::Other(b)) => a.ct_eq(b),
#[allow(unreachable_patterns)]
_ => Choice::from(0),
}
Expand DownExpand Up@@ -278,6 +303,10 @@ impl Decode for KeypairData {
}
#[cfg(feature = "alloc")]
Algorithm::SkEd25519 => SkEd25519::decode(reader).map(Self::SkEd25519),
#[cfg(feature = "alloc")]
algorithm @ Algorithm::Other(_) => {
OpaqueKeypair::decode_as(reader, algorithm).map(Self::Other)
}
#[allow(unreachable_patterns)]
_ => Err(Error::AlgorithmUnknown),
}
Expand DownExpand Up@@ -307,6 +336,8 @@ impl Encode for KeypairData {
Self::SkEcdsaSha2NistP256(sk) => sk.encoded_len()?,
#[cfg(feature = "alloc")]
Self::SkEd25519(sk) => sk.encoded_len()?,
#[cfg(feature = "alloc")]
Self::Other(key) => key.encoded_len()?,
};

[alg_len, key_len].checked_sum()
Expand All@@ -331,6 +362,8 @@ impl Encode for KeypairData {
Self::SkEcdsaSha2NistP256(sk) => sk.encode(writer)?,
#[cfg(feature = "alloc")]
Self::SkEd25519(sk) => sk.encode(writer)?,
#[cfg(feature = "alloc")]
Self::Other(key) => key.encode(writer)?,
}

Ok(())
Expand All@@ -357,6 +390,8 @@ impl TryFrom<&KeypairData> for public::KeyData {
}
#[cfg(feature = "alloc")]
KeypairData::SkEd25519(sk) => public::KeyData::SkEd25519(sk.public().clone()),
#[cfg(feature = "alloc")]
KeypairData::Other(key) => public::KeyData::Other(key.into()),
})
}
}
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Support additional SSH key algorithms by gabi-250 · Pull Request #136 · RustCrypto/SSH · GitHub
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
2 changes: 1 addition & 1 deletion ssh-key/Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -46,7 +46,7 @@ default = ["ecdsa", "rand_core", "std"]
alloc = [
"encoding/alloc",
"signature/alloc",
"zeroize/alloc"
"zeroize/alloc",
]
std = [
"alloc",
Expand Down
30 changes: 27 additions & 3 deletions ssh-key/src/algorithm.rs
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
//! Algorithm support.

#[cfg(feature = "alloc")]
mod name;

use crate::{Error, Result};
use core::{fmt, str};
use encoding::{Label, LabelError};
Expand All@@ -10,6 +13,9 @@ use {
sha2::{Digest, Sha256, Sha512},
};

#[cfg(feature = "alloc")]
pub use name::AlgorithmName;

/// bcrypt-pbkdf
const BCRYPT: &str = "bcrypt";

Expand DownExpand Up@@ -80,7 +86,7 @@ const SK_SSH_ED25519: &str = "sk-ssh-ed25519@openssh.com";
///
/// This type provides a registry of supported digital signature algorithms
/// used for SSH keys.
#[derive(Copy, Clone, Debug, Default, Eq, Hash, PartialEq, PartialOrd, Ord)]
#[derive(Clone, Debug, Default, Eq, Hash, PartialEq, PartialOrd, Ord)]
#[non_exhaustive]
pub enum Algorithm {
/// Digital Signature Algorithm
Expand DownExpand Up@@ -113,6 +119,10 @@ pub enum Algorithm {

/// FIDO/U2F key with Ed25519
SkEd25519,

/// Other
#[cfg(feature = "alloc")]
Other(AlgorithmName),
}

impl Algorithm {
Expand All@@ -127,6 +137,8 @@ impl Algorithm {
/// - `ssh-rsa`
/// - `sk-ecdsa-sha2-nistp256@openssh.com` (FIDO/U2F key)
/// - `sk-ssh-ed25519@openssh.com` (FIDO/U2F key)
///
/// Any other algorithms are mapped to the [`Algorithm::Other`] variant.
pub fn new(id: &str) -> Result<Self> {
Ok(id.parse()?)
}
Expand All@@ -147,6 +159,8 @@ impl Algorithm {
/// - `sk-ecdsa-sha2-nistp256-cert-v01@openssh.com` (FIDO/U2F key)
/// - `sk-ssh-ed25519-cert-v01@openssh.com` (FIDO/U2F key)
///
/// Any other algorithms are mapped to the [`Algorithm::Other`] variant.
///
/// [PROTOCOL.certkeys]: https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.certkeys?annotate=HEAD
pub fn new_certificate(id: &str) -> Result<Self> {
match id {
Expand All@@ -164,12 +178,15 @@ impl Algorithm {
CERT_RSA => Ok(Algorithm::Rsa { hash: None }),
CERT_SK_ECDSA_SHA2_P256 => Ok(Algorithm::SkEcdsaSha2NistP256),
CERT_SK_SSH_ED25519 => Ok(Algorithm::SkEd25519),
#[cfg(feature = "alloc")]
_ => Ok(Algorithm::Other(AlgorithmName::from_certificate_str(id)?)),
#[cfg(not(feature = "alloc"))]
_ => Err(Error::AlgorithmUnknown),
}
}

/// Get the string identifier which corresponds to this algorithm.
pub fn as_str(self) -> &'static str {
pub fn as_str(&self) -> &str {
match self {
Algorithm::Dsa => SSH_DSA,
Algorithm::Ecdsa { curve } => match curve {
Expand All@@ -185,6 +202,8 @@ impl Algorithm {
},
Algorithm::SkEcdsaSha2NistP256 => SK_ECDSA_SHA2_P256,
Algorithm::SkEd25519 => SK_SSH_ED25519,
#[cfg(feature = "alloc")]
Algorithm::Other(algorithm) => algorithm.as_str(),
}
}

Expand All@@ -195,7 +214,7 @@ impl Algorithm {
/// See [PROTOCOL.certkeys] for more information.
///
/// [PROTOCOL.certkeys]: https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.certkeys?annotate=HEAD
pub fn as_certificate_str(self) -> &'static str {
pub fn as_certificate_str(&self) -> &str {
match self {
Algorithm::Dsa => CERT_DSA,
Algorithm::Ecdsa { curve } => match curve {
Expand All@@ -207,6 +226,8 @@ impl Algorithm {
Algorithm::Rsa { .. } => CERT_RSA,
Algorithm::SkEcdsaSha2NistP256 => CERT_SK_ECDSA_SHA2_P256,
Algorithm::SkEd25519 => CERT_SK_SSH_ED25519,
#[cfg(feature = "alloc")]
Algorithm::Other(algorithm) => algorithm.certificate_str(),
}
}

Expand DownExpand Up@@ -276,6 +297,9 @@ impl str::FromStr for Algorithm {
SSH_RSA => Ok(Algorithm::Rsa { hash: None }),
SK_ECDSA_SHA2_P256 => Ok(Algorithm::SkEcdsaSha2NistP256),
SK_SSH_ED25519 => Ok(Algorithm::SkEd25519),
#[cfg(feature = "alloc")]
_ => Ok(Algorithm::Other(AlgorithmName::from_str(id)?)),
#[cfg(not(feature = "alloc"))]
_ => Err(LabelError::new(id)),
}
}
Expand Down
109 changes: 109 additions & 0 deletions ssh-key/src/algorithm/name.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
use alloc::string::String;
use core::str::{self, FromStr};
use encoding::LabelError;

/// The suffix added to the `name` in a `name@domainname` algorithm string identifier.
const CERT_STR_SUFFIX: &str = "-cert-v01";

/// According to [RFC4251 § 6], algorithm names are ASCII strings that are at most 64
/// characters long.
///
/// [RFC4251 § 6]: https://www.rfc-editor.org/rfc/rfc4251.html#section-6
const MAX_ALGORITHM_NAME_LEN: usize = 64;

/// The maximum length of the certificate string identifier is [`MAX_ALGORITHM_NAME_LEN`] +
/// `"-cert-v01".len()` (the certificate identifier is obtained by inserting `"-cert-v01"` in the
/// algorithm name).
const MAX_CERT_STR_LEN: usize = MAX_ALGORITHM_NAME_LEN + CERT_STR_SUFFIX.len();

/// A string representing an additional algorithm name in the `name@domainname` format (see
/// [RFC4251 § 6]).
///
/// Additional algorithm names must be non-empty printable ASCII strings no longer than 64
/// characters.
///
/// This also provides a `name-cert-v01@domainnname` string identifier for the corresponding
/// OpenSSH certificate format, derived from the specified `name@domainname` string.
///
/// NOTE: RFC4251 specifies additional validation criteria for algorithm names, but we do not
/// implement all of them here.
///
/// [RFC4251 § 6]: https://www.rfc-editor.org/rfc/rfc4251.html#section-6
#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub struct AlgorithmName {
/// The string identifier which corresponds to this algorithm.
id: String,
/// The string identifier which corresponds to the OpenSSH certificate format.
///
/// This is derived from the algorithm name by inserting `"-cert-v01"` immediately after the
/// name preceding the at-symbol (`@`).
certificate_str: String,
}

impl AlgorithmName {
/// Get the string identifier which corresponds to this algorithm name.
pub fn as_str(&self) -> &str {
&self.id
}

/// Get the string identifier which corresponds to the OpenSSH certificate format.
pub fn certificate_str(&self) -> &str {
&self.certificate_str
}

/// Create a new [`AlgorithmName`] from an OpenSSH certificate format string identifier.
pub fn from_certificate_str(id: &str) -> Result<Self, LabelError> {
validate_algorithm_id(id, MAX_CERT_STR_LEN)?;

// Derive the algorithm name from the certificate format string identifier:
let (name, domain) = split_algorithm_id(id)?;
let name = name
.strip_suffix(CERT_STR_SUFFIX)
.ok_or_else(|| LabelError::new(id))?;

let algorithm_name = format!("{name}@{domain}");

Ok(Self {
id: algorithm_name,
certificate_str: id.into(),
})
}
}

impl FromStr for AlgorithmName {
type Err = LabelError;

fn from_str(id: &str) -> Result<Self, LabelError> {
validate_algorithm_id(id, MAX_ALGORITHM_NAME_LEN)?;

// Derive the certificate format string identifier from the algorithm name:
let (name, domain) = split_algorithm_id(id)?;
let certificate_str = format!("{name}{CERT_STR_SUFFIX}@{domain}");

Ok(Self {
id: id.into(),
certificate_str,
})
}
}

/// Check if the length of `id` is at most `n`, and that `id` only consists of ASCII characters.
fn validate_algorithm_id(id: &str, n: usize) -> Result<(), LabelError> {
if id.len() > n || !id.is_ascii() {
return Err(LabelError::new(id));
}

Ok(())
}

/// Split a `name@domainname` algorithm string identifier into `(name, domainname)`.
fn split_algorithm_id(id: &str) -> Result<(&str, &str), LabelError> {
let (name, domain) = id.split_once('@').ok_or_else(|| LabelError::new(id))?;

// TODO: validate name and domain_name according to the criteria from RFC4251
if name.is_empty() || domain.is_empty() || domain.contains('@') {
return Err(LabelError::new(id));
}

Ok((name, domain))
}
1 change: 1 addition & 0 deletions ssh-key/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -174,6 +174,7 @@ pub use sha2;

#[cfg(feature = "alloc")]
pub use crate::{
algorithm::AlgorithmName,
certificate::Certificate,
known_hosts::KnownHosts,
mpint::Mpint,
Expand Down
3 changes: 3 additions & 0 deletions ssh-key/src/private.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -111,6 +111,8 @@ mod ecdsa;
mod ed25519;
mod keypair;
#[cfg(feature = "alloc")]
mod opaque;
#[cfg(feature = "alloc")]
mod rsa;
#[cfg(feature = "alloc")]
mod sk;
Expand All@@ -124,6 +126,7 @@ pub use self::{
pub use crate::{
private::{
dsa::{DsaKeypair, DsaPrivateKey},
opaque::{OpaqueKeypair, OpaqueKeypairBytes, OpaquePrivateKeyBytes},
rsa::{RsaKeypair, RsaPrivateKey},
sk::SkEd25519,
},
Expand Down
37 changes: 36 additions & 1 deletion ssh-key/src/private/keypair.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,7 +7,7 @@ use subtle::{Choice, ConstantTimeEq};

#[cfg(feature = "alloc")]
use {
super::{DsaKeypair, RsaKeypair, SkEd25519},
super::{DsaKeypair, OpaqueKeypair, RsaKeypair, SkEd25519},
alloc::vec::Vec,
};

Expand DownExpand Up@@ -55,6 +55,10 @@ pub enum KeypairData {
/// [PROTOCOL.u2f]: https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.u2f?annotate=HEAD
#[cfg(feature = "alloc")]
SkEd25519(SkEd25519),

/// Opaque keypair.
#[cfg(feature = "alloc")]
Other(OpaqueKeypair),
}

impl KeypairData {
Expand All@@ -74,6 +78,8 @@ impl KeypairData {
Self::SkEcdsaSha2NistP256(_) => Algorithm::SkEcdsaSha2NistP256,
#[cfg(feature = "alloc")]
Self::SkEd25519(_) => Algorithm::SkEd25519,
#[cfg(feature = "alloc")]
Self::Other(key) => key.algorithm(),
})
}

Expand DownExpand Up@@ -140,6 +146,15 @@ impl KeypairData {
}
}

/// Get the custom, opaque private key if this key is the correct type.
#[cfg(feature = "alloc")]
pub fn other(&self) -> Option<&OpaqueKeypair> {
match self {
Self::Other(key) => Some(key),
_ => None,
}
}

/// Is this key a DSA key?
#[cfg(feature = "alloc")]
pub fn is_dsa(&self) -> bool {
Expand DownExpand Up@@ -187,6 +202,12 @@ impl KeypairData {
matches!(self, Self::SkEd25519(_))
}

/// Is this a key with a custom algorithm?
#[cfg(feature = "alloc")]
pub fn is_other(&self) -> bool {
matches!(self, Self::Other(_))
}

/// Compute a deterministic "checkint" for this private key.
///
/// This is a sort of primitive pseudo-MAC used by the OpenSSH key format.
Expand All@@ -206,6 +227,8 @@ impl KeypairData {
Self::SkEcdsaSha2NistP256(sk) => sk.key_handle(),
#[cfg(feature = "alloc")]
Self::SkEd25519(sk) => sk.key_handle(),
#[cfg(feature = "alloc")]
Self::Other(key) => key.private.as_ref(),
};

let mut n = 0u32;
Expand DownExpand Up@@ -243,6 +266,8 @@ impl ConstantTimeEq for KeypairData {
// The key structs contain all public data.
Choice::from((a == b) as u8)
}
#[cfg(feature = "alloc")]
(Self::Other(a), Self::Other(b)) => a.ct_eq(b),
#[allow(unreachable_patterns)]
_ => Choice::from(0),
}
Expand DownExpand Up@@ -278,6 +303,10 @@ impl Decode for KeypairData {
}
#[cfg(feature = "alloc")]
Algorithm::SkEd25519 => SkEd25519::decode(reader).map(Self::SkEd25519),
#[cfg(feature = "alloc")]
algorithm @ Algorithm::Other(_) => {
OpaqueKeypair::decode_as(reader, algorithm).map(Self::Other)
}
#[allow(unreachable_patterns)]
_ => Err(Error::AlgorithmUnknown),
}
Expand DownExpand Up@@ -307,6 +336,8 @@ impl Encode for KeypairData {
Self::SkEcdsaSha2NistP256(sk) => sk.encoded_len()?,
#[cfg(feature = "alloc")]
Self::SkEd25519(sk) => sk.encoded_len()?,
#[cfg(feature = "alloc")]
Self::Other(key) => key.encoded_len()?,
};

[alg_len, key_len].checked_sum()
Expand All@@ -331,6 +362,8 @@ impl Encode for KeypairData {
Self::SkEcdsaSha2NistP256(sk) => sk.encode(writer)?,
#[cfg(feature = "alloc")]
Self::SkEd25519(sk) => sk.encode(writer)?,
#[cfg(feature = "alloc")]
Self::Other(key) => key.encode(writer)?,
}

Ok(())
Expand All@@ -357,6 +390,8 @@ impl TryFrom<&KeypairData> for public::KeyData {
}
#[cfg(feature = "alloc")]
KeypairData::SkEd25519(sk) => public::KeyData::SkEd25519(sk.public().clone()),
#[cfg(feature = "alloc")]
KeypairData::Other(key) => public::KeyData::Other(key.into()),
})
}
}
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' Support additional SSH key algorithms by gabi-250 · Pull Request #136 · RustCrypto/SSH · GitHub
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
2 changes: 1 addition & 1 deletion ssh-key/Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -46,7 +46,7 @@ default = ["ecdsa", "rand_core", "std"]
alloc = [
"encoding/alloc",
"signature/alloc",
"zeroize/alloc"
"zeroize/alloc",
]
std = [
"alloc",
Expand Down
30 changes: 27 additions & 3 deletions ssh-key/src/algorithm.rs
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
//! Algorithm support.

#[cfg(feature = "alloc")]
mod name;

use crate::{Error, Result};
use core::{fmt, str};
use encoding::{Label, LabelError};
Expand All@@ -10,6 +13,9 @@ use {
sha2::{Digest, Sha256, Sha512},
};

#[cfg(feature = "alloc")]
pub use name::AlgorithmName;

/// bcrypt-pbkdf
const BCRYPT: &str = "bcrypt";

Expand DownExpand Up@@ -80,7 +86,7 @@ const SK_SSH_ED25519: &str = "sk-ssh-ed25519@openssh.com";
///
/// This type provides a registry of supported digital signature algorithms
/// used for SSH keys.
#[derive(Copy, Clone, Debug, Default, Eq, Hash, PartialEq, PartialOrd, Ord)]
#[derive(Clone, Debug, Default, Eq, Hash, PartialEq, PartialOrd, Ord)]
#[non_exhaustive]
pub enum Algorithm {
/// Digital Signature Algorithm
Expand DownExpand Up@@ -113,6 +119,10 @@ pub enum Algorithm {

/// FIDO/U2F key with Ed25519
SkEd25519,

/// Other
#[cfg(feature = "alloc")]
Other(AlgorithmName),
}

impl Algorithm {
Expand All@@ -127,6 +137,8 @@ impl Algorithm {
/// - `ssh-rsa`
/// - `sk-ecdsa-sha2-nistp256@openssh.com` (FIDO/U2F key)
/// - `sk-ssh-ed25519@openssh.com` (FIDO/U2F key)
///
/// Any other algorithms are mapped to the [`Algorithm::Other`] variant.
pub fn new(id: &str) -> Result<Self> {
Ok(id.parse()?)
}
Expand All@@ -147,6 +159,8 @@ impl Algorithm {
/// - `sk-ecdsa-sha2-nistp256-cert-v01@openssh.com` (FIDO/U2F key)
/// - `sk-ssh-ed25519-cert-v01@openssh.com` (FIDO/U2F key)
///
/// Any other algorithms are mapped to the [`Algorithm::Other`] variant.
///
/// [PROTOCOL.certkeys]: https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.certkeys?annotate=HEAD
pub fn new_certificate(id: &str) -> Result<Self> {
match id {
Expand All@@ -164,12 +178,15 @@ impl Algorithm {
CERT_RSA => Ok(Algorithm::Rsa { hash: None }),
CERT_SK_ECDSA_SHA2_P256 => Ok(Algorithm::SkEcdsaSha2NistP256),
CERT_SK_SSH_ED25519 => Ok(Algorithm::SkEd25519),
#[cfg(feature = "alloc")]
_ => Ok(Algorithm::Other(AlgorithmName::from_certificate_str(id)?)),
#[cfg(not(feature = "alloc"))]
_ => Err(Error::AlgorithmUnknown),
}
}

/// Get the string identifier which corresponds to this algorithm.
pub fn as_str(self) -> &'static str {
pub fn as_str(&self) -> &str {
match self {
Algorithm::Dsa => SSH_DSA,
Algorithm::Ecdsa { curve } => match curve {
Expand All@@ -185,6 +202,8 @@ impl Algorithm {
},
Algorithm::SkEcdsaSha2NistP256 => SK_ECDSA_SHA2_P256,
Algorithm::SkEd25519 => SK_SSH_ED25519,
#[cfg(feature = "alloc")]
Algorithm::Other(algorithm) => algorithm.as_str(),
}
}

Expand All@@ -195,7 +214,7 @@ impl Algorithm {
/// See [PROTOCOL.certkeys] for more information.
///
/// [PROTOCOL.certkeys]: https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.certkeys?annotate=HEAD
pub fn as_certificate_str(self) -> &'static str {
pub fn as_certificate_str(&self) -> &str {
match self {
Algorithm::Dsa => CERT_DSA,
Algorithm::Ecdsa { curve } => match curve {
Expand All@@ -207,6 +226,8 @@ impl Algorithm {
Algorithm::Rsa { .. } => CERT_RSA,
Algorithm::SkEcdsaSha2NistP256 => CERT_SK_ECDSA_SHA2_P256,
Algorithm::SkEd25519 => CERT_SK_SSH_ED25519,
#[cfg(feature = "alloc")]
Algorithm::Other(algorithm) => algorithm.certificate_str(),
}
}

Expand DownExpand Up@@ -276,6 +297,9 @@ impl str::FromStr for Algorithm {
SSH_RSA => Ok(Algorithm::Rsa { hash: None }),
SK_ECDSA_SHA2_P256 => Ok(Algorithm::SkEcdsaSha2NistP256),
SK_SSH_ED25519 => Ok(Algorithm::SkEd25519),
#[cfg(feature = "alloc")]
_ => Ok(Algorithm::Other(AlgorithmName::from_str(id)?)),
#[cfg(not(feature = "alloc"))]
_ => Err(LabelError::new(id)),
}
}
Expand Down
109 changes: 109 additions & 0 deletions ssh-key/src/algorithm/name.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
use alloc::string::String;
use core::str::{self, FromStr};
use encoding::LabelError;

/// The suffix added to the `name` in a `name@domainname` algorithm string identifier.
const CERT_STR_SUFFIX: &str = "-cert-v01";

/// According to [RFC4251 § 6], algorithm names are ASCII strings that are at most 64
/// characters long.
///
/// [RFC4251 § 6]: https://www.rfc-editor.org/rfc/rfc4251.html#section-6
const MAX_ALGORITHM_NAME_LEN: usize = 64;

/// The maximum length of the certificate string identifier is [`MAX_ALGORITHM_NAME_LEN`] +
/// `"-cert-v01".len()` (the certificate identifier is obtained by inserting `"-cert-v01"` in the
/// algorithm name).
const MAX_CERT_STR_LEN: usize = MAX_ALGORITHM_NAME_LEN + CERT_STR_SUFFIX.len();

/// A string representing an additional algorithm name in the `name@domainname` format (see
/// [RFC4251 § 6]).
///
/// Additional algorithm names must be non-empty printable ASCII strings no longer than 64
/// characters.
///
/// This also provides a `name-cert-v01@domainnname` string identifier for the corresponding
/// OpenSSH certificate format, derived from the specified `name@domainname` string.
///
/// NOTE: RFC4251 specifies additional validation criteria for algorithm names, but we do not
/// implement all of them here.
///
/// [RFC4251 § 6]: https://www.rfc-editor.org/rfc/rfc4251.html#section-6
#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub struct AlgorithmName {
/// The string identifier which corresponds to this algorithm.
id: String,
/// The string identifier which corresponds to the OpenSSH certificate format.
///
/// This is derived from the algorithm name by inserting `"-cert-v01"` immediately after the
/// name preceding the at-symbol (`@`).
certificate_str: String,
}

impl AlgorithmName {
/// Get the string identifier which corresponds to this algorithm name.
pub fn as_str(&self) -> &str {
&self.id
}

/// Get the string identifier which corresponds to the OpenSSH certificate format.
pub fn certificate_str(&self) -> &str {
&self.certificate_str
}

/// Create a new [`AlgorithmName`] from an OpenSSH certificate format string identifier.
pub fn from_certificate_str(id: &str) -> Result<Self, LabelError> {
validate_algorithm_id(id, MAX_CERT_STR_LEN)?;

// Derive the algorithm name from the certificate format string identifier:
let (name, domain) = split_algorithm_id(id)?;
let name = name
.strip_suffix(CERT_STR_SUFFIX)
.ok_or_else(|| LabelError::new(id))?;

let algorithm_name = format!("{name}@{domain}");

Ok(Self {
id: algorithm_name,
certificate_str: id.into(),
})
}
}

impl FromStr for AlgorithmName {
type Err = LabelError;

fn from_str(id: &str) -> Result<Self, LabelError> {
validate_algorithm_id(id, MAX_ALGORITHM_NAME_LEN)?;

// Derive the certificate format string identifier from the algorithm name:
let (name, domain) = split_algorithm_id(id)?;
let certificate_str = format!("{name}{CERT_STR_SUFFIX}@{domain}");

Ok(Self {
id: id.into(),
certificate_str,
})
}
}

/// Check if the length of `id` is at most `n`, and that `id` only consists of ASCII characters.
fn validate_algorithm_id(id: &str, n: usize) -> Result<(), LabelError> {
if id.len() > n || !id.is_ascii() {
return Err(LabelError::new(id));
}

Ok(())
}

/// Split a `name@domainname` algorithm string identifier into `(name, domainname)`.
fn split_algorithm_id(id: &str) -> Result<(&str, &str), LabelError> {
let (name, domain) = id.split_once('@').ok_or_else(|| LabelError::new(id))?;

// TODO: validate name and domain_name according to the criteria from RFC4251
if name.is_empty() || domain.is_empty() || domain.contains('@') {
return Err(LabelError::new(id));
}

Ok((name, domain))
}
1 change: 1 addition & 0 deletions ssh-key/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -174,6 +174,7 @@ pub use sha2;

#[cfg(feature = "alloc")]
pub use crate::{
algorithm::AlgorithmName,
certificate::Certificate,
known_hosts::KnownHosts,
mpint::Mpint,
Expand Down
3 changes: 3 additions & 0 deletions ssh-key/src/private.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -111,6 +111,8 @@ mod ecdsa;
mod ed25519;
mod keypair;
#[cfg(feature = "alloc")]
mod opaque;
#[cfg(feature = "alloc")]
mod rsa;
#[cfg(feature = "alloc")]
mod sk;
Expand All@@ -124,6 +126,7 @@ pub use self::{
pub use crate::{
private::{
dsa::{DsaKeypair, DsaPrivateKey},
opaque::{OpaqueKeypair, OpaqueKeypairBytes, OpaquePrivateKeyBytes},
rsa::{RsaKeypair, RsaPrivateKey},
sk::SkEd25519,
},
Expand Down
37 changes: 36 additions & 1 deletion ssh-key/src/private/keypair.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,7 +7,7 @@ use subtle::{Choice, ConstantTimeEq};

#[cfg(feature = "alloc")]
use {
super::{DsaKeypair, RsaKeypair, SkEd25519},
super::{DsaKeypair, OpaqueKeypair, RsaKeypair, SkEd25519},
alloc::vec::Vec,
};

Expand DownExpand Up@@ -55,6 +55,10 @@ pub enum KeypairData {
/// [PROTOCOL.u2f]: https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.u2f?annotate=HEAD
#[cfg(feature = "alloc")]
SkEd25519(SkEd25519),

/// Opaque keypair.
#[cfg(feature = "alloc")]
Other(OpaqueKeypair),
}

impl KeypairData {
Expand All@@ -74,6 +78,8 @@ impl KeypairData {
Self::SkEcdsaSha2NistP256(_) => Algorithm::SkEcdsaSha2NistP256,
#[cfg(feature = "alloc")]
Self::SkEd25519(_) => Algorithm::SkEd25519,
#[cfg(feature = "alloc")]
Self::Other(key) => key.algorithm(),
})
}

Expand DownExpand Up@@ -140,6 +146,15 @@ impl KeypairData {
}
}

/// Get the custom, opaque private key if this key is the correct type.
#[cfg(feature = "alloc")]
pub fn other(&self) -> Option<&OpaqueKeypair> {
match self {
Self::Other(key) => Some(key),
_ => None,
}
}

/// Is this key a DSA key?
#[cfg(feature = "alloc")]
pub fn is_dsa(&self) -> bool {
Expand DownExpand Up@@ -187,6 +202,12 @@ impl KeypairData {
matches!(self, Self::SkEd25519(_))
}

/// Is this a key with a custom algorithm?
#[cfg(feature = "alloc")]
pub fn is_other(&self) -> bool {
matches!(self, Self::Other(_))
}

/// Compute a deterministic "checkint" for this private key.
///
/// This is a sort of primitive pseudo-MAC used by the OpenSSH key format.
Expand All@@ -206,6 +227,8 @@ impl KeypairData {
Self::SkEcdsaSha2NistP256(sk) => sk.key_handle(),
#[cfg(feature = "alloc")]
Self::SkEd25519(sk) => sk.key_handle(),
#[cfg(feature = "alloc")]
Self::Other(key) => key.private.as_ref(),
};

let mut n = 0u32;
Expand DownExpand Up@@ -243,6 +266,8 @@ impl ConstantTimeEq for KeypairData {
// The key structs contain all public data.
Choice::from((a == b) as u8)
}
#[cfg(feature = "alloc")]
(Self::Other(a), Self::Other(b)) => a.ct_eq(b),
#[allow(unreachable_patterns)]
_ => Choice::from(0),
}
Expand DownExpand Up@@ -278,6 +303,10 @@ impl Decode for KeypairData {
}
#[cfg(feature = "alloc")]
Algorithm::SkEd25519 => SkEd25519::decode(reader).map(Self::SkEd25519),
#[cfg(feature = "alloc")]
algorithm @ Algorithm::Other(_) => {
OpaqueKeypair::decode_as(reader, algorithm).map(Self::Other)
}
#[allow(unreachable_patterns)]
_ => Err(Error::AlgorithmUnknown),
}
Expand DownExpand Up@@ -307,6 +336,8 @@ impl Encode for KeypairData {
Self::SkEcdsaSha2NistP256(sk) => sk.encoded_len()?,
#[cfg(feature = "alloc")]
Self::SkEd25519(sk) => sk.encoded_len()?,
#[cfg(feature = "alloc")]
Self::Other(key) => key.encoded_len()?,
};

[alg_len, key_len].checked_sum()
Expand All@@ -331,6 +362,8 @@ impl Encode for KeypairData {
Self::SkEcdsaSha2NistP256(sk) => sk.encode(writer)?,
#[cfg(feature = "alloc")]
Self::SkEd25519(sk) => sk.encode(writer)?,
#[cfg(feature = "alloc")]
Self::Other(key) => key.encode(writer)?,
}

Ok(())
Expand All@@ -357,6 +390,8 @@ impl TryFrom<&KeypairData> for public::KeyData {
}
#[cfg(feature = "alloc")]
KeypairData::SkEd25519(sk) => public::KeyData::SkEd25519(sk.public().clone()),
#[cfg(feature = "alloc")]
KeypairData::Other(key) => public::KeyData::Other(key.into()),
})
}
}
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Support additional SSH key algorithms by gabi-250 · Pull Request #136 · RustCrypto/SSH · GitHub
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
2 changes: 1 addition & 1 deletion ssh-key/Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -46,7 +46,7 @@ default = ["ecdsa", "rand_core", "std"]
alloc = [
"encoding/alloc",
"signature/alloc",
"zeroize/alloc"
"zeroize/alloc",
]
std = [
"alloc",
Expand Down
30 changes: 27 additions & 3 deletions ssh-key/src/algorithm.rs
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
//! Algorithm support.

#[cfg(feature = "alloc")]
mod name;

use crate::{Error, Result};
use core::{fmt, str};
use encoding::{Label, LabelError};
Expand All@@ -10,6 +13,9 @@ use {
sha2::{Digest, Sha256, Sha512},
};

#[cfg(feature = "alloc")]
pub use name::AlgorithmName;

/// bcrypt-pbkdf
const BCRYPT: &str = "bcrypt";

Expand DownExpand Up@@ -80,7 +86,7 @@ const SK_SSH_ED25519: &str = "sk-ssh-ed25519@openssh.com";
///
/// This type provides a registry of supported digital signature algorithms
/// used for SSH keys.
#[derive(Copy, Clone, Debug, Default, Eq, Hash, PartialEq, PartialOrd, Ord)]
#[derive(Clone, Debug, Default, Eq, Hash, PartialEq, PartialOrd, Ord)]
#[non_exhaustive]
pub enum Algorithm {
/// Digital Signature Algorithm
Expand DownExpand Up@@ -113,6 +119,10 @@ pub enum Algorithm {

/// FIDO/U2F key with Ed25519
SkEd25519,

/// Other
#[cfg(feature = "alloc")]
Other(AlgorithmName),
}

impl Algorithm {
Expand All@@ -127,6 +137,8 @@ impl Algorithm {
/// - `ssh-rsa`
/// - `sk-ecdsa-sha2-nistp256@openssh.com` (FIDO/U2F key)
/// - `sk-ssh-ed25519@openssh.com` (FIDO/U2F key)
///
/// Any other algorithms are mapped to the [`Algorithm::Other`] variant.
pub fn new(id: &str) -> Result<Self> {
Ok(id.parse()?)
}
Expand All@@ -147,6 +159,8 @@ impl Algorithm {
/// - `sk-ecdsa-sha2-nistp256-cert-v01@openssh.com` (FIDO/U2F key)
/// - `sk-ssh-ed25519-cert-v01@openssh.com` (FIDO/U2F key)
///
/// Any other algorithms are mapped to the [`Algorithm::Other`] variant.
///
/// [PROTOCOL.certkeys]: https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.certkeys?annotate=HEAD
pub fn new_certificate(id: &str) -> Result<Self> {
match id {
Expand All@@ -164,12 +178,15 @@ impl Algorithm {
CERT_RSA => Ok(Algorithm::Rsa { hash: None }),
CERT_SK_ECDSA_SHA2_P256 => Ok(Algorithm::SkEcdsaSha2NistP256),
CERT_SK_SSH_ED25519 => Ok(Algorithm::SkEd25519),
#[cfg(feature = "alloc")]
_ => Ok(Algorithm::Other(AlgorithmName::from_certificate_str(id)?)),
#[cfg(not(feature = "alloc"))]
_ => Err(Error::AlgorithmUnknown),
}
}

/// Get the string identifier which corresponds to this algorithm.
pub fn as_str(self) -> &'static str {
pub fn as_str(&self) -> &str {
match self {
Algorithm::Dsa => SSH_DSA,
Algorithm::Ecdsa { curve } => match curve {
Expand All@@ -185,6 +202,8 @@ impl Algorithm {
},
Algorithm::SkEcdsaSha2NistP256 => SK_ECDSA_SHA2_P256,
Algorithm::SkEd25519 => SK_SSH_ED25519,
#[cfg(feature = "alloc")]
Algorithm::Other(algorithm) => algorithm.as_str(),
}
}

Expand All@@ -195,7 +214,7 @@ impl Algorithm {
/// See [PROTOCOL.certkeys] for more information.
///
/// [PROTOCOL.certkeys]: https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.certkeys?annotate=HEAD
pub fn as_certificate_str(self) -> &'static str {
pub fn as_certificate_str(&self) -> &str {
match self {
Algorithm::Dsa => CERT_DSA,
Algorithm::Ecdsa { curve } => match curve {
Expand All@@ -207,6 +226,8 @@ impl Algorithm {
Algorithm::Rsa { .. } => CERT_RSA,
Algorithm::SkEcdsaSha2NistP256 => CERT_SK_ECDSA_SHA2_P256,
Algorithm::SkEd25519 => CERT_SK_SSH_ED25519,
#[cfg(feature = "alloc")]
Algorithm::Other(algorithm) => algorithm.certificate_str(),
}
}

Expand DownExpand Up@@ -276,6 +297,9 @@ impl str::FromStr for Algorithm {
SSH_RSA => Ok(Algorithm::Rsa { hash: None }),
SK_ECDSA_SHA2_P256 => Ok(Algorithm::SkEcdsaSha2NistP256),
SK_SSH_ED25519 => Ok(Algorithm::SkEd25519),
#[cfg(feature = "alloc")]
_ => Ok(Algorithm::Other(AlgorithmName::from_str(id)?)),
#[cfg(not(feature = "alloc"))]
_ => Err(LabelError::new(id)),
}
}
Expand Down
109 changes: 109 additions & 0 deletions ssh-key/src/algorithm/name.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
use alloc::string::String;
use core::str::{self, FromStr};
use encoding::LabelError;

/// The suffix added to the `name` in a `name@domainname` algorithm string identifier.
const CERT_STR_SUFFIX: &str = "-cert-v01";

/// According to [RFC4251 § 6], algorithm names are ASCII strings that are at most 64
/// characters long.
///
/// [RFC4251 § 6]: https://www.rfc-editor.org/rfc/rfc4251.html#section-6
const MAX_ALGORITHM_NAME_LEN: usize = 64;

/// The maximum length of the certificate string identifier is [`MAX_ALGORITHM_NAME_LEN`] +
/// `"-cert-v01".len()` (the certificate identifier is obtained by inserting `"-cert-v01"` in the
/// algorithm name).
const MAX_CERT_STR_LEN: usize = MAX_ALGORITHM_NAME_LEN + CERT_STR_SUFFIX.len();

/// A string representing an additional algorithm name in the `name@domainname` format (see
/// [RFC4251 § 6]).
///
/// Additional algorithm names must be non-empty printable ASCII strings no longer than 64
/// characters.
///
/// This also provides a `name-cert-v01@domainnname` string identifier for the corresponding
/// OpenSSH certificate format, derived from the specified `name@domainname` string.
///
/// NOTE: RFC4251 specifies additional validation criteria for algorithm names, but we do not
/// implement all of them here.
///
/// [RFC4251 § 6]: https://www.rfc-editor.org/rfc/rfc4251.html#section-6
#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub struct AlgorithmName {
/// The string identifier which corresponds to this algorithm.
id: String,
/// The string identifier which corresponds to the OpenSSH certificate format.
///
/// This is derived from the algorithm name by inserting `"-cert-v01"` immediately after the
/// name preceding the at-symbol (`@`).
certificate_str: String,
}

impl AlgorithmName {
/// Get the string identifier which corresponds to this algorithm name.
pub fn as_str(&self) -> &str {
&self.id
}

/// Get the string identifier which corresponds to the OpenSSH certificate format.
pub fn certificate_str(&self) -> &str {
&self.certificate_str
}

/// Create a new [`AlgorithmName`] from an OpenSSH certificate format string identifier.
pub fn from_certificate_str(id: &str) -> Result<Self, LabelError> {
validate_algorithm_id(id, MAX_CERT_STR_LEN)?;

// Derive the algorithm name from the certificate format string identifier:
let (name, domain) = split_algorithm_id(id)?;
let name = name
.strip_suffix(CERT_STR_SUFFIX)
.ok_or_else(|| LabelError::new(id))?;

let algorithm_name = format!("{name}@{domain}");

Ok(Self {
id: algorithm_name,
certificate_str: id.into(),
})
}
}

impl FromStr for AlgorithmName {
type Err = LabelError;

fn from_str(id: &str) -> Result<Self, LabelError> {
validate_algorithm_id(id, MAX_ALGORITHM_NAME_LEN)?;

// Derive the certificate format string identifier from the algorithm name:
let (name, domain) = split_algorithm_id(id)?;
let certificate_str = format!("{name}{CERT_STR_SUFFIX}@{domain}");

Ok(Self {
id: id.into(),
certificate_str,
})
}
}

/// Check if the length of `id` is at most `n`, and that `id` only consists of ASCII characters.
fn validate_algorithm_id(id: &str, n: usize) -> Result<(), LabelError> {
if id.len() > n || !id.is_ascii() {
return Err(LabelError::new(id));
}

Ok(())
}

/// Split a `name@domainname` algorithm string identifier into `(name, domainname)`.
fn split_algorithm_id(id: &str) -> Result<(&str, &str), LabelError> {
let (name, domain) = id.split_once('@').ok_or_else(|| LabelError::new(id))?;

// TODO: validate name and domain_name according to the criteria from RFC4251
if name.is_empty() || domain.is_empty() || domain.contains('@') {
return Err(LabelError::new(id));
}

Ok((name, domain))
}
1 change: 1 addition & 0 deletions ssh-key/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -174,6 +174,7 @@ pub use sha2;

#[cfg(feature = "alloc")]
pub use crate::{
algorithm::AlgorithmName,
certificate::Certificate,
known_hosts::KnownHosts,
mpint::Mpint,
Expand Down
3 changes: 3 additions & 0 deletions ssh-key/src/private.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -111,6 +111,8 @@ mod ecdsa;
mod ed25519;
mod keypair;
#[cfg(feature = "alloc")]
mod opaque;
#[cfg(feature = "alloc")]
mod rsa;
#[cfg(feature = "alloc")]
mod sk;
Expand All@@ -124,6 +126,7 @@ pub use self::{
pub use crate::{
private::{
dsa::{DsaKeypair, DsaPrivateKey},
opaque::{OpaqueKeypair, OpaqueKeypairBytes, OpaquePrivateKeyBytes},
rsa::{RsaKeypair, RsaPrivateKey},
sk::SkEd25519,
},
Expand Down
37 changes: 36 additions & 1 deletion ssh-key/src/private/keypair.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,7 +7,7 @@ use subtle::{Choice, ConstantTimeEq};

#[cfg(feature = "alloc")]
use {
super::{DsaKeypair, RsaKeypair, SkEd25519},
super::{DsaKeypair, OpaqueKeypair, RsaKeypair, SkEd25519},
alloc::vec::Vec,
};

Expand DownExpand Up@@ -55,6 +55,10 @@ pub enum KeypairData {
/// [PROTOCOL.u2f]: https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.u2f?annotate=HEAD
#[cfg(feature = "alloc")]
SkEd25519(SkEd25519),

/// Opaque keypair.
#[cfg(feature = "alloc")]
Other(OpaqueKeypair),
}

impl KeypairData {
Expand All@@ -74,6 +78,8 @@ impl KeypairData {
Self::SkEcdsaSha2NistP256(_) => Algorithm::SkEcdsaSha2NistP256,
#[cfg(feature = "alloc")]
Self::SkEd25519(_) => Algorithm::SkEd25519,
#[cfg(feature = "alloc")]
Self::Other(key) => key.algorithm(),
})
}

Expand DownExpand Up@@ -140,6 +146,15 @@ impl KeypairData {
}
}

/// Get the custom, opaque private key if this key is the correct type.
#[cfg(feature = "alloc")]
pub fn other(&self) -> Option<&OpaqueKeypair> {
match self {
Self::Other(key) => Some(key),
_ => None,
}
}

/// Is this key a DSA key?
#[cfg(feature = "alloc")]
pub fn is_dsa(&self) -> bool {
Expand DownExpand Up@@ -187,6 +202,12 @@ impl KeypairData {
matches!(self, Self::SkEd25519(_))
}

/// Is this a key with a custom algorithm?
#[cfg(feature = "alloc")]
pub fn is_other(&self) -> bool {
matches!(self, Self::Other(_))
}

/// Compute a deterministic "checkint" for this private key.
///
/// This is a sort of primitive pseudo-MAC used by the OpenSSH key format.
Expand All@@ -206,6 +227,8 @@ impl KeypairData {
Self::SkEcdsaSha2NistP256(sk) => sk.key_handle(),
#[cfg(feature = "alloc")]
Self::SkEd25519(sk) => sk.key_handle(),
#[cfg(feature = "alloc")]
Self::Other(key) => key.private.as_ref(),
};

let mut n = 0u32;
Expand DownExpand Up@@ -243,6 +266,8 @@ impl ConstantTimeEq for KeypairData {
// The key structs contain all public data.
Choice::from((a == b) as u8)
}
#[cfg(feature = "alloc")]
(Self::Other(a), Self::Other(b)) => a.ct_eq(b),
#[allow(unreachable_patterns)]
_ => Choice::from(0),
}
Expand DownExpand Up@@ -278,6 +303,10 @@ impl Decode for KeypairData {
}
#[cfg(feature = "alloc")]
Algorithm::SkEd25519 => SkEd25519::decode(reader).map(Self::SkEd25519),
#[cfg(feature = "alloc")]
algorithm @ Algorithm::Other(_) => {
OpaqueKeypair::decode_as(reader, algorithm).map(Self::Other)
}
#[allow(unreachable_patterns)]
_ => Err(Error::AlgorithmUnknown),
}
Expand DownExpand Up@@ -307,6 +336,8 @@ impl Encode for KeypairData {
Self::SkEcdsaSha2NistP256(sk) => sk.encoded_len()?,
#[cfg(feature = "alloc")]
Self::SkEd25519(sk) => sk.encoded_len()?,
#[cfg(feature = "alloc")]
Self::Other(key) => key.encoded_len()?,
};

[alg_len, key_len].checked_sum()
Expand All@@ -331,6 +362,8 @@ impl Encode for KeypairData {
Self::SkEcdsaSha2NistP256(sk) => sk.encode(writer)?,
#[cfg(feature = "alloc")]
Self::SkEd25519(sk) => sk.encode(writer)?,
#[cfg(feature = "alloc")]
Self::Other(key) => key.encode(writer)?,
}

Ok(())
Expand All@@ -357,6 +390,8 @@ impl TryFrom<&KeypairData> for public::KeyData {
}
#[cfg(feature = "alloc")]
KeypairData::SkEd25519(sk) => public::KeyData::SkEd25519(sk.public().clone()),
#[cfg(feature = "alloc")]
KeypairData::Other(key) => public::KeyData::Other(key.into()),
})
}
}
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Support additional SSH key algorithms by gabi-250 · Pull Request #136 · RustCrypto/SSH · GitHub
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
2 changes: 1 addition & 1 deletion ssh-key/Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -46,7 +46,7 @@ default = ["ecdsa", "rand_core", "std"]
alloc = [
"encoding/alloc",
"signature/alloc",
"zeroize/alloc"
"zeroize/alloc",
]
std = [
"alloc",
Expand Down
30 changes: 27 additions & 3 deletions ssh-key/src/algorithm.rs
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
//! Algorithm support.

#[cfg(feature = "alloc")]
mod name;

use crate::{Error, Result};
use core::{fmt, str};
use encoding::{Label, LabelError};
Expand All@@ -10,6 +13,9 @@ use {
sha2::{Digest, Sha256, Sha512},
};

#[cfg(feature = "alloc")]
pub use name::AlgorithmName;

/// bcrypt-pbkdf
const BCRYPT: &str = "bcrypt";

Expand DownExpand Up@@ -80,7 +86,7 @@ const SK_SSH_ED25519: &str = "sk-ssh-ed25519@openssh.com";
///
/// This type provides a registry of supported digital signature algorithms
/// used for SSH keys.
#[derive(Copy, Clone, Debug, Default, Eq, Hash, PartialEq, PartialOrd, Ord)]
#[derive(Clone, Debug, Default, Eq, Hash, PartialEq, PartialOrd, Ord)]
#[non_exhaustive]
pub enum Algorithm {
/// Digital Signature Algorithm
Expand DownExpand Up@@ -113,6 +119,10 @@ pub enum Algorithm {

/// FIDO/U2F key with Ed25519
SkEd25519,

/// Other
#[cfg(feature = "alloc")]
Other(AlgorithmName),
}

impl Algorithm {
Expand All@@ -127,6 +137,8 @@ impl Algorithm {
/// - `ssh-rsa`
/// - `sk-ecdsa-sha2-nistp256@openssh.com` (FIDO/U2F key)
/// - `sk-ssh-ed25519@openssh.com` (FIDO/U2F key)
///
/// Any other algorithms are mapped to the [`Algorithm::Other`] variant.
pub fn new(id: &str) -> Result<Self> {
Ok(id.parse()?)
}
Expand All@@ -147,6 +159,8 @@ impl Algorithm {
/// - `sk-ecdsa-sha2-nistp256-cert-v01@openssh.com` (FIDO/U2F key)
/// - `sk-ssh-ed25519-cert-v01@openssh.com` (FIDO/U2F key)
///
/// Any other algorithms are mapped to the [`Algorithm::Other`] variant.
///
/// [PROTOCOL.certkeys]: https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.certkeys?annotate=HEAD
pub fn new_certificate(id: &str) -> Result<Self> {
match id {
Expand All@@ -164,12 +178,15 @@ impl Algorithm {
CERT_RSA => Ok(Algorithm::Rsa { hash: None }),
CERT_SK_ECDSA_SHA2_P256 => Ok(Algorithm::SkEcdsaSha2NistP256),
CERT_SK_SSH_ED25519 => Ok(Algorithm::SkEd25519),
#[cfg(feature = "alloc")]
_ => Ok(Algorithm::Other(AlgorithmName::from_certificate_str(id)?)),
#[cfg(not(feature = "alloc"))]
_ => Err(Error::AlgorithmUnknown),
}
}

/// Get the string identifier which corresponds to this algorithm.
pub fn as_str(self) -> &'static str {
pub fn as_str(&self) -> &str {
match self {
Algorithm::Dsa => SSH_DSA,
Algorithm::Ecdsa { curve } => match curve {
Expand All@@ -185,6 +202,8 @@ impl Algorithm {
},
Algorithm::SkEcdsaSha2NistP256 => SK_ECDSA_SHA2_P256,
Algorithm::SkEd25519 => SK_SSH_ED25519,
#[cfg(feature = "alloc")]
Algorithm::Other(algorithm) => algorithm.as_str(),
}
}

Expand All@@ -195,7 +214,7 @@ impl Algorithm {
/// See [PROTOCOL.certkeys] for more information.
///
/// [PROTOCOL.certkeys]: https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.certkeys?annotate=HEAD
pub fn as_certificate_str(self) -> &'static str {
pub fn as_certificate_str(&self) -> &str {
match self {
Algorithm::Dsa => CERT_DSA,
Algorithm::Ecdsa { curve } => match curve {
Expand All@@ -207,6 +226,8 @@ impl Algorithm {
Algorithm::Rsa { .. } => CERT_RSA,
Algorithm::SkEcdsaSha2NistP256 => CERT_SK_ECDSA_SHA2_P256,
Algorithm::SkEd25519 => CERT_SK_SSH_ED25519,
#[cfg(feature = "alloc")]
Algorithm::Other(algorithm) => algorithm.certificate_str(),
}
}

Expand DownExpand Up@@ -276,6 +297,9 @@ impl str::FromStr for Algorithm {
SSH_RSA => Ok(Algorithm::Rsa { hash: None }),
SK_ECDSA_SHA2_P256 => Ok(Algorithm::SkEcdsaSha2NistP256),
SK_SSH_ED25519 => Ok(Algorithm::SkEd25519),
#[cfg(feature = "alloc")]
_ => Ok(Algorithm::Other(AlgorithmName::from_str(id)?)),
#[cfg(not(feature = "alloc"))]
_ => Err(LabelError::new(id)),
}
}
Expand Down
109 changes: 109 additions & 0 deletions ssh-key/src/algorithm/name.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
use alloc::string::String;
use core::str::{self, FromStr};
use encoding::LabelError;

/// The suffix added to the `name` in a `name@domainname` algorithm string identifier.
const CERT_STR_SUFFIX: &str = "-cert-v01";

/// According to [RFC4251 § 6], algorithm names are ASCII strings that are at most 64
/// characters long.
///
/// [RFC4251 § 6]: https://www.rfc-editor.org/rfc/rfc4251.html#section-6
const MAX_ALGORITHM_NAME_LEN: usize = 64;

/// The maximum length of the certificate string identifier is [`MAX_ALGORITHM_NAME_LEN`] +
/// `"-cert-v01".len()` (the certificate identifier is obtained by inserting `"-cert-v01"` in the
/// algorithm name).
const MAX_CERT_STR_LEN: usize = MAX_ALGORITHM_NAME_LEN + CERT_STR_SUFFIX.len();

/// A string representing an additional algorithm name in the `name@domainname` format (see
/// [RFC4251 § 6]).
///
/// Additional algorithm names must be non-empty printable ASCII strings no longer than 64
/// characters.
///
/// This also provides a `name-cert-v01@domainnname` string identifier for the corresponding
/// OpenSSH certificate format, derived from the specified `name@domainname` string.
///
/// NOTE: RFC4251 specifies additional validation criteria for algorithm names, but we do not
/// implement all of them here.
///
/// [RFC4251 § 6]: https://www.rfc-editor.org/rfc/rfc4251.html#section-6
#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub struct AlgorithmName {
/// The string identifier which corresponds to this algorithm.
id: String,
/// The string identifier which corresponds to the OpenSSH certificate format.
///
/// This is derived from the algorithm name by inserting `"-cert-v01"` immediately after the
/// name preceding the at-symbol (`@`).
certificate_str: String,
}

impl AlgorithmName {
/// Get the string identifier which corresponds to this algorithm name.
pub fn as_str(&self) -> &str {
&self.id
}

/// Get the string identifier which corresponds to the OpenSSH certificate format.
pub fn certificate_str(&self) -> &str {
&self.certificate_str
}

/// Create a new [`AlgorithmName`] from an OpenSSH certificate format string identifier.
pub fn from_certificate_str(id: &str) -> Result<Self, LabelError> {
validate_algorithm_id(id, MAX_CERT_STR_LEN)?;

// Derive the algorithm name from the certificate format string identifier:
let (name, domain) = split_algorithm_id(id)?;
let name = name
.strip_suffix(CERT_STR_SUFFIX)
.ok_or_else(|| LabelError::new(id))?;

let algorithm_name = format!("{name}@{domain}");

Ok(Self {
id: algorithm_name,
certificate_str: id.into(),
})
}
}

impl FromStr for AlgorithmName {
type Err = LabelError;

fn from_str(id: &str) -> Result<Self, LabelError> {
validate_algorithm_id(id, MAX_ALGORITHM_NAME_LEN)?;

// Derive the certificate format string identifier from the algorithm name:
let (name, domain) = split_algorithm_id(id)?;
let certificate_str = format!("{name}{CERT_STR_SUFFIX}@{domain}");

Ok(Self {
id: id.into(),
certificate_str,
})
}
}

/// Check if the length of `id` is at most `n`, and that `id` only consists of ASCII characters.
fn validate_algorithm_id(id: &str, n: usize) -> Result<(), LabelError> {
if id.len() > n || !id.is_ascii() {
return Err(LabelError::new(id));
}

Ok(())
}

/// Split a `name@domainname` algorithm string identifier into `(name, domainname)`.
fn split_algorithm_id(id: &str) -> Result<(&str, &str), LabelError> {
let (name, domain) = id.split_once('@').ok_or_else(|| LabelError::new(id))?;

// TODO: validate name and domain_name according to the criteria from RFC4251
if name.is_empty() || domain.is_empty() || domain.contains('@') {
return Err(LabelError::new(id));
}

Ok((name, domain))
}
1 change: 1 addition & 0 deletions ssh-key/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -174,6 +174,7 @@ pub use sha2;

#[cfg(feature = "alloc")]
pub use crate::{
algorithm::AlgorithmName,
certificate::Certificate,
known_hosts::KnownHosts,
mpint::Mpint,
Expand Down
3 changes: 3 additions & 0 deletions ssh-key/src/private.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -111,6 +111,8 @@ mod ecdsa;
mod ed25519;
mod keypair;
#[cfg(feature = "alloc")]
mod opaque;
#[cfg(feature = "alloc")]
mod rsa;
#[cfg(feature = "alloc")]
mod sk;
Expand All@@ -124,6 +126,7 @@ pub use self::{
pub use crate::{
private::{
dsa::{DsaKeypair, DsaPrivateKey},
opaque::{OpaqueKeypair, OpaqueKeypairBytes, OpaquePrivateKeyBytes},
rsa::{RsaKeypair, RsaPrivateKey},
sk::SkEd25519,
},
Expand Down
37 changes: 36 additions & 1 deletion ssh-key/src/private/keypair.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,7 +7,7 @@ use subtle::{Choice, ConstantTimeEq};

#[cfg(feature = "alloc")]
use {
super::{DsaKeypair, RsaKeypair, SkEd25519},
super::{DsaKeypair, OpaqueKeypair, RsaKeypair, SkEd25519},
alloc::vec::Vec,
};

Expand DownExpand Up@@ -55,6 +55,10 @@ pub enum KeypairData {
/// [PROTOCOL.u2f]: https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.u2f?annotate=HEAD
#[cfg(feature = "alloc")]
SkEd25519(SkEd25519),

/// Opaque keypair.
#[cfg(feature = "alloc")]
Other(OpaqueKeypair),
}

impl KeypairData {
Expand All@@ -74,6 +78,8 @@ impl KeypairData {
Self::SkEcdsaSha2NistP256(_) => Algorithm::SkEcdsaSha2NistP256,
#[cfg(feature = "alloc")]
Self::SkEd25519(_) => Algorithm::SkEd25519,
#[cfg(feature = "alloc")]
Self::Other(key) => key.algorithm(),
})
}

Expand DownExpand Up@@ -140,6 +146,15 @@ impl KeypairData {
}
}

/// Get the custom, opaque private key if this key is the correct type.
#[cfg(feature = "alloc")]
pub fn other(&self) -> Option<&OpaqueKeypair> {
match self {
Self::Other(key) => Some(key),
_ => None,
}
}

/// Is this key a DSA key?
#[cfg(feature = "alloc")]
pub fn is_dsa(&self) -> bool {
Expand DownExpand Up@@ -187,6 +202,12 @@ impl KeypairData {
matches!(self, Self::SkEd25519(_))
}

/// Is this a key with a custom algorithm?
#[cfg(feature = "alloc")]
pub fn is_other(&self) -> bool {
matches!(self, Self::Other(_))
}

/// Compute a deterministic "checkint" for this private key.
///
/// This is a sort of primitive pseudo-MAC used by the OpenSSH key format.
Expand All@@ -206,6 +227,8 @@ impl KeypairData {
Self::SkEcdsaSha2NistP256(sk) => sk.key_handle(),
#[cfg(feature = "alloc")]
Self::SkEd25519(sk) => sk.key_handle(),
#[cfg(feature = "alloc")]
Self::Other(key) => key.private.as_ref(),
};

let mut n = 0u32;
Expand DownExpand Up@@ -243,6 +266,8 @@ impl ConstantTimeEq for KeypairData {
// The key structs contain all public data.
Choice::from((a == b) as u8)
}
#[cfg(feature = "alloc")]
(Self::Other(a), Self::Other(b)) => a.ct_eq(b),
#[allow(unreachable_patterns)]
_ => Choice::from(0),
}
Expand DownExpand Up@@ -278,6 +303,10 @@ impl Decode for KeypairData {
}
#[cfg(feature = "alloc")]
Algorithm::SkEd25519 => SkEd25519::decode(reader).map(Self::SkEd25519),
#[cfg(feature = "alloc")]
algorithm @ Algorithm::Other(_) => {
OpaqueKeypair::decode_as(reader, algorithm).map(Self::Other)
}
#[allow(unreachable_patterns)]
_ => Err(Error::AlgorithmUnknown),
}
Expand DownExpand Up@@ -307,6 +336,8 @@ impl Encode for KeypairData {
Self::SkEcdsaSha2NistP256(sk) => sk.encoded_len()?,
#[cfg(feature = "alloc")]
Self::SkEd25519(sk) => sk.encoded_len()?,
#[cfg(feature = "alloc")]
Self::Other(key) => key.encoded_len()?,
};

[alg_len, key_len].checked_sum()
Expand All@@ -331,6 +362,8 @@ impl Encode for KeypairData {
Self::SkEcdsaSha2NistP256(sk) => sk.encode(writer)?,
#[cfg(feature = "alloc")]
Self::SkEd25519(sk) => sk.encode(writer)?,
#[cfg(feature = "alloc")]
Self::Other(key) => key.encode(writer)?,
}

Ok(())
Expand All@@ -357,6 +390,8 @@ impl TryFrom<&KeypairData> for public::KeyData {
}
#[cfg(feature = "alloc")]
KeypairData::SkEd25519(sk) => public::KeyData::SkEd25519(sk.public().clone()),
#[cfg(feature = "alloc")]
KeypairData::Other(key) => public::KeyData::Other(key.into()),
})
}
}
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); Support additional SSH key algorithms by gabi-250 · Pull Request #136 · RustCrypto/SSH · GitHub
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
2 changes: 1 addition & 1 deletion ssh-key/Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -46,7 +46,7 @@ default = ["ecdsa", "rand_core", "std"]
alloc = [
"encoding/alloc",
"signature/alloc",
"zeroize/alloc"
"zeroize/alloc",
]
std = [
"alloc",
Expand Down
30 changes: 27 additions & 3 deletions ssh-key/src/algorithm.rs
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
//! Algorithm support.

#[cfg(feature = "alloc")]
mod name;

use crate::{Error, Result};
use core::{fmt, str};
use encoding::{Label, LabelError};
Expand All@@ -10,6 +13,9 @@ use {
sha2::{Digest, Sha256, Sha512},
};

#[cfg(feature = "alloc")]
pub use name::AlgorithmName;

/// bcrypt-pbkdf
const BCRYPT: &str = "bcrypt";

Expand DownExpand Up@@ -80,7 +86,7 @@ const SK_SSH_ED25519: &str = "sk-ssh-ed25519@openssh.com";
///
/// This type provides a registry of supported digital signature algorithms
/// used for SSH keys.
#[derive(Copy, Clone, Debug, Default, Eq, Hash, PartialEq, PartialOrd, Ord)]
#[derive(Clone, Debug, Default, Eq, Hash, PartialEq, PartialOrd, Ord)]
#[non_exhaustive]
pub enum Algorithm {
/// Digital Signature Algorithm
Expand DownExpand Up@@ -113,6 +119,10 @@ pub enum Algorithm {

/// FIDO/U2F key with Ed25519
SkEd25519,

/// Other
#[cfg(feature = "alloc")]
Other(AlgorithmName),
}

impl Algorithm {
Expand All@@ -127,6 +137,8 @@ impl Algorithm {
/// - `ssh-rsa`
/// - `sk-ecdsa-sha2-nistp256@openssh.com` (FIDO/U2F key)
/// - `sk-ssh-ed25519@openssh.com` (FIDO/U2F key)
///
/// Any other algorithms are mapped to the [`Algorithm::Other`] variant.
pub fn new(id: &str) -> Result<Self> {
Ok(id.parse()?)
}
Expand All@@ -147,6 +159,8 @@ impl Algorithm {
/// - `sk-ecdsa-sha2-nistp256-cert-v01@openssh.com` (FIDO/U2F key)
/// - `sk-ssh-ed25519-cert-v01@openssh.com` (FIDO/U2F key)
///
/// Any other algorithms are mapped to the [`Algorithm::Other`] variant.
///
/// [PROTOCOL.certkeys]: https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.certkeys?annotate=HEAD
pub fn new_certificate(id: &str) -> Result<Self> {
match id {
Expand All@@ -164,12 +178,15 @@ impl Algorithm {
CERT_RSA => Ok(Algorithm::Rsa { hash: None }),
CERT_SK_ECDSA_SHA2_P256 => Ok(Algorithm::SkEcdsaSha2NistP256),
CERT_SK_SSH_ED25519 => Ok(Algorithm::SkEd25519),
#[cfg(feature = "alloc")]
_ => Ok(Algorithm::Other(AlgorithmName::from_certificate_str(id)?)),
#[cfg(not(feature = "alloc"))]
_ => Err(Error::AlgorithmUnknown),
}
}

/// Get the string identifier which corresponds to this algorithm.
pub fn as_str(self) -> &'static str {
pub fn as_str(&self) -> &str {
match self {
Algorithm::Dsa => SSH_DSA,
Algorithm::Ecdsa { curve } => match curve {
Expand All@@ -185,6 +202,8 @@ impl Algorithm {
},
Algorithm::SkEcdsaSha2NistP256 => SK_ECDSA_SHA2_P256,
Algorithm::SkEd25519 => SK_SSH_ED25519,
#[cfg(feature = "alloc")]
Algorithm::Other(algorithm) => algorithm.as_str(),
}
}

Expand All@@ -195,7 +214,7 @@ impl Algorithm {
/// See [PROTOCOL.certkeys] for more information.
///
/// [PROTOCOL.certkeys]: https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.certkeys?annotate=HEAD
pub fn as_certificate_str(self) -> &'static str {
pub fn as_certificate_str(&self) -> &str {
match self {
Algorithm::Dsa => CERT_DSA,
Algorithm::Ecdsa { curve } => match curve {
Expand All@@ -207,6 +226,8 @@ impl Algorithm {
Algorithm::Rsa { .. } => CERT_RSA,
Algorithm::SkEcdsaSha2NistP256 => CERT_SK_ECDSA_SHA2_P256,
Algorithm::SkEd25519 => CERT_SK_SSH_ED25519,
#[cfg(feature = "alloc")]
Algorithm::Other(algorithm) => algorithm.certificate_str(),
}
}

Expand DownExpand Up@@ -276,6 +297,9 @@ impl str::FromStr for Algorithm {
SSH_RSA => Ok(Algorithm::Rsa { hash: None }),
SK_ECDSA_SHA2_P256 => Ok(Algorithm::SkEcdsaSha2NistP256),
SK_SSH_ED25519 => Ok(Algorithm::SkEd25519),
#[cfg(feature = "alloc")]
_ => Ok(Algorithm::Other(AlgorithmName::from_str(id)?)),
#[cfg(not(feature = "alloc"))]
_ => Err(LabelError::new(id)),
}
}
Expand Down
109 changes: 109 additions & 0 deletions ssh-key/src/algorithm/name.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
use alloc::string::String;
use core::str::{self, FromStr};
use encoding::LabelError;

/// The suffix added to the `name` in a `name@domainname` algorithm string identifier.
const CERT_STR_SUFFIX: &str = "-cert-v01";

/// According to [RFC4251 § 6], algorithm names are ASCII strings that are at most 64
/// characters long.
///
/// [RFC4251 § 6]: https://www.rfc-editor.org/rfc/rfc4251.html#section-6
const MAX_ALGORITHM_NAME_LEN: usize = 64;

/// The maximum length of the certificate string identifier is [`MAX_ALGORITHM_NAME_LEN`] +
/// `"-cert-v01".len()` (the certificate identifier is obtained by inserting `"-cert-v01"` in the
/// algorithm name).
const MAX_CERT_STR_LEN: usize = MAX_ALGORITHM_NAME_LEN + CERT_STR_SUFFIX.len();

/// A string representing an additional algorithm name in the `name@domainname` format (see
/// [RFC4251 § 6]).
///
/// Additional algorithm names must be non-empty printable ASCII strings no longer than 64
/// characters.
///
/// This also provides a `name-cert-v01@domainnname` string identifier for the corresponding
/// OpenSSH certificate format, derived from the specified `name@domainname` string.
///
/// NOTE: RFC4251 specifies additional validation criteria for algorithm names, but we do not
/// implement all of them here.
///
/// [RFC4251 § 6]: https://www.rfc-editor.org/rfc/rfc4251.html#section-6
#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub struct AlgorithmName {
/// The string identifier which corresponds to this algorithm.
id: String,
/// The string identifier which corresponds to the OpenSSH certificate format.
///
/// This is derived from the algorithm name by inserting `"-cert-v01"` immediately after the
/// name preceding the at-symbol (`@`).
certificate_str: String,
}

impl AlgorithmName {
/// Get the string identifier which corresponds to this algorithm name.
pub fn as_str(&self) -> &str {
&self.id
}

/// Get the string identifier which corresponds to the OpenSSH certificate format.
pub fn certificate_str(&self) -> &str {
&self.certificate_str
}

/// Create a new [`AlgorithmName`] from an OpenSSH certificate format string identifier.
pub fn from_certificate_str(id: &str) -> Result<Self, LabelError> {
validate_algorithm_id(id, MAX_CERT_STR_LEN)?;

// Derive the algorithm name from the certificate format string identifier:
let (name, domain) = split_algorithm_id(id)?;
let name = name
.strip_suffix(CERT_STR_SUFFIX)
.ok_or_else(|| LabelError::new(id))?;

let algorithm_name = format!("{name}@{domain}");

Ok(Self {
id: algorithm_name,
certificate_str: id.into(),
})
}
}

impl FromStr for AlgorithmName {
type Err = LabelError;

fn from_str(id: &str) -> Result<Self, LabelError> {
validate_algorithm_id(id, MAX_ALGORITHM_NAME_LEN)?;

// Derive the certificate format string identifier from the algorithm name:
let (name, domain) = split_algorithm_id(id)?;
let certificate_str = format!("{name}{CERT_STR_SUFFIX}@{domain}");

Ok(Self {
id: id.into(),
certificate_str,
})
}
}

/// Check if the length of `id` is at most `n`, and that `id` only consists of ASCII characters.
fn validate_algorithm_id(id: &str, n: usize) -> Result<(), LabelError> {
if id.len() > n || !id.is_ascii() {
return Err(LabelError::new(id));
}

Ok(())
}

/// Split a `name@domainname` algorithm string identifier into `(name, domainname)`.
fn split_algorithm_id(id: &str) -> Result<(&str, &str), LabelError> {
let (name, domain) = id.split_once('@').ok_or_else(|| LabelError::new(id))?;

// TODO: validate name and domain_name according to the criteria from RFC4251
if name.is_empty() || domain.is_empty() || domain.contains('@') {
return Err(LabelError::new(id));
}

Ok((name, domain))
}
1 change: 1 addition & 0 deletions ssh-key/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -174,6 +174,7 @@ pub use sha2;

#[cfg(feature = "alloc")]
pub use crate::{
algorithm::AlgorithmName,
certificate::Certificate,
known_hosts::KnownHosts,
mpint::Mpint,
Expand Down
3 changes: 3 additions & 0 deletions ssh-key/src/private.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -111,6 +111,8 @@ mod ecdsa;
mod ed25519;
mod keypair;
#[cfg(feature = "alloc")]
mod opaque;
#[cfg(feature = "alloc")]
mod rsa;
#[cfg(feature = "alloc")]
mod sk;
Expand All@@ -124,6 +126,7 @@ pub use self::{
pub use crate::{
private::{
dsa::{DsaKeypair, DsaPrivateKey},
opaque::{OpaqueKeypair, OpaqueKeypairBytes, OpaquePrivateKeyBytes},
rsa::{RsaKeypair, RsaPrivateKey},
sk::SkEd25519,
},
Expand Down
37 changes: 36 additions & 1 deletion ssh-key/src/private/keypair.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,7 +7,7 @@ use subtle::{Choice, ConstantTimeEq};

#[cfg(feature = "alloc")]
use {
super::{DsaKeypair, RsaKeypair, SkEd25519},
super::{DsaKeypair, OpaqueKeypair, RsaKeypair, SkEd25519},
alloc::vec::Vec,
};

Expand DownExpand Up@@ -55,6 +55,10 @@ pub enum KeypairData {
/// [PROTOCOL.u2f]: https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.u2f?annotate=HEAD
#[cfg(feature = "alloc")]
SkEd25519(SkEd25519),

/// Opaque keypair.
#[cfg(feature = "alloc")]
Other(OpaqueKeypair),
}

impl KeypairData {
Expand All@@ -74,6 +78,8 @@ impl KeypairData {
Self::SkEcdsaSha2NistP256(_) => Algorithm::SkEcdsaSha2NistP256,
#[cfg(feature = "alloc")]
Self::SkEd25519(_) => Algorithm::SkEd25519,
#[cfg(feature = "alloc")]
Self::Other(key) => key.algorithm(),
})
}

Expand DownExpand Up@@ -140,6 +146,15 @@ impl KeypairData {
}
}

/// Get the custom, opaque private key if this key is the correct type.
#[cfg(feature = "alloc")]
pub fn other(&self) -> Option<&OpaqueKeypair> {
match self {
Self::Other(key) => Some(key),
_ => None,
}
}

/// Is this key a DSA key?
#[cfg(feature = "alloc")]
pub fn is_dsa(&self) -> bool {
Expand DownExpand Up@@ -187,6 +202,12 @@ impl KeypairData {
matches!(self, Self::SkEd25519(_))
}

/// Is this a key with a custom algorithm?
#[cfg(feature = "alloc")]
pub fn is_other(&self) -> bool {
matches!(self, Self::Other(_))
}

/// Compute a deterministic "checkint" for this private key.
///
/// This is a sort of primitive pseudo-MAC used by the OpenSSH key format.
Expand All@@ -206,6 +227,8 @@ impl KeypairData {
Self::SkEcdsaSha2NistP256(sk) => sk.key_handle(),
#[cfg(feature = "alloc")]
Self::SkEd25519(sk) => sk.key_handle(),
#[cfg(feature = "alloc")]
Self::Other(key) => key.private.as_ref(),
};

let mut n = 0u32;
Expand DownExpand Up@@ -243,6 +266,8 @@ impl ConstantTimeEq for KeypairData {
// The key structs contain all public data.
Choice::from((a == b) as u8)
}
#[cfg(feature = "alloc")]
(Self::Other(a), Self::Other(b)) => a.ct_eq(b),
#[allow(unreachable_patterns)]
_ => Choice::from(0),
}
Expand DownExpand Up@@ -278,6 +303,10 @@ impl Decode for KeypairData {
}
#[cfg(feature = "alloc")]
Algorithm::SkEd25519 => SkEd25519::decode(reader).map(Self::SkEd25519),
#[cfg(feature = "alloc")]
algorithm @ Algorithm::Other(_) => {
OpaqueKeypair::decode_as(reader, algorithm).map(Self::Other)
}
#[allow(unreachable_patterns)]
_ => Err(Error::AlgorithmUnknown),
}
Expand DownExpand Up@@ -307,6 +336,8 @@ impl Encode for KeypairData {
Self::SkEcdsaSha2NistP256(sk) => sk.encoded_len()?,
#[cfg(feature = "alloc")]
Self::SkEd25519(sk) => sk.encoded_len()?,
#[cfg(feature = "alloc")]
Self::Other(key) => key.encoded_len()?,
};

[alg_len, key_len].checked_sum()
Expand All@@ -331,6 +362,8 @@ impl Encode for KeypairData {
Self::SkEcdsaSha2NistP256(sk) => sk.encode(writer)?,
#[cfg(feature = "alloc")]
Self::SkEd25519(sk) => sk.encode(writer)?,
#[cfg(feature = "alloc")]
Self::Other(key) => key.encode(writer)?,
}

Ok(())
Expand All@@ -357,6 +390,8 @@ impl TryFrom<&KeypairData> for public::KeyData {
}
#[cfg(feature = "alloc")]
KeypairData::SkEd25519(sk) => public::KeyData::SkEd25519(sk.public().clone()),
#[cfg(feature = "alloc")]
KeypairData::Other(key) => public::KeyData::Other(key.into()),
})
}
}
Expand Down
Loading