mod keyfile;
pub mod pubkey;
pub use keyfile::{KeyPaths, default_key_paths, load_or_generate, read_key, write_key};
use crate::error::{Error, Result};
use rsa::pkcs1::{DecodeRsaPrivateKey as _, EncodeRsaPrivateKey as _};
use rsa::pkcs1v15::Pkcs1v15Sign;
use rsa::pkcs8::DecodePrivateKey as _;
use rsa::{RsaPrivateKey, RsaPublicKey};
use sha1::Sha1;
pub const TOKEN_LEN: usize = 20;
pub const KEY_BITS: usize = 2048;
#[derive(Clone)]
pub struct HostKey {
private: RsaPrivateKey,
public: RsaPublicKey,
comment: String,
}
impl std::fmt::Debug for HostKey {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("HostKey")
.field("comment", &self.comment)
.finish_non_exhaustive()
}
}
impl HostKey {
pub fn generate(comment: impl Into<String>) -> Result<Self> {
let private = RsaPrivateKey::new(&mut rand::rngs::OsRng, KEY_BITS)?;
Self::from_private(private, comment.into())
}
pub fn from_private(private: RsaPrivateKey, comment: String) -> Result<Self> {
let public = private.to_public_key();
pubkey::encode(&public)?;
Ok(Self {
private,
public,
comment,
})
}
pub fn from_pem(pem: &str, comment: impl Into<String>) -> Result<Self> {
let private = match RsaPrivateKey::from_pkcs8_pem(pem) {
Ok(key) => key,
Err(pkcs8_err) => RsaPrivateKey::from_pkcs1_pem(pem).map_err(|pkcs1_err| {
Error::Key(format!("not PKCS#8 ({pkcs8_err}) nor PKCS#1 ({pkcs1_err})"))
})?,
};
Self::from_private(private, comment.into())
}
pub fn to_pem(&self) -> Result<String> {
Ok(self
.private
.to_pkcs1_pem(rsa::pkcs8::LineEnding::LF)?
.to_string())
}
pub fn public_key(&self) -> &RsaPublicKey {
&self.public
}
pub fn comment(&self) -> &str {
&self.comment
}
pub fn public_key_line(&self) -> Result<String> {
pubkey::encode_line(&self.public, &self.comment)
}
pub fn public_key_payload(&self) -> Result<Vec<u8>> {
let mut bytes = self.public_key_line()?.into_bytes();
bytes.push(0);
Ok(bytes)
}
pub fn sign_token(&self, token: &[u8]) -> Result<Vec<u8>> {
if token.len() != TOKEN_LEN {
return Err(Error::Protocol(format!(
"auth token must be {TOKEN_LEN} bytes, got {}",
token.len()
)));
}
Ok(self.private.sign(Pkcs1v15Sign::new::<Sha1>(), token)?)
}
}
pub fn verify_token(key: &RsaPublicKey, token: &[u8], signature: &[u8]) -> Result<()> {
if token.len() != TOKEN_LEN {
return Err(Error::Protocol(format!(
"auth token must be {TOKEN_LEN} bytes, got {}",
token.len()
)));
}
key.verify(Pkcs1v15Sign::new::<Sha1>(), token, signature)
.map_err(|e| Error::Key(format!("signature rejected: {e}")))
}