Files
moon-i2p/tunnel/build.mbt
T

275 lines
8.4 KiB
MoonBit

///|
/// Errors raised by the I2P Tunnel subsystem (ShortTunnelBuild, TunnelData framing, layer crypto).
#derive(Eq, Debug)
pub suberror TunnelError {
Crypto(@crypto.CryptoError)
Encoding(@encoding.EncodingError)
Common(@common.CommonError)
InvalidLength(String)
InvalidFormat(String)
ChecksumMismatch
RecordNotForUs
}
///|
/// Proposal 157 ShortTunnelBuild Noise protocol name for ECIES-X25519 record encryption.
let stbm_protocol_name : Bytes = b"Noise_N_25519_ChaChaPoly_SHA256"
///|
fn t_slice(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 t_concat(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)
}
///|
/// Hop-derived symmetric keys from a Proposal 157 ShortTunnelBuild record.
#derive(Eq, Debug)
pub(all) struct HopKeys {
reply_key : Bytes // 32-byte ChaCha20-Poly1305 key for ShortBuildReplyRecord
layer_key : Bytes // 32-byte AES-256 tunnel layer key
iv_key : Bytes // 32-byte AES-256 tunnel IV key
handshake_hash : Bytes // 32-byte AD `h` for reply AEAD
}
///|
/// Cleartext 154-byte Proposal 157 ShortBuildRequestRecord.
#derive(Eq, Debug)
pub(all) struct ShortBuildRequestRecord {
receive_tunnel_id : UInt32
next_tunnel_id : UInt32
next_ident : @common.Hash
flag : Byte // bit 7 = IBGW (0x80), bit 6 = OBEP (0x40)
layer_enc_type : Byte // 0 = AES-256-CBC
request_time_min : UInt32 // minutes since Unix epoch
request_expiration_sec : UInt32 // seconds (typically 600)
send_message_id : UInt32
options : @common.Mapping
}
///|
pub fn ShortBuildRequestRecord::encode_154(
self : ShortBuildRequestRecord,
) -> Bytes raise TunnelError {
let w = @encoding.Writer::new(capacity=154)
w.write_u32_be(self.receive_tunnel_id)
w.write_u32_be(self.next_tunnel_id)
self.next_ident.encode(w)
w.write_u8(self.flag)
w.write_u16_be(0U) // more_flags
w.write_u8(self.layer_enc_type)
w.write_u32_be(self.request_time_min)
w.write_u32_be(self.request_expiration_sec)
w.write_u32_be(self.send_message_id)
self.options.encode(w) catch {
e => raise Common(e)
}
let prefix = w.to_bytes()
if prefix.length() > 154 {
raise InvalidLength(
"ShortBuildRequestRecord exceeds 154 bytes: \{prefix.length()}",
)
}
let out = FixedArray::make(154, b'\x00')
for i = 0; i < prefix.length(); i = i + 1 {
out[i] = prefix[i]
}
Bytes::from_array(out)
}
///|
pub fn ShortBuildRequestRecord::decode_154(
data : Bytes,
) -> ShortBuildRequestRecord raise TunnelError {
if data.length() != 154 {
raise InvalidLength(
"ShortBuildRequestRecord must be 154 bytes, got \{data.length()}",
)
}
let r = @encoding.Reader::new(data)
let receive_tunnel_id = r.read_u32_be() catch { e => raise Encoding(e) }
let next_tunnel_id = r.read_u32_be() catch { e => raise Encoding(e) }
let next_ident = @common.Hash::decode(r) catch { e => raise Common(e) }
let flag = r.read_u8() catch { e => raise Encoding(e) }
let _ = r.read_u16_be() catch { e => raise Encoding(e) }
let layer_enc_type = r.read_u8() catch { e => raise Encoding(e) }
let request_time_min = r.read_u32_be() catch { e => raise Encoding(e) }
let request_expiration_sec = r.read_u32_be() catch { e => raise Encoding(e) }
let send_message_id = r.read_u32_be() catch { e => raise Encoding(e) }
let options = @common.Mapping::decode(r) catch { e => raise Common(e) }
{
receive_tunnel_id,
next_tunnel_id,
next_ident,
flag,
layer_enc_type,
request_time_min,
request_expiration_sec,
send_message_id,
options,
}
}
///|
fn derive_hop_keys(ck : Bytes, h : Bytes) -> HopKeys raise TunnelError {
// Derive 96 bytes = reply_key (32) || layer_key (32) || iv_key (32) via HKDF-SHA256
let okm = @crypto.hkdf(ck, b"", b"SMTunnelReplyKey", 96) catch {
e => raise Crypto(e)
}
{
reply_key: t_slice(okm, 0, 32),
layer_key: t_slice(okm, 32, 32),
iv_key: t_slice(okm, 64, 32),
handshake_hash: h,
}
}
///|
fn stbm_init_state(
hop_static_pub : Bytes,
ephem_pub : Bytes,
dh : Bytes,
) -> (Bytes, Bytes, Bytes) {
let sym = @noise.SymmetricState::initialize(stbm_protocol_name)
sym.mix_hash(b"") // prologue
sym.mix_hash(hop_static_pub) // <- s
sym.mix_hash(ephem_pub) // -> e
sym.mix_key(dh) // es
let ck = sym.chaining_key()
let h = sym.handshake_hash()
// Extract the AEAD encryption key from ck/dh via standard Noise HKDF
let temp_k = @crypto.hmac_sha256(
@crypto.hmac_sha256(
@noise.SymmetricState::initialize(stbm_protocol_name).chaining_key(),
dh,
),
t_concat(ck, b"\x02"),
)
(ck, h, temp_k)
}
///|
/// Encrypts a 154-byte `ShortBuildRequestRecord` into a 218-byte Proposal 157 build record
/// targeting `hop_ident_hash` / `hop_static_pub` using `ephemeral` X25519 keypair.
/// Returns `(encrypted_218B, derived_hop_keys)`.
pub fn encrypt_short_build_record(
record : ShortBuildRequestRecord,
hop_ident_hash : @common.Hash,
hop_static_pub : Bytes,
ephemeral : @noise.KeyPair,
) -> (Bytes, HopKeys) raise TunnelError {
if hop_static_pub.length() != 32 {
raise InvalidLength("hop_static_pub must be 32 bytes")
}
let pt = record.encode_154()
let dh = @crypto.x25519(ephemeral.private_key, hop_static_pub) catch {
e => raise Crypto(e)
}
let (ck, h, enc_key) = stbm_init_state(
hop_static_pub,
ephemeral.public_key,
dh,
)
let nonce = Bytes::make(12, b'\x00')
let ct = @crypto.aead_chacha20_poly1305_encrypt(enc_key, nonce, h, pt) catch {
e => raise Crypto(e)
}
let h_after = @crypto.sha256(t_concat(h, ct))
let keys = derive_hop_keys(ck, h_after)
// 218 bytes = to_peer[0..16] || ephem_pub (32B) || ciphertext (170B)
let to_peer = t_slice(hop_ident_hash.as_bytes(), 0, 16)
let out = t_concat(t_concat(to_peer, ephemeral.public_key), ct)
(out, keys)
}
///|
/// Attempts to decrypt a 218-byte Proposal 157 build record addressed to `local_ident_hash`.
/// Raises `RecordNotForUs` if the 16-byte `to_peer` prefix does not match.
pub fn decrypt_short_build_record(
record_218 : Bytes,
local_ident_hash : @common.Hash,
local_static : @noise.KeyPair,
) -> (ShortBuildRequestRecord, HopKeys) raise TunnelError {
if record_218.length() != 218 {
raise InvalidLength(
"ShortTunnelBuild record must be 218 bytes, got \{record_218.length()}",
)
}
let to_peer = t_slice(record_218, 0, 16)
let expected_prefix = t_slice(local_ident_hash.as_bytes(), 0, 16)
if !@crypto.ct_eq(to_peer, expected_prefix) {
raise RecordNotForUs
}
let ephem_pub = t_slice(record_218, 16, 32)
let ct = t_slice(record_218, 48, 170)
let dh = @crypto.x25519(local_static.private_key, ephem_pub) catch {
e => raise Crypto(e)
}
let (ck, h, enc_key) = stbm_init_state(local_static.public_key, ephem_pub, dh)
let nonce = Bytes::make(12, b'\x00')
let pt = @crypto.aead_chacha20_poly1305_decrypt(enc_key, nonce, h, ct) catch {
e => raise Crypto(e)
}
let h_after = @crypto.sha256(t_concat(h, ct))
let keys = derive_hop_keys(ck, h_after)
let rec = ShortBuildRequestRecord::decode_154(pt)
(rec, keys)
}
///|
/// Encrypts a 218-byte Proposal 157 `ShortBuildReplyRecord` (`reply_code`: `0` = accept, `30` = reject).
pub fn encrypt_short_build_reply(
keys : HopKeys,
reply_code : Byte,
) -> Bytes raise TunnelError {
let pt = FixedArray::make(202, b'\x00')
// 2-byte empty options mapping (0x00, 0x00) + padding + final reply byte at index 201
pt[201] = reply_code
let nonce = Bytes::make(12, b'\x00')
@crypto.aead_chacha20_poly1305_encrypt(
keys.reply_key,
nonce,
keys.handshake_hash,
Bytes::from_array(pt),
) catch {
e => raise Crypto(e)
}
}
///|
/// Decrypts a 218-byte Proposal 157 `ShortBuildReplyRecord` and returns its `reply_code` byte (`0` = accept).
pub fn decrypt_short_build_reply(
keys : HopKeys,
reply_218 : Bytes,
) -> Byte raise TunnelError {
if reply_218.length() != 218 {
raise InvalidLength(
"ShortBuildReplyRecord must be 218 bytes, got \{reply_218.length()}",
)
}
let nonce = Bytes::make(12, b'\x00')
let pt = @crypto.aead_chacha20_poly1305_decrypt(
keys.reply_key,
nonce,
keys.handshake_hash,
reply_218,
) catch {
e => raise Crypto(e)
}
pt[201]
}