Files
ssw-mpc/crates/mpc-node/src/secure.rs
T
admin 54781b3f83
ci / gate (push) Waiting to run
refactor: 项目改名 ssw-mpc,crate 统一到 mpc-* 前缀
- 项目与文档标题:nax-rs → ssw-mpc(尚数网-多方安全计算),二进制 nax → mpc
- 18 个 crate 及目录 nax-* → mpc-*,Rust 引用 nax_* → mpc_*
- 环境变量、C 符号、构建/部署脚本:NAX_* → MPC_*、libnax_ray.so → libmpc_ray.so
- 保留协议域分隔常量与 refs/nax 参考实现路径,维持 golden 向量与历史数据兼容
- 新增 [profile.dev] incremental=false
2026-11-05 15:06:12 +08:00

293 lines
10 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! 链路加密:把每一帧包进 ChaCha20-Poly1305。
//!
//! # 与 [`crate::auth`] 的分工
//!
//! * `auth` 解决「**你是谁**」—— PSK 挑战-应答,挡住冒充参与方。
//! * `secure` 解决「**别人看不看得见、改不改得动**」—— 挡住嗅探与篡改。
//!
//! 两者都建立在同一把 PSK 上:握手先在明文里用 HMAC 签 nonce 完成认证,
//! 认证成功后由同一次握手的上下文派生会话密钥,之后的每个字节都走 AEAD。
//! 握手本身不需要加密(交换的是 nonce,tag 已保证完整性)。
//!
//! # 线格式
//!
//! ```text
//! [ u32 正文长度 ][ 密文 (n 字节) ][ tag (16 字节) ]
//! ^ 明文是一整帧 Frame::encode() 的字节
//! ```
//!
//! AAD 用的是那个 4 字节长度字段本身 —— 攻击者改长度会立刻让 tag 失效。
//! 长度字段无法被认证地"先于"读取,所以只能这样绑;好在它一旦被改,
//! 要么读不到足够字节(阻塞后超时),要么解密失败,两种都会明确报错。
//!
//! # nonce 与重放
//!
//! 每个方向一个 `u64` 计数器,nonce = `0^4 ‖ 计数器`。TCP 保序,所以
//! **接收侧要求计数器严格对齐当前值**:攻击者重放上一次的帧,会用错位的
//! nonce 解密,tag 必然不匹配 —— 重放自动被拒,不需要额外的序号表。
use std::io::{Read, Write};
use std::net::TcpStream;
use mpc_core::aead::{self, KEY_LEN, NONCE_LEN, TAG_LEN};
use mpc_core::MpcError;
use mpc_proto::MAX_PAYLOAD;
use crate::auth::SessionKeys;
use crate::NodeError;
/// 一个封好的帧在网络上占的最大字节数。
pub const MAX_SEALED: usize = 4 + MAX_PAYLOAD + TAG_LEN;
/// 一条连接上的加密状态:两个方向各一把密钥、一个计数器。
pub struct SecureChannel {
key_out: [u8; KEY_LEN],
key_in: [u8; KEY_LEN],
ctr_out: u64,
ctr_in: u64,
}
impl SecureChannel {
/// 主动方视角:发用 `c2s`,收用 `s2c`。
pub fn for_client(keys: &SessionKeys) -> Self {
Self {
key_out: *keys.c2s(),
key_in: *keys.s2c(),
ctr_out: 0,
ctr_in: 0,
}
}
/// 被动方视角:发用 `s2c`,收用 `c2s`。
pub fn for_server(keys: &SessionKeys) -> Self {
Self {
key_out: *keys.s2c(),
key_in: *keys.c2s(),
ctr_out: 0,
ctr_in: 0,
}
}
/// 已封帧数(发送方向),测试与诊断用。
pub fn frames_out(&self) -> u64 {
self.ctr_out
}
/// 已解帧数(接收方向)。
pub fn frames_in(&self) -> u64 {
self.ctr_in
}
/// 封一帧:返回可整段写进 TCP 的字节。
pub fn seal(&mut self, plain: &[u8]) -> Result<Vec<u8>, NodeError> {
if plain.len() > MAX_PAYLOAD {
return Err(NodeError::Crypto(format!(
"要发的帧 {} 字节,超过上限 {MAX_PAYLOAD}",
plain.len()
)));
}
let len = plain.len() as u32;
let aad = len.to_le_bytes();
let mut out = vec![0u8; 4 + plain.len() + TAG_LEN];
out[..4].copy_from_slice(&aad);
aead::seal(&self.key_out, &nonce_for(self.ctr_out), &aad, plain, &mut out[4..])
.map_err(to_node_err)?;
self.ctr_out = self
.ctr_out
.checked_add(1)
.ok_or_else(|| NodeError::Crypto("发送计数器用尽".into()))?;
Ok(out)
}
/// 解一帧。`wire` 必须是完整的一帧(4 + n + 16)。
pub fn open(&mut self, wire: &[u8]) -> Result<Vec<u8>, NodeError> {
if wire.len() < 4 + TAG_LEN {
return Err(NodeError::Crypto(format!(
"密文帧只有 {} 字节,不足 4+16",
wire.len()
)));
}
let len = u32::from_le_bytes([wire[0], wire[1], wire[2], wire[3]]) as usize;
if len > MAX_PAYLOAD {
return Err(NodeError::Crypto(format!(
"对端声明正文 {len} 字节,超过上限 {MAX_PAYLOAD}"
)));
}
if wire.len() != 4 + len + TAG_LEN {
return Err(NodeError::Crypto(format!(
"密文帧长度不符:声明 {len},实际整帧 {} 字节(应为 {})",
wire.len(),
4 + len + TAG_LEN
)));
}
let mut out = vec![0u8; len];
aead::open(
&self.key_in,
&nonce_for(self.ctr_in),
&wire[..4],
&wire[4..],
&mut out,
)
.map_err(to_node_err)?;
self.ctr_in = self
.ctr_in
.checked_add(1)
.ok_or_else(|| NodeError::Crypto("接收计数器用尽".into()))?;
Ok(out)
}
/// 封一帧并整段写进流。
pub fn write_frame(&mut self, stream: &mut TcpStream, plain: &[u8]) -> Result<(), NodeError> {
let wire = self.seal(plain)?;
stream
.write_all(&wire)
.map_err(|e| NodeError::Io(format!("write: {e}")))?;
stream
.flush()
.map_err(|e| NodeError::Io(format!("flush: {e}")))?;
Ok(())
}
/// 从流里读满一帧并解密。
pub fn read_frame(&mut self, stream: &mut TcpStream) -> Result<Vec<u8>, NodeError> {
let mut head = [0u8; 4];
stream
.read_exact(&mut head)
.map_err(|e| NodeError::Io(format!("read header: {e}")))?;
let len = u32::from_le_bytes(head) as usize;
if len > MAX_PAYLOAD {
return Err(NodeError::Crypto(format!(
"对端声明正文 {len} 字节,超过上限 {MAX_PAYLOAD}"
)));
}
let mut wire = vec![0u8; 4 + len + TAG_LEN];
wire[..4].copy_from_slice(&head);
stream
.read_exact(&mut wire[4..])
.map_err(|e| NodeError::Io(format!("read body: {e}")))?;
self.open(&wire)
}
}
/// nonce = `0^4 ‖ 计数器`(12 字节)。
///
/// 前 4 字节留零而不是放方向标记:方向已经由**两把不同密钥**隔开,
/// 再塞标记只是重复表达,反而让 nonce 空间少 2^32。
fn nonce_for(ctr: u64) -> [u8; NONCE_LEN] {
let mut n = [0u8; NONCE_LEN];
n[4..].copy_from_slice(&ctr.to_be_bytes());
n
}
fn to_node_err(e: MpcError) -> NodeError {
match e {
// 这一条要单独说清楚:它不是「参数写错」,而是有人在动链路,
// 或者两边的会话密钥根本对不上(PSK 派生不一致)。
MpcError::TagMismatch => {
NodeError::Crypto("AEAD 校验失败:链路被篡改,或双方的会话密钥不一致".into())
}
other => NodeError::Crypto(other.to_string()),
}
}
#[cfg(test)]
mod tests {
use super::*;
/// 造一对方向正确的密钥(不跑真握手,只测封装层)。
fn keys_pair() -> SessionKeys {
crate::auth::session_keys(&[42u8; 32], 0, 1, &[1u8; 16], &[2u8; 16])
}
#[test]
fn roundtrip_both_directions() {
let keys = keys_pair();
let mut c = SecureChannel::for_client(&keys);
let mut s = SecureChannel::for_server(&keys);
for i in 0..5u8 {
let msg = vec![i; 100 + i as usize];
let wire = c.seal(&msg).unwrap();
assert_eq!(s.open(&wire).unwrap(), msg, "c→s 第 {i} 帧");
}
for i in 0..3u8 {
let msg = vec![200 + i; 7];
let wire = s.seal(&msg).unwrap();
assert_eq!(c.open(&wire).unwrap(), msg, "s→c 第 {i} 帧");
}
assert_eq!(c.frames_out(), 5);
assert_eq!(s.frames_in(), 5);
}
#[test]
fn wire_does_not_contain_plaintext() {
let keys = keys_pair();
let mut c = SecureChannel::for_client(&keys);
let secret = b"balance=1000000;id=42;region=east";
let wire = c.seal(secret).unwrap();
assert!(
!wire.windows(secret.len()).any(|w| w == secret),
"密文里出现了明文片段"
);
}
#[test]
fn tampered_byte_is_rejected() {
let keys = keys_pair();
let mut c = SecureChannel::for_client(&keys);
let mut s = SecureChannel::for_server(&keys);
let wire = c.seal(b"hello world, this is a frame").unwrap();
for i in 0..wire.len() {
let mut bad = wire.clone();
bad[i] ^= 0x01;
// 改长度字段可能先被长度校验拦下,改正文/标签则必定是 tag 错 —— 都要报错
assert!(s.open(&bad).is_err(), "第 {i} 字节被改却没报错");
}
}
#[test]
fn replay_is_rejected() {
let keys = keys_pair();
let mut c = SecureChannel::for_client(&keys);
let mut s = SecureChannel::for_server(&keys);
let wire = c.seal(b"only once").unwrap();
s.open(&wire).unwrap();
// 原样再送一次:接收侧计数器已前进,nonce 错位 → tag 不匹配
assert!(s.open(&wire).is_err(), "重放没有被拒");
}
#[test]
fn wrong_direction_key_fails() {
let keys = keys_pair();
let mut c = SecureChannel::for_client(&keys);
let wire = c.seal(b"x").unwrap();
// 用同一个方向密钥去解 → 解不开
let mut c2 = SecureChannel::for_client(&keys);
assert!(c2.open(&wire).is_err(), "同向密钥不该能解");
}
#[test]
fn stream_io_roundtrip() {
let keys = keys_pair();
let k2 = keys.clone();
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let h = std::thread::spawn(move || {
let (mut s, _) = listener.accept().unwrap();
let mut ch = SecureChannel::for_server(&k2);
assert_eq!(ch.read_frame(&mut s).unwrap(), b"ping over tcp");
ch.write_frame(&mut s, b"pong over tcp").unwrap();
});
let mut s = TcpStream::connect(addr).unwrap();
let mut ch = SecureChannel::for_client(&keys);
ch.write_frame(&mut s, b"ping over tcp").unwrap();
assert_eq!(ch.read_frame(&mut s).unwrap(), b"pong over tcp");
h.join().unwrap();
}
}