i2p: keep the session's private key out of freed memory and debug output

This commit is contained in:
DeFiDude committed 2026-10-25 12:00:48 -06:00
1 parent 6aa1d4bbf1
commit 21100300fc
10 files changed
+405 -72

No files matched your search

+1
View File
@@ -37,6 +37,7 @@
- Writing, verifying and recovering state files retries a read that a signal interrupts instead of failing.
- Interface options wipe their IFAC passphrase when dropped, and the debug output of IFAC settings no longer shows it.
- Each interface's IFAC key lives in one allocation that is wiped when dropped, so interface tables no longer leave copies of it in freed memory.
- I2P interfaces no longer leave their private key in freed memory when they read it, store it or exchange it with the SAM bridge, and refuse a key file or SAM reply longer than 16 KiB.
## 1.4.0 - 2026-10-12
+5
View File
@@ -129,6 +129,11 @@ allocation that clones share and that is wiped when the last one drops, so
interface tables never copy the key. `with_ifac` still takes the key bytes;
otherwise set `Some(key.into())` or `IfacKey::derive(network_name,
passphrase)`, and read the bytes through `&*key`.
rns-crypto re-exports `zeroize` for crates that hold its wiped types without
depending on it, and `rns_identity::persistence::read_secret_file` reads a
bounded secret file into one wiped buffer. An I2P interface refuses a key file
or a SAM reply line longer than 16 KiB, and `I2PServerConfig` prints
`<redacted>` in place of a configured key.
rns-crypto enables the `zeroize` features of `aes` and `cbc`, so AES key
schedules and CBC state are wiped when dropped; dependents that build with
`--locked` refresh their lock files.
+1
View File
@@ -1,4 +1,5 @@
pub mod rns_crypto
pub use rns_crypto::zeroize
pub mod rns_crypto::aes_cbc
pub enum rns_crypto::aes_cbc::AesCbcError
pub rns_crypto::aes_cbc::AesCbcError::DecryptionFailed
+1
View File
@@ -337,6 +337,7 @@ pub fn rns_identity::persistence::durable_rename_directory(&std::path::Path, &st
pub fn rns_identity::persistence::durable_write(&std::path::Path, &[u8]) -> core::result::Result<rns_identity::persistence::DurableFileReceipt, rns_identity::persistence::DurableWriteError>
pub fn rns_identity::persistence::read_file(&std::path::Path) -> core::io::error::Result<core::option::Option<alloc::vec::Vec<u8>>>
pub fn rns_identity::persistence::read_file_bounded(&std::path::Path, usize) -> core::io::error::Result<core::option::Option<alloc::vec::Vec<u8>>>
pub fn rns_identity::persistence::read_secret_file(&std::path::Path, usize) -> core::io::error::Result<zeroize::Zeroizing<alloc::vec::Vec<u8>>>
pub fn rns_identity::persistence::storage_risk(&std::path::Path) -> core::io::error::Result<core::option::Option<rns_identity::persistence::StorageRisk>>
pub fn rns_identity::persistence::try_lock_exclusive(&std::fs::File) -> core::io::error::Result<()>
pub fn rns_identity::persistence::validate_durable_storage_directory(&std::path::Path) -> core::result::Result<(), rns_identity::persistence::DurableWriteError>
+2
View File
@@ -471,6 +471,8 @@ pub rns_interface::i2p::I2PServerConfig::sam_host: alloc::string::String
pub rns_interface::i2p::I2PServerConfig::sam_port: u16
impl rns_interface::i2p::I2PServerConfig
pub fn rns_interface::i2p::I2PServerConfig::new(&str) -> Self
impl core::fmt::Debug for rns_interface::i2p::I2PServerConfig
pub fn rns_interface::i2p::I2PServerConfig::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
pub const rns_interface::i2p::BITRATE_GUESS: u64
pub const rns_interface::i2p::DEFAULT_SAM_ADDRESS: &str
pub const rns_interface::i2p::DEFAULT_SAM_PORT: u16
+6 -6
View File
@@ -24,8 +24,8 @@
"tier": "provisional",
"compatibility": "reviewed-snapshot",
"snapshot": "api/snapshots/rns-crypto.txt",
"itemCount": 91,
"sha256": "2422d2c6ab0100d84c6cd7bc5adf81a006d6c05ed5cc81eca82f889777de09de"
"itemCount": 92,
"sha256": "1f4539cfe1dfc1bf78a75e95dc98a3bf14a432cf0292d8d654fc043d5c4d21dc"
},
{
"name": "rns-wire",
@@ -42,8 +42,8 @@
"tier": "candidate-stable",
"compatibility": "reviewed-snapshot",
"snapshot": "api/snapshots/rns-identity.txt",
"itemCount": 430,
"sha256": "3ea675b37cbbbb57d60659316d56f2582da42558b66760a87092018bca3d15e2"
"itemCount": 431,
"sha256": "377cb3b72a97b071e0d590c399d0cc0433b60fe5a6ae37a73657283d3622f037"
},
{
"name": "rns-transport",
@@ -78,8 +78,8 @@
"tier": "candidate-stable",
"compatibility": "reviewed-snapshot",
"snapshot": "api/snapshots/rns-interface.txt",
"itemCount": 1434,
"sha256": "5b07b30d8175bf09b1d8921a23c4170884017e53aa267834581927fb7a26882d"
"itemCount": 1436,
"sha256": "49b82fbc29b7e146489503f20a9081736c670c56379093660091215ba012a364"
},
{
"name": "rns-runtime",
+4
View File
@@ -16,6 +16,10 @@ pub mod token;
pub mod x25519;
pub use token::TOKEN_OVERHEAD;
/// The wiping types in this crate's API, such as the output of
/// [`hkdf::hkdf_sha256`], for crates that hold secrets without depending on
/// `zeroize` themselves.
pub use zeroize;
use alloc::string::String;
use core::fmt::Write;
+3 -2
View File
@@ -106,8 +106,9 @@ fn verify_bytes(path: &Path, data: &[u8]) -> std::io::Result<()> {
/// Read a secret file of at most `max_len` bytes into one buffer that is
/// allocated up front and wiped on drop, so neither growth nor a failed read
/// leaves a copy behind.
pub(crate) fn read_secret_file(path: &Path, max_len: usize) -> std::io::Result<Zeroizing<Vec<u8>>> {
/// leaves a copy behind. A longer file is refused with `InvalidData` once
/// `max_len + 1` bytes have been read.
pub fn read_secret_file(path: &Path, max_len: usize) -> std::io::Result<Zeroizing<Vec<u8>>> {
let mut file = fs::File::open(path)?;
let mut data = Zeroizing::new(vec![0u8; max_len.saturating_add(1)]);
let mut filled = 0;
+170 -64
View File
@@ -7,7 +7,8 @@ use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use bytes::Bytes;
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
use rns_crypto::zeroize::Zeroizing;
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt, BufReader};
use tokio::net::TcpStream;
use tokio::sync::mpsc;
@@ -38,6 +39,12 @@ pub const RECONNECT_WAIT_MAX: u64 = 300;
pub const SAM_VERSION: &str = "3.1";
/// The longest SAM reply line read, well past a SESSION STATUS that carries a
/// private key.
const SAM_REPLY_MAX_BYTES: usize = 16 * 1024;
/// An I2P key file holds one base64 SAM private key of a few kilobytes.
const I2P_KEY_FILE_MAX_BYTES: usize = 16 * 1024;
#[derive(Debug, thiserror::Error)]
pub enum SamError {
#[error("SAM I/O error: {0}")]
@@ -80,23 +87,81 @@ pub fn sam_reply_has_token(pairs: &[(String, String)], token: &str) -> bool {
pairs.iter().any(|(k, v)| k == token && v.is_empty())
}
async fn read_sam_reply(
reader: &mut BufReader<tokio::net::tcp::OwnedReadHalf>,
) -> Result<String, SamError> {
let mut line = String::new();
let n = reader.read_line(&mut line).await?;
if n == 0 {
return Err(SamError::Io(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
"SAM connection closed during handshake",
)));
}
Ok(line.trim_end().to_string())
/// The value of `key` in a reply, borrowed from it.
fn reply_value<'a>(reply: &'a str, key: &str) -> Option<&'a str> {
reply
.split_whitespace()
.find_map(|token| token.strip_prefix(key)?.strip_prefix('='))
}
async fn sam_hello(
/// Whether a reply holds `token` with no value.
fn reply_has_token(reply: &str, token: &str) -> bool {
reply
.split_whitespace()
.any(|word| word == token || word.strip_suffix('=') == Some(token))
}
/// A reply for an error message, with any private key left out.
fn without_destination(reply: &str) -> String {
reply
.split_whitespace()
.map(|token| {
if token.starts_with("DESTINATION=") {
"DESTINATION=<redacted>"
} else {
token
}
})
.collect::<Vec<_>>()
.join(" ")
}
/// Read one reply line into a buffer reserved once and wiped on drop, since a
/// SESSION STATUS reply carries the session's private key. Bytes are read one
/// at a time, so nothing past the line is consumed.
async fn read_sam_reply<R: AsyncRead + Unpin>(
reader: &mut R,
) -> Result<Zeroizing<String>, SamError> {
let mut line = Zeroizing::new(Vec::with_capacity(SAM_REPLY_MAX_BYTES));
loop {
match reader.read_u8().await {
Ok(b'\n') => break,
Ok(_) if line.len() == SAM_REPLY_MAX_BYTES => {
return Err(SamError::UnexpectedReply(format!(
"reply longer than {SAM_REPLY_MAX_BYTES} bytes"
)));
}
Ok(byte) => line.push(byte),
Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof && !line.is_empty() => break,
Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => {
return Err(SamError::Io(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
"SAM connection closed during handshake",
)));
}
Err(e) => return Err(e.into()),
}
}
let end = line
.iter()
.rposition(|byte| !byte.is_ascii_whitespace())
.map_or(0, |last| last + 1);
line.truncate(end);
match String::from_utf8(std::mem::take(&mut *line)) {
Ok(text) => Ok(Zeroizing::new(text)),
Err(error) => {
drop(Zeroizing::new(error.into_bytes()));
Err(SamError::Io(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"SAM reply is not UTF-8",
)))
}
}
}
async fn sam_hello<R: AsyncRead + Unpin>(
writer: &mut tokio::net::tcp::OwnedWriteHalf,
reader: &mut BufReader<tokio::net::tcp::OwnedReadHalf>,
reader: &mut R,
) -> Result<(), SamError> {
let hello_msg = format!("HELLO VERSION MIN={} MAX={}\n", SAM_VERSION, SAM_VERSION);
writer.write_all(hello_msg.as_bytes()).await?;
@@ -108,7 +173,7 @@ async fn sam_hello(
if !sam_reply_has_token(&pairs, "HELLO") || !sam_reply_has_token(&pairs, "REPLY") {
return Err(SamError::HandshakeFailed(format!(
"expected HELLO REPLY, got: {}",
reply
reply.as_str()
)));
}
@@ -120,45 +185,58 @@ async fn sam_hello(
))),
None => Err(SamError::HandshakeFailed(format!(
"no RESULT in HELLO reply: {}",
reply
reply.as_str()
))),
}
}
/// Returns the destination (base64). `private_key=None` = transient.
async fn sam_session_create(
/// Returns the session's private key (base64), wiped on drop.
/// `private_key=None` = transient.
async fn sam_session_create<R: AsyncRead + Unpin>(
writer: &mut tokio::net::tcp::OwnedWriteHalf,
reader: &mut BufReader<tokio::net::tcp::OwnedReadHalf>,
reader: &mut R,
session_id: &str,
private_key: Option<&str>,
transient_signature_type: Option<u8>,
) -> Result<String, SamError> {
let dest_param = match (private_key, transient_signature_type) {
(Some(key), _) => key.to_string(),
(None, Some(signature_type)) => format!("TRANSIENT SIGNATURE_TYPE={signature_type}"),
(None, None) => "TRANSIENT".to_string(),
) -> Result<Zeroizing<String>, SamError> {
let transient;
let destination = match (private_key, transient_signature_type) {
(Some(key), _) => key,
(None, Some(signature_type)) => {
transient = format!("TRANSIENT SIGNATURE_TYPE={signature_type}");
&transient
}
(None, None) => "TRANSIENT",
};
let create_msg = format!(
"SESSION CREATE STYLE=STREAM ID={} DESTINATION={}\n",
session_id, dest_param
);
// Sized up front: the command carries the private key.
let mut create_msg = Zeroizing::new(String::with_capacity(
64 + session_id.len() + destination.len(),
));
for part in [
"SESSION CREATE STYLE=STREAM ID=",
session_id,
" DESTINATION=",
destination,
"\n",
] {
create_msg.push_str(part);
}
writer.write_all(create_msg.as_bytes()).await?;
writer.flush().await?;
let reply = read_sam_reply(reader).await?;
let pairs = parse_sam_reply(&reply);
if !sam_reply_has_token(&pairs, "SESSION") || !sam_reply_has_token(&pairs, "STATUS") {
if !reply_has_token(&reply, "SESSION") || !reply_has_token(&reply, "STATUS") {
return Err(SamError::SessionFailed(format!(
"expected SESSION STATUS, got: {}",
reply
without_destination(&reply)
)));
}
match sam_reply_get(&pairs, "RESULT") {
match reply_value(&reply, "RESULT") {
Some("OK") => {}
Some(other) => {
let msg_detail = sam_reply_get(&pairs, "MESSAGE").unwrap_or("no details");
let msg_detail = reply_value(&reply, "MESSAGE").unwrap_or("no details");
return Err(SamError::SessionFailed(format!(
"SESSION RESULT={}: {}",
other, msg_detail
@@ -167,13 +245,13 @@ async fn sam_session_create(
None => {
return Err(SamError::SessionFailed(format!(
"no RESULT in SESSION STATUS: {}",
reply
without_destination(&reply)
)));
}
}
match sam_reply_get(&pairs, "DESTINATION") {
Some(dest) => Ok(dest.to_string()),
match reply_value(&reply, "DESTINATION") {
Some(dest) => Ok(Zeroizing::new(dest.to_string())),
None => Err(SamError::SessionFailed(
"SESSION STATUS OK but no DESTINATION returned".to_string(),
)),
@@ -201,7 +279,7 @@ async fn sam_stream_connect(
if !sam_reply_has_token(&pairs, "STREAM") || !sam_reply_has_token(&pairs, "STATUS") {
return Err(SamError::StreamFailed(format!(
"expected STREAM STATUS, got: {}",
reply
reply.as_str()
)));
}
@@ -216,7 +294,7 @@ async fn sam_stream_connect(
}
None => Err(SamError::StreamFailed(format!(
"no RESULT in STREAM STATUS: {}",
reply
reply.as_str()
))),
}
}
@@ -238,7 +316,7 @@ async fn sam_stream_accept(
if !sam_reply_has_token(&pairs, "STREAM") || !sam_reply_has_token(&pairs, "STATUS") {
return Err(SamError::AcceptFailed(format!(
"expected STREAM STATUS, got: {}",
reply
reply.as_str()
)));
}
@@ -254,7 +332,7 @@ async fn sam_stream_accept(
None => {
return Err(SamError::AcceptFailed(format!(
"no RESULT in STREAM STATUS: {}",
reply
reply.as_str()
)));
}
}
@@ -286,7 +364,7 @@ fn generate_session_id() -> String {
format!("reticulum_{:016x}", id)
}
#[derive(Debug, Clone)]
#[derive(Clone)]
pub struct I2PServerConfig {
pub name: String,
pub sam_host: String,
@@ -304,6 +382,23 @@ pub struct I2PServerConfig {
pub b32: Option<tokio::sync::watch::Sender<Option<String>>>,
}
// The key is the destination's secret; debug output names only its presence.
impl std::fmt::Debug for I2PServerConfig {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("I2PServerConfig")
.field("name", &self.name)
.field("sam_host", &self.sam_host)
.field("sam_port", &self.sam_port)
.field("keyfile", &self.keyfile.as_ref().map(|_| "<redacted>"))
.field("key_path", &self.key_path)
.field("reconnect_delay", &self.reconnect_delay)
.field("mode", &self.mode)
.field("b32", &self.b32)
.finish()
}
}
impl I2PServerConfig {
pub fn new(name: &str) -> Self {
Self {
@@ -323,14 +418,21 @@ impl I2PServerConfig {
/// (RNS/vendor/i2plib/sam.py:91-93).
const NEW_DESTINATION_SIGNATURE_TYPE: u8 = 7;
/// The stored key, `None` when there is none yet. A file that cannot be read
/// is an error, so it is never replaced.
fn read_private_key(path: &std::path::Path) -> std::io::Result<Option<String>> {
match std::fs::read_to_string(path) {
Ok(key) => Ok(Some(key.trim().to_string()).filter(|key| !key.is_empty())),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(error) => Err(error),
}
/// The stored key, `None` when there is none yet, read into buffers that are
/// wiped on drop. A file that cannot be read is an error, so it is never
/// replaced.
fn read_private_key(path: &std::path::Path) -> std::io::Result<Option<Zeroizing<String>>> {
let data = match rns_identity::persistence::read_secret_file(path, I2P_KEY_FILE_MAX_BYTES) {
Ok(data) => data,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(error) => return Err(error),
};
let key = std::str::from_utf8(&data)
.map_err(|_| {
std::io::Error::new(std::io::ErrorKind::InvalidData, "I2P key file is not UTF-8")
})?
.trim();
Ok((!key.is_empty()).then(|| Zeroizing::new(key.to_string())))
}
/// Keep a session's private key readable by its owner only, replaced
@@ -352,9 +454,10 @@ pub fn destination_b32(private_key: &str) -> Option<String> {
Some(base32_lowercase(&hash))
}
/// Base64 with I2P's `-~` alphabet (i2plib `i2p_b64decode`).
fn i2p_base64_decode(text: &str) -> Option<Vec<u8>> {
let mut bytes = Vec::with_capacity(text.len() * 3 / 4);
/// Base64 with I2P's `-~` alphabet (i2plib `i2p_b64decode`), into a buffer
/// sized up front and wiped on drop: the input is usually a private key.
fn i2p_base64_decode(text: &str) -> Option<Zeroizing<Vec<u8>>> {
let mut bytes = Zeroizing::new(Vec::with_capacity(text.len() * 3 / 4));
let (mut buffer, mut bits) = (0u32, 0u32);
for c in text.trim_end_matches('=').bytes() {
let value = match c {
@@ -483,10 +586,10 @@ pub async fn spawn_i2p_client(
}
};
let (session_reader, mut session_writer) = session_stream.into_split();
let mut session_buf_reader = BufReader::new(session_reader);
// Read unbuffered: a read buffer would keep SAM's reply, private key included.
let (mut session_reader, mut session_writer) = session_stream.into_split();
if let Err(e) = sam_hello(&mut session_writer, &mut session_buf_reader).await {
if let Err(e) = sam_hello(&mut session_writer, &mut session_reader).await {
tracing::warn!(
name = %config.name,
error = %e,
@@ -505,7 +608,7 @@ pub async fn spawn_i2p_client(
let _our_dest = match sam_session_create(
&mut session_writer,
&mut session_buf_reader,
&mut session_reader,
&session_id,
None,
None,
@@ -740,20 +843,23 @@ pub async fn spawn_i2p_server(
}
};
let (session_reader, mut session_writer) = session_stream.into_split();
let mut session_buf_reader = BufReader::new(session_reader);
// Read unbuffered: a read buffer would keep SAM's reply, private key included.
let (mut session_reader, mut session_writer) = session_stream.into_split();
if let Err(e) = sam_hello(&mut session_writer, &mut session_buf_reader).await {
if let Err(e) = sam_hello(&mut session_writer, &mut session_reader).await {
tracing::warn!(name = %config.name, error = %e, "I2P server: SAM HELLO failed");
tokio::time::sleep(std::time::Duration::from_secs(config.reconnect_delay)).await;
continue;
}
let (private_key, store_key) = match (&config.keyfile, config.key_path.as_deref()) {
(Some(key), _) => (Some(key.clone()), false),
(Some(key), _) => (Some(Zeroizing::new(key.clone())), false),
(None, None) => (None, false),
(None, Some(path)) => match read_private_key(path) {
Ok(key) => (key.clone(), key.is_none()),
Ok(key) => {
let missing = key.is_none();
(key, missing)
}
Err(error) => {
tracing::warn!(
name = %config.name,
@@ -767,9 +873,9 @@ pub async fn spawn_i2p_server(
};
let our_dest = match sam_session_create(
&mut session_writer,
&mut session_buf_reader,
&mut session_reader,
&session_id,
private_key.as_deref(),
private_key.as_deref().map(String::as_str),
Some(NEW_DESTINATION_SIGNATURE_TYPE),
)
.await
@@ -0,0 +1,212 @@
//! A SAM session's private key, read from its key file or returned by the SAM
//! bridge, must not survive in freed heap memory.
#[path = "../../rns-crypto/tests/residue/mod.rs"]
mod residue;
use std::io::{BufRead, BufReader, Write};
use std::net::{TcpListener, TcpStream};
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
use residue::{assert_no_residue, freed_by, pseudo_random, serial};
use rns_interface::i2p::{I2PClientConfig, I2PServerConfig, spawn_i2p_client, spawn_i2p_server};
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-~";
/// A SAM private key: a destination of 384 key bytes and an Ed25519 key
/// certificate, then 256 private and 32 signing-key bytes. Returns the key's
/// bytes and its I2P base64 text.
fn sam_private_key(seed: u64) -> (Vec<u8>, String) {
let mut key = pseudo_random::<384>(seed).to_vec();
key.extend_from_slice(&[5, 0, 4, 0, 7, 0, 0]);
key.extend_from_slice(&pseudo_random::<288>(seed + 1));
let mut text = String::new();
for chunk in key.chunks(3) {
let bits = chunk.iter().enumerate().fold(0u32, |bits, (n, byte)| {
bits | u32::from(*byte) << (16 - 8 * n)
});
for n in 0..=chunk.len() {
text.push(char::from(ALPHABET[(bits >> (18 - 6 * n)) as usize & 63]));
}
text.extend(std::iter::repeat_n('=', 3 - chunk.len()));
}
(key, text)
}
/// A SAM bridge on its own threads, so none of its frees are recorded. A
/// session keeps the key it asks for, a transient one gets `transient`, and a
/// STREAM CONNECT succeeds; every socket then stays open.
fn sam_bridge(transient: String) -> u16 {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
std::thread::spawn(move || {
for socket in listener.incoming() {
let Ok(socket) = socket else { return };
let transient = transient.clone();
std::thread::spawn(move || serve(socket, &transient));
}
});
port
}
fn serve(mut socket: TcpStream, transient: &str) {
let mut reader = BufReader::new(socket.try_clone().unwrap());
let mut line = String::new();
if reader.read_line(&mut line).unwrap_or(0) == 0 {
return;
}
let _ = socket.write_all(b"HELLO REPLY RESULT=OK VERSION=3.1\n");
line.clear();
if reader.read_line(&mut line).unwrap_or(0) == 0 {
return;
}
if line.starts_with("SESSION CREATE") {
let destination = match line
.split_whitespace()
.find_map(|token| token.strip_prefix("DESTINATION="))
{
Some("TRANSIENT") | None => transient,
Some(key) => key,
};
let _ = socket
.write_all(format!("SESSION STATUS RESULT=OK DESTINATION={destination}\n").as_bytes());
} else if line.starts_with("STREAM CONNECT") {
let _ = socket.write_all(b"STREAM STATUS RESULT=OK\n");
}
let mut rest = Vec::new();
let _ = std::io::Read::read_to_end(&mut reader, &mut rest);
}
/// Run `body` on a current-thread runtime inside the check, then drop the
/// runtime there too, so every task's frees are recorded.
fn checked(body: impl std::future::Future<Output = ()>) -> residue::Freed {
let ((), freed) = freed_by(|| {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
runtime.block_on(body);
drop(runtime);
});
freed
}
struct TempDir(PathBuf);
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn temp_dir(label: &str) -> TempDir {
let path = std::env::temp_dir().join(format!("rns-i2p-residue-{label}-{}", std::process::id()));
std::fs::create_dir_all(&path).unwrap();
TempDir(path)
}
async fn run_server(sam_port: u16, key_path: PathBuf) {
let (b32_tx, mut b32_rx) = tokio::sync::watch::channel(None);
let mut config = I2PServerConfig::new("residue");
config.sam_host = "127.0.0.1".into();
config.sam_port = sam_port;
config.key_path = Some(key_path);
config.b32 = Some(b32_tx);
let (transport_tx, _transport_rx) = tokio::sync::mpsc::channel(16);
let (handle_tx, _handle_rx) = tokio::sync::mpsc::channel(16);
let _handle = spawn_i2p_server(
config,
1,
Arc::new(AtomicU64::new(2)),
transport_tx,
handle_tx,
)
.await
.unwrap();
tokio::time::timeout(Duration::from_secs(10), b32_rx.wait_for(Option::is_some))
.await
.expect("session created")
.unwrap();
// Let the server reach its STREAM ACCEPT.
tokio::time::sleep(Duration::from_millis(100)).await;
}
#[test]
fn i2p_server_with_a_stored_key_frees_no_private_key() {
let _serial = serial();
let (key, text) = sam_private_key(10);
let sam_port = sam_bridge(sam_private_key(11).1);
let dir = temp_dir("stored");
let key_path = dir.0.join("i2p.key");
std::fs::write(&key_path, format!("{text}\n")).unwrap();
let freed = checked(run_server(sam_port, key_path));
assert_no_residue(
&freed,
&[("private key text", text.as_bytes()), ("private key", &key)],
);
}
#[test]
fn i2p_server_storing_a_new_key_frees_no_private_key() {
let _serial = serial();
let (key, text) = sam_private_key(20);
let sam_port = sam_bridge(text.clone());
let dir = temp_dir("new");
let key_path = dir.0.join("i2p.key");
let freed = checked(run_server(sam_port, key_path.clone()));
assert_eq!(std::fs::read_to_string(&key_path).unwrap(), text);
assert_no_residue(
&freed,
&[("private key text", text.as_bytes()), ("private key", &key)],
);
}
#[test]
fn i2p_client_session_frees_no_private_key() {
let _serial = serial();
let (key, text) = sam_private_key(30);
let sam_port = sam_bridge(text.clone());
let peer = sam_private_key(40).1;
let freed = checked(async move {
let mut config = I2PClientConfig::new("residue", &peer[..516]);
config.sam_host = "127.0.0.1".into();
config.sam_port = sam_port;
let (transport_tx, mut transport_rx) = tokio::sync::mpsc::channel(16);
let handle = spawn_i2p_client(config, 1, transport_tx).await.unwrap();
tokio::time::timeout(Duration::from_secs(10), async {
while !handle.online.load(Ordering::SeqCst) {
tokio::select! {
_ = transport_rx.recv() => {}
_ = tokio::time::sleep(Duration::from_millis(10)) => {}
}
}
})
.await
.expect("client online");
});
assert_no_residue(
&freed,
&[("private key text", text.as_bytes()), ("private key", &key)],
);
}
#[test]
fn i2p_server_debug_output_hides_its_key() {
let (_, text) = sam_private_key(50);
let mut config = I2PServerConfig::new("residue");
config.keyfile = Some(text.clone());
let shown = format!("{config:?}");
assert!(!shown.contains(&text[..32]), "{shown}");
assert!(shown.contains("residue"), "{shown}");
}