Skip to content

Commit

Permalink
Zeroize RSA private key data on drop (#275)
Browse files Browse the repository at this point in the history
  • Loading branch information
robertabcd committed Apr 30, 2024
1 parent 4f749f4 commit 4b40f51
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 1 deletion.
1 change: 1 addition & 0 deletions russh-keys/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ thiserror = "1.0"
tokio = { version = "1.17.0", features = ["io-util", "rt-multi-thread", "time", "net"] }
tokio-stream = { version = "0.1", features = ["net"] }
typenum = "1.17"
zeroize = "1.7"

[features]
vendored-openssl = ["openssl", "openssl/vendored"]
Expand Down
20 changes: 20 additions & 0 deletions russh-keys/src/key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -462,6 +462,13 @@ pub struct RsaCrtExtra<'a> {
pub dq: Cow<'a, [u8]>,
}

impl Drop for RsaCrtExtra<'_> {
fn drop(&mut self) {
zeroize_cow(&mut self.dp);
zeroize_cow(&mut self.dq);
}
}

fn ec_signature(key: &ec::PrivateKey, b: &[u8]) -> Result<Vec<u8>, Error> {
let (r, s) = key.try_sign(b)?;
let mut buf = Vec::new();
Expand Down Expand Up @@ -513,3 +520,16 @@ pub fn parse_public_key(p: &[u8], prefer_hash: Option<SignatureHash>) -> Result<
pub fn safe_rng() -> impl rand::CryptoRng + rand::RngCore {
rand::thread_rng()
}

/// Zeroize `Cow` if value is owned.
pub(crate) fn zeroize_cow<T>(v: &mut Cow<T>)
where
T: ToOwned + ?Sized,
<T as ToOwned>::Owned: zeroize::Zeroize,
{
use zeroize::Zeroize;
match v {
Cow::Owned(v) => v.zeroize(),
Cow::Borrowed(_) => (),
}
}
15 changes: 14 additions & 1 deletion russh-keys/src/protocol.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use crate::encoding::{Encoding, Position, SshRead, SshWrite};
use std::borrow::Cow;

use crate::encoding::{Encoding, Position, SshRead, SshWrite};
use crate::key::zeroize_cow;

type Result<T> = std::result::Result<T, crate::Error>;

/// SSH RSA public key.
Expand Down Expand Up @@ -72,3 +74,14 @@ impl SshWrite for RsaPrivateKey<'_> {
encoder.extend_ssh_string(&self.comment);
}
}

impl Drop for RsaPrivateKey<'_> {
fn drop(&mut self) {
// Private parts only.
zeroize_cow(&mut self.private_exponent);
zeroize_cow(&mut self.coefficient);
zeroize_cow(&mut self.prime1);
zeroize_cow(&mut self.prime2);
zeroize_cow(&mut self.comment);
}
}

0 comments on commit 4b40f51

Please sign in to comment.