identity: reject low-order X25519 keys and follow upstream IFAC rules

This commit is contained in:
DeFiDude committed 2026-11-10 02:46:18 -07:00
1 parent e008436d56
commit fd43574c8a
15 files changed
+253 -149

No files matched your search

+41 -16
View File
@@ -3,19 +3,23 @@
use alloc::vec;
use alloc::vec::Vec;
use hkdf::Hkdf;
use hmac::{Hmac, Mac};
use sha2::Sha256;
use thiserror::Error;
use zeroize::Zeroizing;
const HASH_LEN: usize = 32;
/// Per RFC 5869, HKDF-SHA256 can emit at most 255 * HashLen = 8160 bytes.
const MAX_OUTPUT_LENGTH: usize = 255 * 32;
const RFC_MAX_OUTPUT_LENGTH: usize = 255 * HASH_LEN;
type HmacSha256 = Hmac<Sha256>;
/// Errors surfaced by [`hkdf_sha256`].
#[derive(Debug, Error)]
pub enum HkdfError {
/// Requested output length exceeds the RFC 5869 cap (8160 bytes).
#[error("requested length {0} exceeds maximum HKDF output of {MAX_OUTPUT_LENGTH} bytes")]
OutputTooLong(usize),
/// Requested output length is zero.
#[error("invalid HKDF output length 0")]
InvalidLength,
/// Underlying HKDF expand call returned an error.
#[error("HKDF expansion failed")]
ExpansionFailed,
@@ -23,23 +27,42 @@ pub enum HkdfError {
/// HKDF-SHA256 key derivation (RFC 5869).
///
/// `length` is capped at 8160 bytes. `salt = None` uses 32 zero bytes as
/// specified by the RFC; `info = None` uses an empty context string. The
/// output is wiped when it is dropped.
/// `salt = None` uses 32 zero bytes as specified by the RFC; `info = None`
/// uses an empty context string. The output is wiped when it is dropped.
/// Lengths above the RFC's 255-block bound are accepted: the reference
/// implementation wraps its one-byte block counter, and IFAC masks for large
/// frames depend on that.
pub fn hkdf_sha256(
length: usize,
ikm: &[u8],
salt: Option<&[u8]>,
info: Option<&[u8]>,
) -> Result<Zeroizing<Vec<u8>>, HkdfError> {
if length > MAX_OUTPUT_LENGTH {
return Err(HkdfError::OutputTooLong(length));
if length == 0 {
return Err(HkdfError::InvalidLength);
}
let info = info.unwrap_or(b"");
let mut okm = Zeroizing::new(vec![0u8; length]);
if length <= RFC_MAX_OUTPUT_LENGTH {
Hkdf::<Sha256>::new(salt, ikm)
.expand(info, &mut okm)
.map_err(|_| HkdfError::ExpansionFailed)?;
return Ok(okm);
}
let hk = Hkdf::<Sha256>::new(salt, ikm);
let mut okm = Zeroizing::new(vec![0u8; length]);
hk.expand(info.unwrap_or(b""), &mut okm)
.map_err(|_| HkdfError::ExpansionFailed)?;
let (prk, _) = Hkdf::<Sha256>::extract(salt, ikm);
let keyed = HmacSha256::new_from_slice(&prk).map_err(|_| HkdfError::ExpansionFailed)?;
let mut previous = Zeroizing::new([0u8; HASH_LEN]);
for (index, chunk) in okm.chunks_mut(HASH_LEN).enumerate() {
let mut mac = keyed.clone();
if index > 0 {
mac.update(&previous[..]);
}
mac.update(info);
mac.update(&[(index as u8).wrapping_add(1)]);
previous.copy_from_slice(&mac.finalize().into_bytes());
chunk.copy_from_slice(&previous[..chunk.len()]);
}
Ok(okm)
}
@@ -74,9 +97,11 @@ mod tests {
}
#[test]
fn test_hkdf_max_length_exceeded() {
let result = hkdf_sha256(MAX_OUTPUT_LENGTH + 1, b"test", None, None);
assert!(result.is_err());
fn test_hkdf_rejects_zero_length() {
assert!(matches!(
hkdf_sha256(0, b"test", None, None),
Err(HkdfError::InvalidLength)
));
}
#[test]
+18 -6
View File
@@ -25,6 +25,14 @@ impl Drop for X25519PrivateKey {
}
}
/// Errors surfaced by [`X25519PrivateKey::exchange`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum X25519Error {
/// The peer key is a low-order point, so the shared secret is all zero.
#[error("X25519 peer key is a low-order point")]
LowOrderPoint,
}
/// X25519 public key (32 bytes, u-coordinate).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct X25519PublicKey {
@@ -59,10 +67,14 @@ impl X25519PrivateKey {
}
/// Compute the shared secret with `peer` via X25519 Diffie-Hellman.
/// This primitive does not reject an all-zero result; a protocol requiring
/// a contributory-behavior check must validate the returned secret.
pub fn exchange(&self, peer: &X25519PublicKey) -> [u8; 32] {
self.secret.diffie_hellman(&peer.key).to_bytes()
/// An all-zero result (a low-order peer key) is rejected, as the
/// reference implementation's default backend does.
pub fn exchange(&self, peer: &X25519PublicKey) -> Result<[u8; 32], X25519Error> {
let shared = self.secret.diffie_hellman(&peer.key);
if !shared.was_contributory() {
return Err(X25519Error::LowOrderPoint);
}
Ok(shared.to_bytes())
}
}
@@ -107,8 +119,8 @@ mod tests {
let bob_prv = X25519PrivateKey::generate();
let bob_pub = bob_prv.public_key();
let alice_shared = alice_prv.exchange(&bob_pub);
let bob_shared = bob_prv.exchange(&alice_pub);
let alice_shared = alice_prv.exchange(&bob_pub).unwrap();
let bob_shared = bob_prv.exchange(&alice_pub).unwrap();
assert_eq!(alice_shared, bob_shared);
}
+11 -3
View File
@@ -42,6 +42,8 @@ pub enum IdentityError {
VerificationFailed,
#[error("decryption failed")]
DecryptionFailed,
#[error("encryption failed")]
EncryptionFailed,
#[error("ed25519 error: {0}")]
Ed25519(#[from] Ed25519Error),
#[error("io error: {0}")]
@@ -359,7 +361,9 @@ impl Identity {
None => self.pub_key.clone(),
};
let mut shared = ephemeral.exchange(&target);
let mut shared = ephemeral
.exchange(&target)
.map_err(|_| IdentityError::EncryptionFailed)?;
let derived =
derive_key_64(&shared, &self.hash).map_err(|_| IdentityError::DecryptionFailed);
shared.zeroize();
@@ -408,7 +412,9 @@ impl Identity {
if let Some(ratchets) = ratchets {
for ratchet in ratchets {
let ratchet_prv = X25519PrivateKey::from_bytes(ratchet);
let mut shared = ratchet_prv.exchange(&peer_pub);
let Ok(mut shared) = ratchet_prv.exchange(&peer_pub) else {
continue;
};
let derived_result = derive_key_64(&shared, &self.hash);
shared.zeroize();
if let Ok(derived) = derived_result
@@ -429,9 +435,11 @@ impl Identity {
// Identity-key ECDH: in-memory key if present, else the hardware backend.
let mut shared: [u8; 32] = if let Some(prv) = self.prv.as_ref() {
prv.exchange(&peer_pub)
.map_err(|_| IdentityError::DecryptionFailed)?
} else if let Some(backend) = self.backend.as_ref() {
backend
.ecdh(&peer_pub_bytes)
.filter(|shared| shared.iter().any(|byte| *byte != 0))
.ok_or(IdentityError::DecryptionFailed)?
} else {
return Err(IdentityError::DecryptionFailed);
@@ -766,7 +774,7 @@ mod tests {
}
fn ecdh(&self, peer_pub: &[u8; 32]) -> Option<[u8; 32]> {
let peer = rns_crypto::x25519::X25519PublicKey::from_bytes(peer_pub);
Some(self.x.exchange(&peer))
self.x.exchange(&peer).ok()
}
}
+1 -1
View File
@@ -40,7 +40,7 @@ impl Drop for TempDir {
fn derived_key(private: &[u8; 32], ephemeral_public: &[u8], salt: &[u8]) -> Zeroizing<Vec<u8>> {
let private = X25519PrivateKey::from_bytes(private);
let public = X25519PublicKey::from_bytes(ephemeral_public.try_into().unwrap());
let shared = Zeroizing::new(private.exchange(&public));
let shared = Zeroizing::new(private.exchange(&public).unwrap());
hkdf_sha256(64, &*shared, Some(salt), None).unwrap()
}
+7 -2
View File
@@ -24,7 +24,8 @@ impl LinkKeys {
///
/// This primitive accepts AES-128-CBC and AES-256-CBC; endpoint admission
/// is narrower (see [`crate::constants::ENABLED_MODES`]). It does not
/// authenticate the peer or reject an all-zero X25519 shared secret.
/// authenticate the peer. A low-order peer key fails with
/// [`LinkKeyError::LowOrderPoint`].
pub fn derive(
my_prv: &X25519PrivateKey,
peer_pub: &X25519PublicKey,
@@ -37,7 +38,9 @@ impl LinkKeys {
_ => return Err(LinkKeyError::UnsupportedMode(mode)),
};
let mut shared_key = my_prv.exchange(peer_pub);
let mut shared_key = my_prv
.exchange(peer_pub)
.map_err(|_| LinkKeyError::LowOrderPoint)?;
let derived_result =
rns_crypto::hkdf::hkdf_sha256(derived_key_length, &shared_key, Some(link_id), None)
@@ -69,6 +72,8 @@ pub enum LinkKeyError {
UnsupportedMode(u8),
#[error("HKDF key derivation failed")]
HkdfFailed,
#[error("peer X25519 key is a low-order point")]
LowOrderPoint,
}
#[cfg(test)]
+1 -1
View File
@@ -342,7 +342,7 @@ mod tests {
let hw_shared = hw.ecdh(&peer_pub_bytes).unwrap();
let hw_pub = X25519PublicKey::from_bytes(&x_pub);
let sw_shared = peer_prv.exchange(&hw_pub);
let sw_shared = peer_prv.exchange(&hw_pub).unwrap();
assert_eq!(hw_shared, sw_shared, "ECDH must be symmetric");
}
+5 -3
View File
@@ -393,7 +393,9 @@ impl MockPivSession {
.ok_or(RatkeyError::EmptySlot { slot })?;
let peer_pub = X25519PublicKey::from_bytes(peer_pub_bytes);
let shared = prv.exchange(&peer_pub);
let shared = prv
.exchange(&peer_pub)
.map_err(|e| RatkeyError::EcdhFailed(e.to_string()))?;
self.operations.push(MockOperation::EcdhX25519 { slot });
Ok(shared)
@@ -652,7 +654,7 @@ mod tests {
let secret_hw = session.ecdh_x25519(SLOT_9D, &peer_pub_bytes).unwrap();
let session_pub = X25519PublicKey::from_bytes(&session_x_pub);
let secret_sw = peer_prv.exchange(&session_pub);
let secret_sw = peer_prv.exchange(&session_pub).unwrap();
assert_eq!(
secret_hw, secret_sw,
@@ -670,7 +672,7 @@ mod tests {
let software_key = X25519PrivateKey::from_bytes(&secret);
let peer = X25519PublicKey::from_bytes(&peer_pub);
let sw_shared = software_key.exchange(&peer);
let sw_shared = software_key.exchange(&peer).unwrap();
let hw_shared = session.ecdh_x25519(SLOT_9D, &peer_pub).unwrap();
+13 -5
View File
@@ -24,7 +24,11 @@ impl PivTransport for EcdhToken {
let mut response = Vec::with_capacity(38);
if apdu[1] == 0x87 {
let peer: [u8; 32] = apdu[apdu.len() - 32..].try_into().unwrap();
let shared = Zeroizing::new(self.key.exchange(&X25519PublicKey::from_bytes(&peer)));
let shared = Zeroizing::new(
self.key
.exchange(&X25519PublicKey::from_bytes(&peer))
.unwrap(),
);
response.extend_from_slice(&[0x7c, 0x22, 0x82, 0x20]);
response.extend_from_slice(&*shared);
}
@@ -55,7 +59,7 @@ fn piv_ecdh_frees_no_shared_secret() {
let peer = X25519PrivateKey::from_bytes(&pseudo_random(41))
.public_key()
.to_bytes();
let expected = Zeroizing::new(key.exchange(&X25519PublicKey::from_bytes(&peer)));
let expected = Zeroizing::new(key.exchange(&X25519PublicKey::from_bytes(&peer)).unwrap());
let mut session = session(key);
let ((), freed) = freed_by(|| {
@@ -79,9 +83,13 @@ fn hardware_decrypt_frees_no_shared_secret_or_plaintext() {
HardwareIdentity::from_keys(ed25519_public, x25519_public, Box::new(session(key))).unwrap();
let plaintext: [u8; 100] = pseudo_random(44);
let ciphertext = hardware.identity.encrypt(&plaintext, None).unwrap();
let shared = Zeroizing::new(X25519PrivateKey::from_bytes(&x25519).exchange(
&X25519PublicKey::from_bytes(ciphertext[..32].try_into().unwrap()),
));
let shared = Zeroizing::new(
X25519PrivateKey::from_bytes(&x25519)
.exchange(&X25519PublicKey::from_bytes(
ciphertext[..32].try_into().unwrap(),
))
.unwrap(),
);
let derived = derive_key_64(&*shared, &hardware.identity.hash).unwrap();
let ((), freed) = freed_by(|| {
+38 -20
View File
@@ -671,6 +671,28 @@ fn synthesize_tcp_client(
Ok(config)
}
/// Reads an IFAC credential the way the reference config loader does: both
/// spellings are evaluated in order, so the second wins, and `""` or `"None"`
/// leaves the credential unset.
fn ifac_credential(
section: &ConfigSection,
plain: &str,
underscore: &str,
what: &str,
) -> Option<String> {
let mut credential = None;
for key in [plain, underscore] {
match section.get(key) {
Some("None") => warn!(
"Ambiguous IFAC {what} \"None\", this value is ignored and an IFAC {what} has NOT been set"
),
Some(value) if !value.is_empty() => credential = Some(value.to_string()),
_ => {}
}
}
credential
}
/// Validate explicit IFAC byte sizes and TCP client `fixed_mtu` before driver
/// startup. A fixed MTU must be at least 500 and fit the driver wire budget
/// after active IFAC overhead. This does not validate every interface field;
@@ -700,13 +722,7 @@ pub fn validate_config_capacity(
} else {
0
};
// IFAC masking expands HKDF-SHA256 over the complete wire packet. Its
// 255-block limit is smaller than TCP's driver buffer when IFAC is active.
let wire_budget: usize = if active_ifac {
rns_transport::ifac::MAX_IFAC_WIRE_BYTES
} else {
262144
};
let wire_budget: usize = 262144;
let maximum = wire_budget
.checked_sub(tag)
.filter(|_| !active_ifac || (1..=64).contains(&tag));
@@ -1813,14 +1829,14 @@ impl InterfacePostInit {
announce_rate_penalty: section
.get_uint("announce_rate_penalty")
.or_else(|| announce_rate_target.map(|_| 0)),
ifac_network_name: section
.get("networkname")
.or_else(|| section.get("network_name"))
.map(|s| s.to_string()),
ifac_passphrase: section
.get("passphrase")
.or_else(|| section.get("pass_phrase"))
.map(|s| zeroize::Zeroizing::new(s.to_string())),
ifac_network_name: ifac_credential(
section,
"networkname",
"network_name",
"network name",
),
ifac_passphrase: ifac_credential(section, "passphrase", "pass_phrase", "passphrase")
.map(zeroize::Zeroizing::new),
ifac_size,
default_ifac_size: 8,
ingress_control,
@@ -2284,18 +2300,20 @@ mod tests {
}
client.set("fixed_mtu", "262144");
assert!(synthesize_interface("tcp", &client).is_ok());
// All supported credential spellings activate the tag, including an
// explicitly empty credential (which differs from an absent field).
// Every credential spelling activates the tag; an empty one does not.
for credential in ["networkname", "network_name", "passphrase", "pass_phrase"] {
let mut blank = client.clone();
blank.set(credential, "");
assert!(synthesize_interface("tcp", &blank).is_ok());
let mut active = client.clone();
active.set(credential, "");
active.set(credential, "k");
assert!(synthesize_interface("tcp", &active).is_err());
active.set("fixed_mtu", "8144");
active.set("fixed_mtu", "262128");
assert!(synthesize_interface("tcp", &active).is_ok());
active.set("ifac_size", "512");
active.set("ifac_size_unit", "bits");
assert!(synthesize_interface("tcp", &active).is_err());
active.set("fixed_mtu", "8096");
active.set("fixed_mtu", "262080");
assert!(synthesize_interface("tcp", &active).is_ok());
}
client.set("ifac_size", "512");
+86 -46
View File
@@ -1015,6 +1015,19 @@ pub enum ReceiptError {
TransportClosed,
}
/// Largest payload whose HEADER_1 packet fits the MTU for a destination type.
fn max_header1_payload(dest_type: DestType) -> usize {
use rns_wire::constants::{AES128_BLOCKSIZE, HEADER_MINSIZE, KEYSIZE, MTU, TOKEN_OVERHEAD};
let room = MTU - HEADER_MINSIZE;
match dest_type {
DestType::Single => {
(room - KEYSIZE / 16 - TOKEN_OVERHEAD) / AES128_BLOCKSIZE * AES128_BLOCKSIZE - 1
}
DestType::Group => (room - TOKEN_OVERHEAD) / AES128_BLOCKSIZE * AES128_BLOCKSIZE - 1,
DestType::Plain | DestType::Link => room,
}
}
#[derive(Debug, thiserror::Error)]
pub enum SendError {
#[error("destination must be outbound")]
@@ -1023,7 +1036,7 @@ pub enum SendError {
LinkDestination,
#[error("no validated identity is known for destination {0}")]
IdentityUnavailable(String),
#[error("payload is {actual} bytes; encrypted SINGLE-packet MDU is {max}")]
#[error("payload is {actual} bytes; the largest payload that fits the MTU is {max}")]
PayloadTooLarge { actual: usize, max: usize },
#[error("destination encryption failed: {0}")]
Encryption(#[from] DestinationError),
@@ -1510,14 +1523,6 @@ impl ReticulumHandle {
if destination.dest_type == DestType::Link {
return Err(SendError::LinkDestination);
}
if destination.dest_type == DestType::Single
&& data.len() > rns_wire::constants::SINGLE_PACKET_ENCRYPTED_MDU
{
return Err(SendError::PayloadTooLarge {
actual: data.len(),
max: rns_wire::constants::SINGLE_PACKET_ENCRYPTED_MDU,
});
}
// Python does not create receipts for PLAIN packets.
let create_receipt = options.create_receipt && destination.dest_type != DestType::Plain;
@@ -1538,14 +1543,22 @@ impl ReticulumHandle {
.remote_ratchet_pub
.as_ref()
.or_else(|| recalled.as_ref().and_then(|entry| entry.ratchet.as_ref()));
let packet = destination
.pack_packet(
data,
Some(encryption_identity),
ratchet,
DestinationPacketOptions::default(),
)?
.packet;
// Like the reference `Packet.pack`, only the packed size is limited.
let packet = match destination.pack_packet(
data,
Some(encryption_identity),
ratchet,
DestinationPacketOptions::default(),
) {
Ok(packed) => packed.packet,
Err(DestinationPacketError::Packet(rns_wire::packet::PacketError::ExceedsMtu(_))) => {
return Err(SendError::PayloadTooLarge {
actual: data.len(),
max: max_header1_payload(destination.dest_type),
});
}
Err(error) => return Err(error.into()),
};
let packet_hash = packet.packet_hash;
let truncated_hash = packet.truncated_hash;
@@ -6193,8 +6206,8 @@ fn derive_ifac_key_from_post_init(
#[derive(Clone, Default)]
/// Optional IFAC settings for runtime-spawned TCP/Backbone interfaces.
/// `ifac_size` is bytes (1..=64), default 16 when active. Empty name and
/// passphrase disable IFAC. IFAC restricts interface access; it does not
/// `ifac_size` is bytes (1..=64), default 16 when active. An empty or "None" name or
/// passphrase is ignored, as in config files. IFAC restricts interface access; it does not
/// provide application end-to-end encryption. `Debug` redacts the passphrase,
/// but the owned `String` is not itself a zeroizing container.
pub struct RuntimeInterfaceIfacConfig {
@@ -6246,8 +6259,8 @@ fn runtime_ifac_post_init(
return Err(format!("Invalid IFAC size {size}; expected 1..=64 bytes"));
}
let network_name = ifac.network_name.filter(|s| !s.is_empty());
let passphrase = ifac.passphrase.filter(|s| !s.is_empty());
let network_name = ifac.network_name.filter(|s| !s.is_empty() && s != "None");
let passphrase = ifac.passphrase.filter(|s| !s.is_empty() && s != "None");
if network_name.is_none() && passphrase.is_none() {
return Ok(None);
}
@@ -7129,6 +7142,14 @@ fn autoconnect_admits(record: &DiscoveredInterface, config: &ReticulumConfig) ->
admitted
}
/// Older nodes published the literal "None"; like an empty value it sets no credential.
fn discovered_ifac_value(value: &Option<String>) -> Option<String> {
value
.as_deref()
.filter(|v| !v.is_empty() && *v != "None")
.map(str::to_string)
}
async fn spawn_discovered_backbone_client(
handle: &ReticulumHandle,
record: &DiscoveredInterface,
@@ -7161,8 +7182,9 @@ async fn spawn_discovered_backbone_client(
.expect("empty interface defaults are valid")
.with_default_ifac_size(16);
finalize_post_init(&mut post_init, &handle.config);
post_init.ifac_network_name = record.info.ifac_netname.clone();
post_init.ifac_passphrase = record.info.ifac_netkey.clone().map(zeroize::Zeroizing::new);
post_init.ifac_network_name = discovered_ifac_value(&record.info.ifac_netname);
post_init.ifac_passphrase =
discovered_ifac_value(&record.info.ifac_netkey).map(zeroize::Zeroizing::new);
let ifac_key = derive_ifac_key_from_post_init(&post_init);
register_interface_with_post_init_and_spawn_permit(
&handle.transport_tx,
@@ -9627,6 +9649,47 @@ mod tests {
assert!(post_init.is_none());
}
#[test]
fn discovered_ifac_values_drop_blank_and_none() {
for (value, expected) in [
(None, None),
(Some(""), None),
(Some("None"), None),
(Some("net"), Some("net")),
] {
assert_eq!(
discovered_ifac_value(&value.map(str::to_string)).as_deref(),
expected
);
}
}
#[test]
fn runtime_ifac_post_init_ignores_none_fields() {
let post_init = runtime_ifac_post_init(
Some(RuntimeInterfaceIfacConfig {
network_name: Some("None".to_string()),
passphrase: Some("None".to_string()),
ifac_size: None,
}),
16,
)
.unwrap();
assert!(post_init.is_none());
let post_init = runtime_ifac_post_init(
Some(RuntimeInterfaceIfacConfig {
network_name: Some("None".to_string()),
passphrase: Some("pw".to_string()),
ifac_size: None,
}),
16,
)
.unwrap()
.unwrap();
assert_eq!(post_init.ifac_network_name, None);
}
#[test]
fn runtime_ifac_post_init_uses_tcp_default_size() {
let post_init = runtime_ifac_post_init(
@@ -12105,29 +12168,6 @@ loglevel = 7
responder.await.unwrap();
}
#[tokio::test]
async fn send_to_rejects_oversized_single_payload_before_transport_work() {
let destination_identity = Identity::new();
let destination = Destination::new(
Some(&destination_identity),
Direction::Out,
DestType::Single,
"send.large",
)
.unwrap();
let handle = dummy_handle();
let payload = vec![0u8; rns_wire::constants::SINGLE_PACKET_ENCRYPTED_MDU + 1];
assert!(matches!(
handle
.send_to(&destination, &payload, SendOptions::default())
.await,
Err(SendError::PayloadTooLarge { actual, max })
if actual == payload.len()
&& max == rns_wire::constants::SINGLE_PACKET_ENCRYPTED_MDU
));
}
#[tokio::test]
async fn typed_path_queries_validate_and_filter_actor_responses() {
let (transport_tx, mut transport_rx) = mpsc::channel::<TransportMessage>(7);
@@ -537,8 +537,8 @@ fn cmd_test(hwid_path: PathBuf, pin: Option<String>) {
println!(" PASS: ECDH returned {} bytes", shared.len());
let hw_pub_bytes = config.x25519_pub_bytes().unwrap();
let hw_pub = rns_crypto::x25519::X25519PublicKey::from_bytes(&hw_pub_bytes);
let peer_shared = peer_prv.exchange(&hw_pub);
if shared == peer_shared {
let peer_shared = peer_prv.exchange(&hw_pub).ok();
if Some(shared) == peer_shared {
println!(" PASS: ECDH is symmetric");
} else {
println!(" FAIL: ECDH shared secrets do not match");
@@ -273,24 +273,22 @@ fn packet_capacity_authenticated_proof_obeys_request_ceiling_and_keeps_original_
}
#[test]
fn packet_capacity_ifac_mask_frontier_is_checked_without_panicking() {
fn packet_capacity_ifac_wire_budget_is_the_hardware_mtu() {
let high = InterfacePacketCapacity::new(262144, 262144, true);
assert_eq!(high.effective_clear_mtu(0).unwrap(), 262144);
for tag in [1, 8, 16, 64] {
let clear = 8160 - tag;
let clear = 262144 - tag;
assert_eq!(high.effective_clear_mtu(tag).unwrap() as usize, clear);
let wire = crate::ifac::try_ifac_sign(&vec![0; clear], &[9; 64], tag).unwrap();
assert_eq!(wire.len(), 8160);
assert_eq!(
crate::ifac::ifac_verify(&wire, &[9; 64], tag)
.unwrap()
.len(),
clear
);
assert_eq!(
crate::ifac::try_ifac_sign(&vec![0; clear + 1], &[9; 64], tag),
Err(crate::ifac::IfacSignError::PacketTooLarge)
);
for len in [8160 - tag, 8161 - tag, 20000] {
let wire = crate::ifac::try_ifac_sign(&vec![0; len], &[9; 64], tag).unwrap();
assert_eq!(wire.len(), len + tag);
assert_eq!(
crate::ifac::ifac_verify(&wire, &[9; 64], tag)
.unwrap()
.len(),
len
);
}
}
assert!(crate::ifac::try_ifac_sign(&[1, 2], &[0; 64], 0).is_err());
assert!(crate::ifac::try_ifac_sign(&[1], &[0; 64], 1).is_err());
+8 -18
View File
@@ -19,17 +19,12 @@ use subtle::ConstantTimeEq;
/// Bit 7 of byte 0 signals IFAC presence, regardless of `ifac_size`.
const IFAC_FLAG: u8 = 0x80;
/// RFC5869 SHA256 expansion bound, including the IFAC tag itself.
pub const MAX_IFAC_WIRE_BYTES: usize = 255 * 32;
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum IfacSignError {
#[error("IFAC tag size must be 1..=64")]
InvalidTagSize,
#[error("packet is shorter than the two-byte header")]
ShortPacket,
#[error("complete IFAC packet exceeds the 8160-byte mask expansion limit")]
PacketTooLarge,
}
/// Stamp a packet with its IFAC tag and XOR mask.
@@ -41,16 +36,16 @@ pub enum IfacSignError {
///
/// # Panics
///
/// Panics for a tag outside 1..=64, a packet shorter than two bytes, or a
/// complete IFAC packet above 8160 bytes. Use [`try_ifac_sign`] when metadata
/// or packet size is caller-provided. Transport egress uses the checked form.
/// Panics for a tag outside 1..=64 or a packet shorter than two bytes. Use
/// [`try_ifac_sign`] when metadata or packet size is caller-provided.
/// Transport egress uses the checked form.
pub fn ifac_sign(packet: &[u8], ifac_key: &[u8; 64], ifac_size: usize) -> Vec<u8> {
try_ifac_sign(packet, ifac_key, ifac_size).expect("invalid IFAC signing arguments")
}
/// Sign and mask with checked tag size and byte length. Accepts tag sizes
/// of 1..=64 bytes and inner packets of at least two bytes, provided packet
/// plus tag is at most [`MAX_IFAC_WIRE_BYTES`]. This is not full packet validation: the
/// of 1..=64 bytes and inner packets of at least two bytes, of any length.
/// This is not full packet validation: the
/// caller must supply an inner packet with the IFAC flag clear. A two-byte
/// inner packet can be signed here but is rejected by [`ifac_verify`], which
/// requires at least one additional byte after the two-byte header.
@@ -65,11 +60,7 @@ pub fn try_ifac_sign(
if packet.len() < 2 {
return Err(IfacSignError::ShortPacket);
}
let mask_len = packet
.len()
.checked_add(ifac_size)
.filter(|len| *len <= MAX_IFAC_WIRE_BYTES)
.ok_or(IfacSignError::PacketTooLarge)?;
let mask_len = packet.len() + ifac_size;
let signing_seed: &[u8; 32] = ifac_key[32..64]
.try_into()
@@ -78,8 +69,7 @@ pub fn try_ifac_sign(
let signature = ed_key.sign(packet);
let tag = &signature[64 - ifac_size..];
let mask = hkdf_sha256(mask_len, tag, Some(ifac_key), None)
.map_err(|_| IfacSignError::PacketTooLarge)?;
let mask = hkdf_sha256(mask_len, tag, Some(ifac_key), None).expect("mask length is nonzero");
let mut new_raw = Vec::with_capacity(2 + ifac_size + packet.len() - 2);
new_raw.push(packet[0] | IFAC_FLAG);
@@ -107,7 +97,7 @@ pub fn try_ifac_sign(
/// Unmask an IFAC packet and compare its tag against the supplied shared key.
/// Return the inner packet bytes on a match; application payloads can still
/// be encrypted. Reject missing flags, invalid tag sizes, packets with no
/// byte after the two-byte header and tag, oversized masks, and mismatched
/// byte after the two-byte header and tag, and mismatched
/// tags. The comparison is constant-time; no inner packet parsing or replay
/// check is performed. Callers must discard `None` results.
pub fn ifac_verify(raw: &[u8], ifac_key: &[u8; 64], ifac_size: usize) -> Option<Vec<u8>> {
@@ -192,8 +192,7 @@ impl InterfacePacketCapacity {
Self::new(mtu, mtu, false)
}
/// Return the smaller of the clear budget and the wire budget minus IFAC.
/// Zero IFAC bytes means inactive; 1..=64 is active and also limits wire
/// size to the 8160-byte mask bound. Reject invalid tag sizes, zero budgets
/// Zero IFAC bytes means inactive; 1..=64 is active. Reject invalid tag sizes, zero budgets
/// and budgets with no room after the tag.
pub fn effective_clear_mtu(
self,
@@ -205,13 +204,8 @@ impl InterfacePacketCapacity {
if active_ifac_bytes > 64 {
return Err(InterfaceCapacityError::InvalidIfac);
}
let wire_limit = if active_ifac_bytes > 0 {
self.max_wire_packet_bytes
.min(crate::ifac::MAX_IFAC_WIRE_BYTES as u32)
} else {
self.max_wire_packet_bytes
};
let wire = usize::try_from(wire_limit).map_err(|_| InterfaceCapacityError::Empty)?;
let wire = usize::try_from(self.max_wire_packet_bytes)
.map_err(|_| InterfaceCapacityError::Empty)?;
let remaining =
wire.checked_sub(active_ifac_bytes)
.ok_or(InterfaceCapacityError::IfacExceedsWire {
+7 -3
View File
@@ -48,8 +48,8 @@ pub struct PacketReceipt {
pub callbacks: ReceiptCallbacks,
}
/// Optional callbacks consumed by delivery or failure methods.
/// Culling does not invoke either callback.
/// Optional callbacks consumed by delivery, failure or cull methods.
/// Culling invokes the timeout callback.
#[allow(missing_docs)]
#[derive(Default)]
pub struct ReceiptCallbacks {
@@ -117,10 +117,14 @@ impl PacketReceipt {
}
}
/// Transition to `Culled` without firing any callback.
/// Transition to `Culled` and fire the timeout callback, as the reference
/// `check_timeout` does for a culled receipt.
pub fn cull(&mut self) {
self.status = ReceiptStatus::Culled;
self.concluded_at = Some(Instant::now());
if let Some(cb) = self.callbacks.timeout.take() {
cb(self);
}
}
/// Elapsed time from creation to conclusion, for any concluded status.