feat: implement NTCP2 protocol, native TCP transport, and live I2P interop
This commit is contained in:
1 parent
dff69dfac6
commit
e6d1c464dd
12 files changed
+2557
-2
No files matched your search
@@ -0,0 +1,728 @@
|
||||
///|
|
||||
/// Pure-MoonBit I2P NTCP2 Protocol Engine (`Noise_XKaesobfse+hs2+hs3_25519_ChaChaPoly_SHA256`).
|
||||
/// Implements AES-256-CBC ephemeral key obfuscation, SessionRequest (Msg 1),
|
||||
/// SessionCreated (Msg 2), SessionConfirmed (Msg 3), and Data Phase KDF + SipHash-2-4 framing.
|
||||
|
||||
///|
|
||||
fn slice_b(data : Bytes, start : Int32, len : Int32) -> Bytes {
|
||||
let out = FixedArray::make(len, b'\x00')
|
||||
for i = 0; i < len; i = i + 1 {
|
||||
out[i] = data[start + i]
|
||||
}
|
||||
Bytes::from_array(out)
|
||||
}
|
||||
|
||||
///|
|
||||
fn concat_b(a : Bytes, b : Bytes) -> Bytes {
|
||||
let out = FixedArray::make(a.length() + b.length(), b'\x00')
|
||||
for i = 0; i < a.length(); i = i + 1 {
|
||||
out[i] = a[i]
|
||||
}
|
||||
for i = 0; i < b.length(); i = i + 1 {
|
||||
out[a.length() + i] = b[i]
|
||||
}
|
||||
Bytes::from_array(out)
|
||||
}
|
||||
|
||||
///|
|
||||
/// Options block inside NTCP2 Message 1 (SessionRequest), 16 bytes plaintext.
|
||||
#derive(Eq, Debug)
|
||||
pub(all) struct SessionRequestOptions {
|
||||
network_id : Byte // 2 for main I2P network
|
||||
version : Byte // 2 for NTCP2
|
||||
pad_len : UInt32 // uint16 cleartext padding length
|
||||
m3p2_len : UInt32 // uint16 Msg 3 Part 2 ciphertext length (including 16B MAC)
|
||||
timestamp_sec : UInt32 // uint32 Unix timestamp in seconds
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn SessionRequestOptions::encode(self : SessionRequestOptions) -> Bytes {
|
||||
let w = @encoding.Writer::new(capacity=16)
|
||||
w.write_u8(self.network_id)
|
||||
w.write_u8(self.version)
|
||||
w.write_u16_be(self.pad_len)
|
||||
w.write_u16_be(self.m3p2_len)
|
||||
w.write_u16_be(0U) // reserved
|
||||
w.write_u32_be(self.timestamp_sec)
|
||||
w.write_u32_be(0U) // reserved
|
||||
w.to_bytes()
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn SessionRequestOptions::decode(
|
||||
data : Bytes,
|
||||
) -> SessionRequestOptions raise Ntcp2Error {
|
||||
if data.length() != 16 {
|
||||
raise InvalidLength(
|
||||
"SessionRequest options must be 16 bytes, got \{data.length()}",
|
||||
)
|
||||
}
|
||||
let r = @encoding.Reader::new(data)
|
||||
let network_id = r.read_u8() catch { e => raise Encoding(e) }
|
||||
let version = r.read_u8() catch { e => raise Encoding(e) }
|
||||
let pad_len = r.read_u16_be() catch { e => raise Encoding(e) }
|
||||
let m3p2_len = r.read_u16_be() catch { e => raise Encoding(e) }
|
||||
let _ = r.read_u16_be() catch { e => raise Encoding(e) }
|
||||
let timestamp_sec = r.read_u32_be() catch { e => raise Encoding(e) }
|
||||
let _ = r.read_u32_be() catch { e => raise Encoding(e) }
|
||||
{ network_id, version, pad_len, m3p2_len, timestamp_sec, }
|
||||
}
|
||||
|
||||
///|
|
||||
/// Options block inside NTCP2 Message 2 (SessionCreated), 16 bytes plaintext.
|
||||
#derive(Eq, Debug)
|
||||
pub(all) struct SessionCreatedOptions {
|
||||
pad_len : UInt32 // uint16 cleartext padding length
|
||||
timestamp_sec : UInt32 // uint32 Unix timestamp in seconds
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn SessionCreatedOptions::encode(self : SessionCreatedOptions) -> Bytes {
|
||||
let w = @encoding.Writer::new(capacity=16)
|
||||
w.write_u16_be(0U) // reserved
|
||||
w.write_u16_be(self.pad_len)
|
||||
w.write_u32_be(0U) // reserved
|
||||
w.write_u32_be(self.timestamp_sec)
|
||||
w.write_u32_be(0U) // reserved
|
||||
w.to_bytes()
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn SessionCreatedOptions::decode(
|
||||
data : Bytes,
|
||||
) -> SessionCreatedOptions raise Ntcp2Error {
|
||||
if data.length() != 16 {
|
||||
raise InvalidLength(
|
||||
"SessionCreated options must be 16 bytes, got \{data.length()}",
|
||||
)
|
||||
}
|
||||
let r = @encoding.Reader::new(data)
|
||||
let _ = r.read_u16_be() catch { e => raise Encoding(e) }
|
||||
let pad_len = r.read_u16_be() catch { e => raise Encoding(e) }
|
||||
let _ = r.read_u32_be() catch { e => raise Encoding(e) }
|
||||
let timestamp_sec = r.read_u32_be() catch { e => raise Encoding(e) }
|
||||
let _ = r.read_u32_be() catch { e => raise Encoding(e) }
|
||||
{ pad_len, timestamp_sec, }
|
||||
}
|
||||
|
||||
///|
|
||||
/// Derived NTCP2 Data Phase SipHash-2-4 keys and initial IVs for both directions.
|
||||
#derive(Eq, Debug)
|
||||
pub(all) struct SipHashParams {
|
||||
key_ab : Bytes // 16-byte SipHash key (Alice -> Bob)
|
||||
iv_ab : Bytes // 8-byte initial IV (Alice -> Bob)
|
||||
key_ba : Bytes // 16-byte SipHash key (Bob -> Alice)
|
||||
iv_ba : Bytes // 8-byte initial IV (Bob -> Alice)
|
||||
}
|
||||
|
||||
///|
|
||||
/// Derives NTCP2 Data Phase SipHash-2-4 keys and IVs from final Noise `(ck, h)`.
|
||||
/// Per NTCP2 spec:
|
||||
/// - `temp_key = HMAC-SHA256(ck, "")`
|
||||
/// - `ask_master = HMAC-SHA256(temp_key, "ask" || 0x01)`
|
||||
/// - `temp_key_sip = HMAC-SHA256(ask_master, h || "siphash")`
|
||||
/// - `sip_master = HMAC-SHA256(temp_key_sip, 0x01)`
|
||||
/// - `temp_key_2 = HMAC-SHA256(sip_master, "")`
|
||||
/// - `sipkeys_ab = HMAC-SHA256(temp_key_2, 0x01)`
|
||||
/// - `sipkeys_ba = HMAC-SHA256(temp_key_2, sipkeys_ab || 0x02)`
|
||||
pub fn derive_siphash_params(ck : Bytes, h : Bytes) -> SipHashParams {
|
||||
let temp_key = @crypto.hmac_sha256(ck, b"")
|
||||
let ask_master = @crypto.hmac_sha256(temp_key, b"ask\x01")
|
||||
let temp_key_sip = @crypto.hmac_sha256(ask_master, concat_b(h, b"siphash"))
|
||||
let sip_master = @crypto.hmac_sha256(temp_key_sip, b"\x01")
|
||||
let temp_key_2 = @crypto.hmac_sha256(sip_master, b"")
|
||||
let sipkeys_ab = @crypto.hmac_sha256(temp_key_2, b"\x01")
|
||||
let sipkeys_ba = @crypto.hmac_sha256(
|
||||
temp_key_2,
|
||||
concat_b(sipkeys_ab, b"\x02"),
|
||||
)
|
||||
{
|
||||
key_ab: slice_b(sipkeys_ab, 0, 16),
|
||||
iv_ab: slice_b(sipkeys_ab, 16, 8),
|
||||
key_ba: slice_b(sipkeys_ba, 0, 16),
|
||||
iv_ba: slice_b(sipkeys_ba, 16, 8),
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// Post-handshake NTCP2 Data Phase session with ChaCha20-Poly1305 AEAD and
|
||||
/// SipHash-2-4 frame length obfuscation.
|
||||
pub struct Ntcp2DataSession {
|
||||
send_cipher : @noise.CipherState
|
||||
recv_cipher : @noise.CipherState
|
||||
send_mask : @noise.SipHashLengthMask
|
||||
recv_mask : @noise.SipHashLengthMask
|
||||
handshake_hash : Bytes
|
||||
remote_static : Bytes
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn Ntcp2DataSession::handshake_hash(self : Ntcp2DataSession) -> Bytes {
|
||||
self.handshake_hash
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn Ntcp2DataSession::remote_static(self : Ntcp2DataSession) -> Bytes {
|
||||
self.remote_static
|
||||
}
|
||||
|
||||
///|
|
||||
/// Encrypts a list of NTCP2 blocks into a complete wire frame:
|
||||
/// `obfuscated_len (2B BE) || ChaCha20-Poly1305(plaintext, ad="")`.
|
||||
pub fn Ntcp2DataSession::encrypt_frame(
|
||||
self : Ntcp2DataSession,
|
||||
blocks : Array[Ntcp2Block],
|
||||
) -> Bytes raise Ntcp2Error {
|
||||
let pt = encode_blocks(blocks)
|
||||
let ct = self.send_cipher.encrypt_with_ad(b"", pt) catch {
|
||||
e => raise Noise(e)
|
||||
}
|
||||
if ct.length() > 65535 {
|
||||
raise InvalidLength("NTCP2 data frame exceeds 65535 bytes: \{ct.length()}")
|
||||
}
|
||||
let obf_len = self.send_mask.xor_length(ct.length().reinterpret_as_uint()) catch {
|
||||
e => raise Noise(e)
|
||||
}
|
||||
let w = @encoding.Writer::new(capacity=2 + ct.length())
|
||||
w.write_u16_be(obf_len)
|
||||
w.write_bytes(ct)
|
||||
w.to_bytes()
|
||||
}
|
||||
|
||||
///|
|
||||
/// De-obfuscates the 2-byte big-endian wire length prefix for the next incoming frame.
|
||||
pub fn Ntcp2DataSession::unmask_frame_length(
|
||||
self : Ntcp2DataSession,
|
||||
obf_len_bytes : Bytes,
|
||||
) -> Int32 raise Ntcp2Error {
|
||||
if obf_len_bytes.length() != 2 {
|
||||
raise InvalidLength("NTCP2 frame length prefix must be 2 bytes")
|
||||
}
|
||||
let obf_len = (obf_len_bytes[0].to_uint() << 8) | obf_len_bytes[1].to_uint()
|
||||
let real_len = self.recv_mask.xor_length(obf_len) catch {
|
||||
e => raise Noise(e)
|
||||
}
|
||||
real_len.reinterpret_as_int()
|
||||
}
|
||||
|
||||
///|
|
||||
/// Decrypts a single NTCP2 data frame body (after reading `unmask_frame_length` bytes)
|
||||
/// and decodes its constituent NTCP2 blocks.
|
||||
pub fn Ntcp2DataSession::decrypt_frame_body(
|
||||
self : Ntcp2DataSession,
|
||||
ciphertext : Bytes,
|
||||
) -> Array[Ntcp2Block] raise Ntcp2Error {
|
||||
let pt = self.recv_cipher.decrypt_with_ad(b"", ciphertext) catch {
|
||||
e => raise Noise(e)
|
||||
}
|
||||
decode_blocks(pt)
|
||||
}
|
||||
|
||||
///|
|
||||
/// Convenience method that unmasks the 2-byte header and decrypts a complete wire frame.
|
||||
pub fn Ntcp2DataSession::decrypt_frame(
|
||||
self : Ntcp2DataSession,
|
||||
frame : Bytes,
|
||||
) -> Array[Ntcp2Block] raise Ntcp2Error {
|
||||
if frame.length() < 18 {
|
||||
raise InvalidLength("NTCP2 frame too short: \{frame.length()}")
|
||||
}
|
||||
let expected_len = self.unmask_frame_length(slice_b(frame, 0, 2))
|
||||
if frame.length() - 2 != expected_len {
|
||||
raise InvalidLength(
|
||||
"NTCP2 frame length mismatch: header=\{expected_len}, actual=\{frame.length() - 2}",
|
||||
)
|
||||
}
|
||||
self.decrypt_frame_body(slice_b(frame, 2, expected_len))
|
||||
}
|
||||
|
||||
///|
|
||||
/// NTCP2 Handshake State Machine (Initiator / Alice and Responder / Bob).
|
||||
pub struct Ntcp2Handshake {
|
||||
sym : @noise.SymmetricState
|
||||
initiator : Bool
|
||||
local_static : @noise.KeyPair
|
||||
mut local_ephemeral : @noise.KeyPair?
|
||||
mut remote_static : Bytes?
|
||||
mut remote_ephemeral : Bytes?
|
||||
responder_hash : Bytes // 32-byte RH_B (AES-256-CBC key)
|
||||
published_iv : Bytes // 16-byte published 'i' IV (AES-256-CBC IV for Msg 1)
|
||||
mut msg2_iv : Bytes // 16-byte IV for Msg 2 (= last 16 bytes of obfuscated X)
|
||||
mut m3p2_len : Int32 // advertised Msg 3 Part 2 ciphertext length
|
||||
mut step : Int32 // 0: msg1, 1: msg2, 2: msg3, 3: done
|
||||
}
|
||||
|
||||
///|
|
||||
/// Creates an NTCP2 initiator (Alice) handshake state targeting responder Bob.
|
||||
/// - `local_static`: Alice's X25519 static keypair
|
||||
/// - `remote_static`: Bob's 32-byte X25519 static public key (`s` in RouterInfo)
|
||||
/// - `responder_hash`: Bob's 32-byte RouterIdentity SHA-256 hash (`RH_B`)
|
||||
/// - `published_iv`: Bob's 16-byte published IV (`i` in RouterInfo)
|
||||
pub fn Ntcp2Handshake::new_initiator(
|
||||
local_static : @noise.KeyPair,
|
||||
remote_static : Bytes,
|
||||
responder_hash : Bytes,
|
||||
published_iv : Bytes,
|
||||
) -> Ntcp2Handshake raise Ntcp2Error {
|
||||
if remote_static.length() != 32 {
|
||||
raise InvalidLength("remote_static must be 32 bytes")
|
||||
}
|
||||
if responder_hash.length() != 32 {
|
||||
raise InvalidLength("responder_hash must be 32 bytes")
|
||||
}
|
||||
if published_iv.length() != 16 {
|
||||
raise InvalidLength("published_iv must be 16 bytes")
|
||||
}
|
||||
let sym = @noise.SymmetricState::initialize(@noise.ntcp2_protocol_name)
|
||||
sym.mix_hash(b"") // empty prologue
|
||||
sym.mix_hash(remote_static) // pre-message: <- s
|
||||
{
|
||||
sym,
|
||||
initiator: true,
|
||||
local_static,
|
||||
local_ephemeral: None,
|
||||
remote_static: Some(remote_static),
|
||||
remote_ephemeral: None,
|
||||
responder_hash,
|
||||
published_iv,
|
||||
msg2_iv: Bytes::make(16, b'\x00'),
|
||||
m3p2_len: 0,
|
||||
step: 0,
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// Creates an NTCP2 responder (Bob) handshake state.
|
||||
pub fn Ntcp2Handshake::new_responder(
|
||||
local_static : @noise.KeyPair,
|
||||
local_router_hash : Bytes,
|
||||
published_iv : Bytes,
|
||||
) -> Ntcp2Handshake raise Ntcp2Error {
|
||||
if local_router_hash.length() != 32 {
|
||||
raise InvalidLength("local_router_hash must be 32 bytes")
|
||||
}
|
||||
if published_iv.length() != 16 {
|
||||
raise InvalidLength("published_iv must be 16 bytes")
|
||||
}
|
||||
let sym = @noise.SymmetricState::initialize(@noise.ntcp2_protocol_name)
|
||||
sym.mix_hash(b"") // empty prologue
|
||||
sym.mix_hash(local_static.public_key) // pre-message: <- s
|
||||
{
|
||||
sym,
|
||||
initiator: false,
|
||||
local_static,
|
||||
local_ephemeral: None,
|
||||
remote_static: None,
|
||||
remote_ephemeral: None,
|
||||
responder_hash: local_router_hash,
|
||||
published_iv,
|
||||
msg2_iv: Bytes::make(16, b'\x00'),
|
||||
m3p2_len: 0,
|
||||
step: 0,
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// Sets the local ephemeral X25519 keypair before writing Message 1 (initiator) or Message 2 (responder).
|
||||
pub fn Ntcp2Handshake::set_ephemeral(
|
||||
self : Ntcp2Handshake,
|
||||
ephemeral : @noise.KeyPair,
|
||||
) -> Unit {
|
||||
self.local_ephemeral = Some(ephemeral)
|
||||
}
|
||||
|
||||
///|
|
||||
/// Returns the advertised Msg 3 Part 2 ciphertext length (including 16-byte MAC).
|
||||
pub fn Ntcp2Handshake::m3p2_len(self : Ntcp2Handshake) -> Int32 {
|
||||
self.m3p2_len
|
||||
}
|
||||
|
||||
///|
|
||||
/// Initiator: writes Message 1 (SessionRequest).
|
||||
/// Returns `X_obf (32B) || AEAD(options_16B) (32B) || cleartext_padding`.
|
||||
pub fn Ntcp2Handshake::write_session_request(
|
||||
self : Ntcp2Handshake,
|
||||
m3p2_ciphertext_len : Int32,
|
||||
timestamp_sec : UInt32,
|
||||
padding~ : Bytes = b"",
|
||||
network_id~ : Byte = b'\x02',
|
||||
) -> Bytes raise Ntcp2Error {
|
||||
if !self.initiator || self.step != 0 {
|
||||
raise InvalidState(
|
||||
"write_session_request only valid for initiator at step 0",
|
||||
)
|
||||
}
|
||||
let ephem = match self.local_ephemeral {
|
||||
Some(kp) => kp
|
||||
None => raise InvalidState("initiator ephemeral key not set")
|
||||
}
|
||||
let rs = match self.remote_static {
|
||||
Some(k) => k
|
||||
None => raise InvalidState("remote static key missing")
|
||||
}
|
||||
// e
|
||||
self.sym.mix_hash(ephem.public_key)
|
||||
// es
|
||||
let dh_es = @crypto.x25519(ephem.private_key, rs) catch {
|
||||
e => raise Crypto(e)
|
||||
}
|
||||
self.sym.mix_key(dh_es)
|
||||
// Encrypt 16-byte options
|
||||
let opts : SessionRequestOptions = {
|
||||
network_id,
|
||||
version: b'\x02',
|
||||
pad_len: padding.length().reinterpret_as_uint(),
|
||||
m3p2_len: m3p2_ciphertext_len.reinterpret_as_uint(),
|
||||
timestamp_sec,
|
||||
}
|
||||
let enc_opts = self.sym.encrypt_and_hash(opts.encode()) catch {
|
||||
e => raise Noise(e)
|
||||
}
|
||||
// MixHash(padding) only if pad_len > 0 (per NTCP2 spec)
|
||||
if padding.length() > 0 {
|
||||
self.sym.mix_hash(padding)
|
||||
}
|
||||
// Obfuscate X with AES-256-CBC(RH_B, published_iv)
|
||||
let x_obf = @crypto.aes256_cbc_encrypt(
|
||||
self.responder_hash,
|
||||
self.published_iv,
|
||||
ephem.public_key,
|
||||
) catch {
|
||||
e => raise Crypto(e)
|
||||
}
|
||||
// Save last 16 bytes of X_obf as IV for Msg 2
|
||||
self.msg2_iv = slice_b(x_obf, 16, 16)
|
||||
self.m3p2_len = m3p2_ciphertext_len
|
||||
self.step = 1
|
||||
concat_b(concat_b(x_obf, enc_opts), padding)
|
||||
}
|
||||
|
||||
///|
|
||||
/// Responder: reads the first 64 bytes of Message 1 (SessionRequest), decrypting options
|
||||
/// and returning `SessionRequestOptions` (caller must then read `opts.pad_len` bytes of
|
||||
/// cleartext padding and pass them to `finish_read_session_request`).
|
||||
pub fn Ntcp2Handshake::read_session_request_head(
|
||||
self : Ntcp2Handshake,
|
||||
head64 : Bytes,
|
||||
) -> SessionRequestOptions raise Ntcp2Error {
|
||||
if self.initiator || self.step != 0 {
|
||||
raise InvalidState(
|
||||
"read_session_request_head only valid for responder at step 0",
|
||||
)
|
||||
}
|
||||
if head64.length() != 64 {
|
||||
raise InvalidLength(
|
||||
"SessionRequest head must be 64 bytes, got \{head64.length()}",
|
||||
)
|
||||
}
|
||||
let x_obf = slice_b(head64, 0, 32)
|
||||
let enc_opts = slice_b(head64, 32, 32)
|
||||
// De-obfuscate X
|
||||
let x = @crypto.aes256_cbc_decrypt(
|
||||
self.responder_hash,
|
||||
self.published_iv,
|
||||
x_obf,
|
||||
) catch {
|
||||
e => raise Crypto(e)
|
||||
}
|
||||
self.remote_ephemeral = Some(x)
|
||||
self.msg2_iv = slice_b(x_obf, 16, 16)
|
||||
// e
|
||||
self.sym.mix_hash(x)
|
||||
// es
|
||||
let dh_es = @crypto.x25519(self.local_static.private_key, x) catch {
|
||||
e => raise Crypto(e)
|
||||
}
|
||||
self.sym.mix_key(dh_es)
|
||||
// Decrypt options
|
||||
let opts_bytes = self.sym.decrypt_and_hash(enc_opts) catch {
|
||||
e => raise Noise(e)
|
||||
}
|
||||
let opts = SessionRequestOptions::decode(opts_bytes)
|
||||
if opts.version != b'\x02' {
|
||||
raise InvalidFormat("unsupported NTCP2 version: \{opts.version.to_int()}")
|
||||
}
|
||||
self.m3p2_len = opts.m3p2_len.reinterpret_as_int()
|
||||
opts
|
||||
}
|
||||
|
||||
///|
|
||||
/// Responder: mixes the cleartext padding from Message 1 and advances state to step 1.
|
||||
pub fn Ntcp2Handshake::finish_read_session_request(
|
||||
self : Ntcp2Handshake,
|
||||
padding : Bytes,
|
||||
) -> Unit raise Ntcp2Error {
|
||||
if self.initiator || self.step != 0 {
|
||||
raise InvalidState(
|
||||
"finish_read_session_request only valid for responder at step 0",
|
||||
)
|
||||
}
|
||||
if padding.length() > 0 {
|
||||
self.sym.mix_hash(padding)
|
||||
}
|
||||
self.step = 1
|
||||
}
|
||||
|
||||
///|
|
||||
/// Responder: convenience method to read a complete Message 1 buffer in one call.
|
||||
pub fn Ntcp2Handshake::read_session_request(
|
||||
self : Ntcp2Handshake,
|
||||
msg1 : Bytes,
|
||||
) -> SessionRequestOptions raise Ntcp2Error {
|
||||
if msg1.length() < 64 {
|
||||
raise InvalidLength("SessionRequest shorter than 64 bytes")
|
||||
}
|
||||
let opts = self.read_session_request_head(slice_b(msg1, 0, 64))
|
||||
let pad_len = opts.pad_len.reinterpret_as_int()
|
||||
if msg1.length() != 64 + pad_len {
|
||||
raise InvalidLength(
|
||||
"SessionRequest length mismatch: expected \{64 + pad_len}, got \{msg1.length()}",
|
||||
)
|
||||
}
|
||||
let padding = if pad_len > 0 { slice_b(msg1, 64, pad_len) } else { b"" }
|
||||
self.finish_read_session_request(padding)
|
||||
opts
|
||||
}
|
||||
|
||||
///|
|
||||
/// Responder: writes Message 2 (SessionCreated).
|
||||
/// Returns `Y_obf (32B) || AEAD(options_16B) (32B) || cleartext_padding`.
|
||||
pub fn Ntcp2Handshake::write_session_created(
|
||||
self : Ntcp2Handshake,
|
||||
timestamp_sec : UInt32,
|
||||
padding~ : Bytes = b"",
|
||||
) -> Bytes raise Ntcp2Error {
|
||||
if self.initiator || self.step != 1 {
|
||||
raise InvalidState(
|
||||
"write_session_created only valid for responder at step 1",
|
||||
)
|
||||
}
|
||||
let ephem = match self.local_ephemeral {
|
||||
Some(kp) => kp
|
||||
None => raise InvalidState("responder ephemeral key not set")
|
||||
}
|
||||
let re = match self.remote_ephemeral {
|
||||
Some(k) => k
|
||||
None => raise InvalidState("remote ephemeral key missing")
|
||||
}
|
||||
// e
|
||||
self.sym.mix_hash(ephem.public_key)
|
||||
// ee
|
||||
let dh_ee = @crypto.x25519(ephem.private_key, re) catch {
|
||||
e => raise Crypto(e)
|
||||
}
|
||||
self.sym.mix_key(dh_ee)
|
||||
// Encrypt 16-byte options
|
||||
let opts : SessionCreatedOptions = {
|
||||
pad_len: padding.length().reinterpret_as_uint(),
|
||||
timestamp_sec,
|
||||
}
|
||||
let enc_opts = self.sym.encrypt_and_hash(opts.encode()) catch {
|
||||
e => raise Noise(e)
|
||||
}
|
||||
if padding.length() > 0 {
|
||||
self.sym.mix_hash(padding)
|
||||
}
|
||||
// Obfuscate Y with AES-256-CBC(RH_B, msg2_iv)
|
||||
let y_obf = @crypto.aes256_cbc_encrypt(
|
||||
self.responder_hash,
|
||||
self.msg2_iv,
|
||||
ephem.public_key,
|
||||
) catch {
|
||||
e => raise Crypto(e)
|
||||
}
|
||||
self.step = 2
|
||||
concat_b(concat_b(y_obf, enc_opts), padding)
|
||||
}
|
||||
|
||||
///|
|
||||
/// Initiator: reads the first 64 bytes of Message 2 (SessionCreated), returning
|
||||
/// `SessionCreatedOptions` (caller must then read `opts.pad_len` bytes and pass
|
||||
/// them to `finish_read_session_created`).
|
||||
pub fn Ntcp2Handshake::read_session_created_head(
|
||||
self : Ntcp2Handshake,
|
||||
head64 : Bytes,
|
||||
) -> SessionCreatedOptions raise Ntcp2Error {
|
||||
if !self.initiator || self.step != 1 {
|
||||
raise InvalidState(
|
||||
"read_session_created_head only valid for initiator at step 1",
|
||||
)
|
||||
}
|
||||
if head64.length() != 64 {
|
||||
raise InvalidLength(
|
||||
"SessionCreated head must be 64 bytes, got \{head64.length()}",
|
||||
)
|
||||
}
|
||||
let y_obf = slice_b(head64, 0, 32)
|
||||
let enc_opts = slice_b(head64, 32, 32)
|
||||
// De-obfuscate Y
|
||||
let y = @crypto.aes256_cbc_decrypt(self.responder_hash, self.msg2_iv, y_obf) catch {
|
||||
e => raise Crypto(e)
|
||||
}
|
||||
self.remote_ephemeral = Some(y)
|
||||
// e
|
||||
self.sym.mix_hash(y)
|
||||
// ee
|
||||
let ephem = match self.local_ephemeral {
|
||||
Some(kp) => kp
|
||||
None => raise InvalidState("initiator ephemeral key missing")
|
||||
}
|
||||
let dh_ee = @crypto.x25519(ephem.private_key, y) catch {
|
||||
e => raise Crypto(e)
|
||||
}
|
||||
self.sym.mix_key(dh_ee)
|
||||
let opts_bytes = self.sym.decrypt_and_hash(enc_opts) catch {
|
||||
e => raise Noise(e)
|
||||
}
|
||||
SessionCreatedOptions::decode(opts_bytes)
|
||||
}
|
||||
|
||||
///|
|
||||
/// Initiator: mixes the cleartext padding from Message 2 and advances state to step 2.
|
||||
pub fn Ntcp2Handshake::finish_read_session_created(
|
||||
self : Ntcp2Handshake,
|
||||
padding : Bytes,
|
||||
) -> Unit raise Ntcp2Error {
|
||||
if !self.initiator || self.step != 1 {
|
||||
raise InvalidState(
|
||||
"finish_read_session_created only valid for initiator at step 1",
|
||||
)
|
||||
}
|
||||
if padding.length() > 0 {
|
||||
self.sym.mix_hash(padding)
|
||||
}
|
||||
self.step = 2
|
||||
}
|
||||
|
||||
///|
|
||||
/// Initiator: convenience method to read a complete Message 2 buffer in one call.
|
||||
pub fn Ntcp2Handshake::read_session_created(
|
||||
self : Ntcp2Handshake,
|
||||
msg2 : Bytes,
|
||||
) -> SessionCreatedOptions raise Ntcp2Error {
|
||||
if msg2.length() < 64 {
|
||||
raise InvalidLength("SessionCreated shorter than 64 bytes")
|
||||
}
|
||||
let opts = self.read_session_created_head(slice_b(msg2, 0, 64))
|
||||
let pad_len = opts.pad_len.reinterpret_as_int()
|
||||
if msg2.length() != 64 + pad_len {
|
||||
raise InvalidLength(
|
||||
"SessionCreated length mismatch: expected \{64 + pad_len}, got \{msg2.length()}",
|
||||
)
|
||||
}
|
||||
let padding = if pad_len > 0 { slice_b(msg2, 64, pad_len) } else { b"" }
|
||||
self.finish_read_session_created(padding)
|
||||
opts
|
||||
}
|
||||
|
||||
///|
|
||||
/// Initiator: writes Message 3 (SessionConfirmed) containing Part 1 (48B encrypted static key)
|
||||
/// and Part 2 (`m3p2_len` bytes encrypted blocks, starting with Alice's RouterInfo block).
|
||||
pub fn Ntcp2Handshake::write_session_confirmed(
|
||||
self : Ntcp2Handshake,
|
||||
blocks : Array[Ntcp2Block],
|
||||
) -> Bytes raise Ntcp2Error {
|
||||
if !self.initiator || self.step != 2 {
|
||||
raise InvalidState(
|
||||
"write_session_confirmed only valid for initiator at step 2",
|
||||
)
|
||||
}
|
||||
let re = match self.remote_ephemeral {
|
||||
Some(k) => k
|
||||
None => raise InvalidState("remote ephemeral key missing")
|
||||
}
|
||||
let pt2 = encode_blocks(blocks)
|
||||
if pt2.length() + 16 != self.m3p2_len {
|
||||
raise InvalidLength(
|
||||
"SessionConfirmed part 2 ciphertext len \{pt2.length() + 16} != advertised m3p2_len \{self.m3p2_len}",
|
||||
)
|
||||
}
|
||||
// Part 1: s
|
||||
let enc_s = self.sym.encrypt_and_hash(self.local_static.public_key) catch {
|
||||
e => raise Noise(e)
|
||||
}
|
||||
// se
|
||||
let dh_se = @crypto.x25519(self.local_static.private_key, re) catch {
|
||||
e => raise Crypto(e)
|
||||
}
|
||||
self.sym.mix_key(dh_se)
|
||||
// Part 2: payload blocks
|
||||
let enc_p2 = self.sym.encrypt_and_hash(pt2) catch { e => raise Noise(e) }
|
||||
self.step = 3
|
||||
concat_b(enc_s, enc_p2)
|
||||
}
|
||||
|
||||
///|
|
||||
/// Responder: reads Message 3 (SessionConfirmed, `48 + m3p2_len` bytes) and returns
|
||||
/// the decoded Part 2 blocks (containing Alice's RouterInfo block).
|
||||
pub fn Ntcp2Handshake::read_session_confirmed(
|
||||
self : Ntcp2Handshake,
|
||||
msg3 : Bytes,
|
||||
) -> Array[Ntcp2Block] raise Ntcp2Error {
|
||||
if self.initiator || self.step != 2 {
|
||||
raise InvalidState(
|
||||
"read_session_confirmed only valid for responder at step 2",
|
||||
)
|
||||
}
|
||||
let expected = 48 + self.m3p2_len
|
||||
if msg3.length() != expected {
|
||||
raise InvalidLength(
|
||||
"SessionConfirmed length mismatch: expected \{expected}, got \{msg3.length()}",
|
||||
)
|
||||
}
|
||||
let enc_s = slice_b(msg3, 0, 48)
|
||||
let enc_p2 = slice_b(msg3, 48, self.m3p2_len)
|
||||
// Part 1: s
|
||||
let rs = self.sym.decrypt_and_hash(enc_s) catch { e => raise Noise(e) }
|
||||
self.remote_static = Some(rs)
|
||||
// se
|
||||
let ephem = match self.local_ephemeral {
|
||||
Some(kp) => kp
|
||||
None => raise InvalidState("responder ephemeral key missing")
|
||||
}
|
||||
let dh_se = @crypto.x25519(ephem.private_key, rs) catch {
|
||||
e => raise Crypto(e)
|
||||
}
|
||||
self.sym.mix_key(dh_se)
|
||||
// Part 2: payload blocks
|
||||
let pt2 = self.sym.decrypt_and_hash(enc_p2) catch { e => raise Noise(e) }
|
||||
self.step = 3
|
||||
decode_blocks(pt2)
|
||||
}
|
||||
|
||||
///|
|
||||
/// Completes the NTCP2 handshake and transitions into a bidirectional `Ntcp2DataSession`.
|
||||
pub fn Ntcp2Handshake::into_data_session(
|
||||
self : Ntcp2Handshake,
|
||||
) -> Ntcp2DataSession raise Ntcp2Error {
|
||||
if self.step != 3 {
|
||||
raise InvalidState("NTCP2 handshake not complete (step=\{self.step})")
|
||||
}
|
||||
let rs = match self.remote_static {
|
||||
Some(k) => k
|
||||
None => raise InvalidState("remote static key missing")
|
||||
}
|
||||
let ck = self.sym.chaining_key()
|
||||
let h = self.sym.handshake_hash()
|
||||
let (c_ab, c_ba) = self.sym.split()
|
||||
let sip = derive_siphash_params(ck, h)
|
||||
let mask_ab = @noise.SipHashLengthMask::new(sip.key_ab, sip.iv_ab) catch {
|
||||
e => raise Noise(e)
|
||||
}
|
||||
let mask_ba = @noise.SipHashLengthMask::new(sip.key_ba, sip.iv_ba) catch {
|
||||
e => raise Noise(e)
|
||||
}
|
||||
let (send_cipher, recv_cipher, send_mask, recv_mask) = if self.initiator {
|
||||
(c_ab, c_ba, mask_ab, mask_ba)
|
||||
} else {
|
||||
(c_ba, c_ab, mask_ba, mask_ab)
|
||||
}
|
||||
{
|
||||
send_cipher,
|
||||
recv_cipher,
|
||||
send_mask,
|
||||
recv_mask,
|
||||
handshake_hash: h,
|
||||
remote_static: rs,
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user