认证与 AES-256-GCM 对称加密 (net/encryption.rs)
主线位置:主线 2 加密层 —— 剖析
fastlogging/src/net/encryption.rs如何使用ring::aead::AES_256_GCM进行 AEAD 认证加密,以及为什么它的NonceGenerator会在发送第 33 条日志时触发整数溢出。
EncryptionMethod 三种枚举变体
EncryptionMethod 定义了三种安全级别:
// fastlogging/src/net/encryption.rs#L4-L8
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum EncryptionMethod {
NONE,
AuthKey(Vec<u8>),
AES(Vec<u8>),
}
NONE/AuthKey(Vec<u8>):连接建立时校验首帧令牌,后续日志以明文传输;AES(Vec<u8>):要求传入 32 字节(256-bit) 密钥(通过aead::UnboundKey::new(&aead::AES_256_GCM, key_vec)构造SealingKey与OpeningKey),附加认证数据(AAD)固定为字符串"FastLoggingRs"(net/def.rs#L45)。
NonceGenerator 源码审计:一行 += 引发的指数爆炸
在 AES-GCM 中,每次调用 seal_in_place_append_tag 或 open_in_place 都必须提供一个在当前密钥下唯一且双端严格同步递增的 96-bit(12 字节)Nonce。为此,encryption.rs#L67-L90 实现了 ring::aead::NonceSequence trait:
// fastlogging/src/net/encryption.rs#L67-L90
#[derive(Debug)]
pub struct NonceGenerator {
last_nonce: u64,
}
impl NonceGenerator {
pub fn new() -> Self {
Self { last_nonce: 0 }
}
}
impl aead::NonceSequence for NonceGenerator {
fn advance(&mut self) -> Result<aead::Nonce, Unspecified> {
self.last_nonce += self.last_nonce.checked_add(1).ok_or(Unspecified)?;
let mut nonce = [0u8; 12];
nonce[0..8].copy_from_slice(&self.last_nonce.to_le_bytes());
Ok(aead::Nonce::assume_unique_for_key(nonce))
}
}
请看第 85 行:
self.last_nonce += self.last_nonce.checked_add(1).ok_or(Unspecified)?;
作者的本意显然是 self.last_nonce = self.last_nonce.checked_add(1).ok_or(Unspecified)?;(每次加 1)。但因为把 = 写成了 +=,等价于:
让我们算一下序列的变化:
- 初始值:
last_nonce = 0 - 第 1 次
advance():0 + (0 + 1) = 1() - 第 2 次
advance():1 + (1 + 1) = 3() - 第 3 次
advance():3 + (3 + 1) = 7() - ……
- 第 63 次
advance(): - 第 64 次
advance(): - 第 65 次
advance():self.last_nonce.checked_add(1)直接溢出返回None,转化成Err(ring::error::Unspecified)!
flowchart LR Init["last_nonce = 0"] -->|"第 1 次 advance"| N1["1 (2^1 - 1)"] N1 -->|"第 2 次 advance"| N2["3 (2^2 - 1)"] N2 -->|"..."| N64["第 64 次: u64::MAX (2^64 - 1)<br/>(对应第 32 条日志的 message)"] N64 -->|"第 65 次 advance (第 33 条日志)"| Err["checked_add(1) == None<br/>抛出 Unspecified 错误断开连接!"]
更致命的是,在 client.rs#L150-L155 中,每发送 1 条 日志消息,客户端会分别对 domain 和 message 调用两次 seal_in_place_append_tag(即消耗 2 次 advance())!因此:
- 前 32 条 日志共调用 次
advance(),刚好把last_nonce推到u64::MAX; - 当发送 第 33 条 日志时,对
domain的第 65 次advance()必然触发u64溢出,导致client_writer_thread报错Unspecified退出!
为什么仓库自带的单元测试 fastlogging/tests/ 没有发现这个在发送第 33 条消息时必现的 NonceGenerator 溢出 Bug?
动脑筋答案
因为在官方仓库的加密网络测试中,每个测试用例只发送了不到 10 条日志(trace、debug、info、warning、error、fatal 各 1~2 条,最多调用十几次 advance()),从未达到 33 条消息(65 次 advance())的溢出阈值。这也体现了在真实服务器(ssh cu)上进行压力与边界实测的价值。
小结
本节剖析了 net/encryption.rs 的加密机制与 NonceGenerator 的指数溢出问题。下一节我们将结合 ClientWriter 与 LoggingServer 的完整收发代码,在 ssh cu 上实测网络吞吐并复现服务端 handle_encrypted_client 的另外两处帧解析 Bug。

