#[cfg(feature = "tls")]
pub mod cert;
pub(crate) mod pubkey;
mod record;
#[cfg(feature = "host-keys")]
pub mod store;
#[cfg(test)]
mod tests;
pub use pubkey::{encode_public_key, KeyName};
pub use record::{decode_key_record, encode_key_record};
pub use rsa;
pub use zeroize;
use alloc::string::String;
use alloc::vec::Vec;
use core::fmt;
use core::future::Future;
use rand_chacha::ChaCha12Rng;
use rsa::pkcs1::DecodeRsaPrivateKey;
use rsa::pkcs1v15::Pkcs1v15Sign;
use rsa::pkcs8::{DecodePrivateKey, EncodePrivateKey, LineEnding, SecretDocument};
use rsa::rand_core::{CryptoRngCore, SeedableRng};
use rsa::RsaPrivateKey;
use sha1::Sha1;
use zeroize::Zeroizing;
use crate::auth::Authenticator;
const MODULUS_BITS: usize = 2048;
const TOKEN_LEN: usize = 20;
pub struct AdbKey {
key: RsaPrivateKey,
padding: Pkcs1v15Sign,
blinding: ChaCha12Rng,
public_key_wire: Vec<u8>,
}
impl AdbKey {
pub fn generate<R: CryptoRngCore + ?Sized>(
rng: &mut R,
name: KeyName<'_>,
) -> Result<Self, KeyError> {
let key = RsaPrivateKey::new(rng, MODULUS_BITS).map_err(KeyError::Rsa)?;
Self::from_private_key(key, rng, name)
}
pub fn from_pkcs8_pem<R: CryptoRngCore + ?Sized>(
pem: &str,
rng: &mut R,
name: KeyName<'_>,
) -> Result<Self, KeyError> {
let key = RsaPrivateKey::from_pkcs8_pem(pem).map_err(KeyError::Pkcs8)?;
Self::from_private_key(key, rng, name)
}
pub fn from_pkcs1_pem<R: CryptoRngCore + ?Sized>(
pem: &str,
rng: &mut R,
name: KeyName<'_>,
) -> Result<Self, KeyError> {
let key = RsaPrivateKey::from_pkcs1_pem(pem).map_err(KeyError::Pkcs1)?;
Self::from_private_key(key, rng, name)
}
pub fn from_pkcs8_der<R: CryptoRngCore + ?Sized>(
der: &[u8],
rng: &mut R,
name: KeyName<'_>,
) -> Result<Self, KeyError> {
let key = RsaPrivateKey::from_pkcs8_der(der).map_err(KeyError::Pkcs8)?;
Self::from_private_key(key, rng, name)
}
pub fn to_pkcs8_pem(&self) -> Result<Zeroizing<String>, KeyError> {
self.key
.to_pkcs8_pem(LineEnding::LF)
.map_err(KeyError::Pkcs8)
}
pub fn to_pkcs8_der(&self) -> Result<SecretDocument, KeyError> {
self.key.to_pkcs8_der().map_err(KeyError::Pkcs8)
}
pub fn public_key_wire(&self) -> &[u8] {
&self.public_key_wire
}
pub fn public_key_line(&self) -> &[u8] {
&self.public_key_wire[..self.public_key_wire.len() - 1]
}
pub fn private_key(&self) -> &RsaPrivateKey {
&self.key
}
fn from_private_key<R: CryptoRngCore + ?Sized>(
key: RsaPrivateKey,
rng: &mut R,
name: KeyName<'_>,
) -> Result<Self, KeyError> {
let mut public_key_wire = encode_public_key(&key.to_public_key(), name)?;
public_key_wire.push(b'\0');
let mut seed = <ChaCha12Rng as SeedableRng>::Seed::default();
rng.fill_bytes(&mut seed);
Ok(Self {
key,
padding: Pkcs1v15Sign::new::<Sha1>(),
blinding: ChaCha12Rng::from_seed(seed),
public_key_wire,
})
}
}
impl fmt::Debug for AdbKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("AdbKey")
.field(
"public_key",
&String::from_utf8_lossy(self.public_key_line()),
)
.finish_non_exhaustive()
}
}
impl Authenticator for AdbKey {
type Error = KeyError;
fn sign(&mut self, token: &[u8]) -> impl Future<Output = Result<Vec<u8>, Self::Error>> {
let res = if token.len() == TOKEN_LEN {
self.key
.sign_with_rng(&mut self.blinding, self.padding.clone(), token)
.map_err(KeyError::Rsa)
} else {
Err(KeyError::InvalidToken(token.len()))
};
core::future::ready(res)
}
fn public_key(&self) -> &[u8] {
&self.public_key_wire
}
}
#[derive(Debug)]
#[non_exhaustive]
pub enum KeyError {
InvalidName,
NameTooLong(usize),
UnsupportedModulus(usize),
EvenModulus,
UnsupportedExponent,
InvalidToken(usize),
PayloadTooLarge(usize),
Pkcs8(rsa::pkcs8::Error),
Pkcs1(rsa::pkcs1::Error),
Rsa(rsa::Error),
}
impl fmt::Display for KeyError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidName => f.write_str("key name contains a NUL, CR or LF"),
Self::NameTooLong(len) => f.write_fmt(format_args!(
"key name of {len} bytes leaves the public key too large for one AUTH packet"
)),
Self::UnsupportedModulus(bits) => f.write_fmt(format_args!(
"unsupported modulus size: {bits} bits, need 2048"
)),
Self::EvenModulus => f.write_str("modulus is even, so it is not an RSA modulus"),
Self::UnsupportedExponent => {
f.write_str("public exponent is not an odd 32-bit integer of at least 3")
}
Self::InvalidToken(len) => f.write_fmt(format_args!(
"expected a 20-byte SHA-1 prehash token, got {len}"
)),
Self::PayloadTooLarge(len) => f.write_fmt(format_args!(
"key record payload of {len} bytes exceeds the 32-bit length field"
)),
Self::Pkcs8(e) => f.write_fmt(format_args!("PKCS#8: {e}")),
Self::Pkcs1(e) => f.write_fmt(format_args!("PKCS#1: {e}")),
Self::Rsa(e) => f.write_fmt(format_args!("RSA: {e}")),
}
}
}
impl core::error::Error for KeyError {}