Files
moon-i2p/ratchet/ecies.mbt
T
nandi 14eae00f5c
check / check (macos-latest) (push) Failing after 27s
check / check (ubuntu-latest) (push) Failing after 28s
check / check (windows-latest) (push) Failing after 26s
feat: add HTTP-over-I2P proxy to router daemon
- Add --http-proxy/--proxy [host:port] (default 127.0.0.1:4444) to route .i2p and .b32.i2p HTTP requests over I2P streams
- Block clearnet hosts with 403 and reject CONNECT and https:// with 501
- Support ?i2paddresshelper= jump links that register host aliases
- Add `just proxy` target and -h/--help usage output
- Expire idle ratchet sessions after 300s and add RatchetSessionManager::drop_session for fresh NewSession handshakes
- Add NetDb::remove_lease_set2 and bound the outbound pending queue to 64 entries
2026-11-28 01:46:36 -08:00

878 lines
26 KiB
MoonBit

///|
/// Pure-MoonBit Proposal 144 ECIES-X25519-AEAD-Ratchet Engine:
/// - `Noise_IKelg2+hs2_25519_ChaChaPoly_SHA256`
/// - Elligator2 ephemeral keys
/// - Bound & Unbound New Session (`NS`), New Session Reply (`NSR`), Existing Session (`ES`)
/// - Symmetric Ratchet (`STInitialization`, `SessionTagKeyGen`, `SymmetricRatchet`) & DH Ratchet (`NextKey`)
/// - Proposal 154 ECIES `DatabaseLookup` encrypted DSM reply.
///|
pub let ecies_protocol_name : Bytes = b"Noise_IKelg2+hs2_25519_ChaChaPoly_SHA256"
///|
pub let router_garlic_protocol_name : Bytes = b"Noise_N_25519_ChaChaPoly_SHA256"
///|
fn r_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 make_ecies_nonce(n : UInt32) -> Bytes {
let buf = FixedArray::make(12, b'\x00')
let v = n.to_uint64()
for i = 0; i < 8; i = i + 1 {
buf[4 + i] = ((v >> (i * 8)) & 0xFFUL).to_byte()
}
Bytes::from_array(buf)
}
///|
/// X25519 ephemeral keypair guaranteed to have a valid Curve25519 Elligator2 representation.
#derive(Eq, Debug)
pub(all) struct ElligatorKeyPair {
private_key : Bytes
public_key : Bytes
elligator_repr : Bytes
}
///|
/// Generates an X25519 keypair with a valid Elligator2 representative using `next_rand_32`.
pub fn generate_elligator_keypair(
next_rand_32 : () -> Bytes,
) -> ElligatorKeyPair raise RatchetError {
for _attempt = 0; _attempt < 128; _attempt = _attempt + 1 {
let priv_key = next_rand_32()
if priv_key.length() != 32 {
raise InvalidLength("random key must be 32 bytes")
}
let pub_key = @crypto.x25519_public_key(priv_key) catch {
e => raise Crypto(e)
}
let tweak_seed = next_rand_32()
let high_bits = (tweak_seed[0].to_int() & 0xC0).to_byte()
let tweak_sign = (tweak_seed[1].to_int() & 1) != 0
let rep_opt = @crypto.elligator2_encode(pub_key, high_bits~, tweak_sign~) catch {
e => raise Crypto(e)
}
match rep_opt {
Some(rep) =>
return {
private_key: priv_key,
public_key: pub_key,
elligator_repr: rep,
}
None => ()
}
}
raise InvalidFormat(
"failed to sample Elligator2-encodable keypair after 128 attempts",
)
}
///|
/// Proposal 144 Tag & Symmetric Key Ratchet state (`STInitialization` -> `SessionTagKeyGen` / `SymmetricRatchet`).
pub struct TagSet {
mut tag_ck : Bytes
sesstag_const : Bytes
mut symm_ck : Bytes
mut msg_num : UInt32
}
///|
/// Runs Proposal 144 `DH_INITIALIZE(root_key, k)`:
/// 1. `KDFDHRatchetStep` -> `(next_root_key, ck)`
/// 2. `TagAndKeyGenKeys` -> `(sess_tag_ck, symm_key_ck)`
/// 3. `STInitialization` -> `(tag_ck, sesstag_const)`
pub fn dh_initialize(
root_key : Bytes,
k : Bytes,
) -> (Bytes, TagSet) raise RatchetError {
let kd = @crypto.hkdf(root_key, k, b"KDFDHRatchetStep", 64) catch {
e => raise Crypto(e)
}
let next_root_key = r_slice(kd, 0, 32)
let ck = r_slice(kd, 32, 32)
let tk = @crypto.hkdf(ck, b"", b"TagAndKeyGenKeys", 64) catch {
e => raise Crypto(e)
}
let sess_tag_ck = r_slice(tk, 0, 32)
let symm_ck = r_slice(tk, 32, 32)
let st = @crypto.hkdf(sess_tag_ck, b"", b"STInitialization", 64) catch {
e => raise Crypto(e)
}
let tag_ck = r_slice(st, 0, 32)
let sesstag_const = r_slice(st, 32, 32)
(next_root_key, { tag_ck, sesstag_const, symm_ck, msg_num: 0U, })
}
///|
/// Advances both the session tag ratchet and symmetric key ratchet by one message index,
/// returning `(msg_num, tag_8B, symm_key_32B)`.
pub fn TagSet::next_entry(
self : TagSet,
) -> (UInt32, Bytes, Bytes) raise RatchetError {
let kd_tag = @crypto.hkdf(
self.tag_ck,
self.sesstag_const,
b"SessionTagKeyGen",
64,
) catch {
e => raise Crypto(e)
}
self.tag_ck = r_slice(kd_tag, 0, 32)
let tag = r_slice(kd_tag, 32, 8)
let kd_key = @crypto.hkdf(self.symm_ck, b"", b"SymmetricRatchet", 64) catch {
e => raise Crypto(e)
}
self.symm_ck = r_slice(kd_key, 0, 32)
let symm_key = r_slice(kd_key, 32, 32)
let n = self.msg_num
self.msg_num = self.msg_num + 1U
(n, tag, symm_key)
}
///|
/// State captured after sending or receiving a Bound New Session, needed for New Session Reply (`NSR`).
pub struct PendingNewSession {
ck : Bytes
h : Bytes
local_ephem_priv : Bytes
remote_ephem_pub : Bytes
remote_static_pub : Bytes
nsr_tagset : TagSet
}
///|
/// Encrypts a Proposal 144 New Session (`NS`) message (`bound` if `initiator_static` is `Some`, else unbound).
/// Wire format: `e_elg2 (32B) || enc_s (48B) || enc_payload`.
/// For Bound NS, also returns `Some(PendingNewSession)` to process the peer's `NSR`.
pub fn encrypt_new_session(
initiator_static : @noise.KeyPair?,
responder_static_pub : Bytes,
ephem : ElligatorKeyPair,
blocks : Array[RatchetBlock],
) -> (Bytes, PendingNewSession?) raise RatchetError {
if responder_static_pub.length() != 32 {
raise InvalidLength("responder_static_pub must be 32 bytes")
}
let sym = @noise.SymmetricState::initialize(ecies_protocol_name)
sym.mix_hash(b"") // null prologue
sym.mix_hash(responder_static_pub) // <- s
sym.mix_hash(ephem.public_key) // -> e (unencoded X25519 key)
let es = @crypto.x25519(ephem.private_key, responder_static_pub) catch {
e => raise Crypto(e)
}
sym.mix_key(es)
let (enc_s, is_bound) = match initiator_static {
Some(kp) => {
let es_ct = sym.encrypt_and_hash(kp.public_key) catch {
e => raise Noise(e)
}
let ss = @crypto.x25519(kp.private_key, responder_static_pub) catch {
e => raise Crypto(e)
}
sym.mix_key(ss)
(es_ct, true)
}
None => {
let es_ct = sym.encrypt_and_hash(Bytes::make(32, b'\x00')) catch {
e => raise Noise(e)
}
(es_ct, false)
}
}
let pt = encode_blocks(blocks)
let enc_payload = sym.encrypt_and_hash(pt) catch { e => raise Noise(e) }
let w = @encoding.Writer::new(capacity=80 + enc_payload.length())
w.write_bytes(ephem.elligator_repr)
w.write_bytes(enc_s)
w.write_bytes(enc_payload)
let wire = w.to_bytes()
if is_bound {
let ck = sym.chaining_key()
let h = sym.handshake_hash()
let tagset_key = @crypto.hkdf(ck, b"", b"SessionReplyTags", 32) catch {
e => raise Crypto(e)
}
let (_rk, nsr_tagset) = dh_initialize(ck, tagset_key)
(
wire,
Some({
ck,
h,
local_ephem_priv: ephem.private_key,
remote_ephem_pub: responder_static_pub,
remote_static_pub: responder_static_pub,
nsr_tagset,
}),
)
} else {
(wire, None)
}
}
///|
/// Decrypts an incoming Proposal 144 New Session (`NS`) message.
/// Returns `(decoded_blocks, pending_ns_if_bound)`.
pub fn decrypt_new_session(
responder_static : @noise.KeyPair,
ns_bytes : Bytes,
) -> (Array[RatchetBlock], PendingNewSession?) raise RatchetError {
if ns_bytes.length() < 96 {
raise InvalidLength("NewSession shorter than 96 bytes")
}
let elg_repr = r_slice(ns_bytes, 0, 32)
let enc_s = r_slice(ns_bytes, 32, 48)
let enc_payload = r_slice(ns_bytes, 80, ns_bytes.length() - 80)
let re_pub = @crypto.elligator2_decode(elg_repr) catch {
e => raise Crypto(e)
}
let sym = @noise.SymmetricState::initialize(ecies_protocol_name)
sym.mix_hash(b"")
sym.mix_hash(responder_static.public_key)
sym.mix_hash(re_pub)
let es = @crypto.x25519(responder_static.private_key, re_pub) catch {
e => raise Crypto(e)
}
sym.mix_key(es)
let rs_plain = sym.decrypt_and_hash(enc_s) catch {
_ => raise AuthenticationFailed
}
let is_bound = !@crypto.ct_eq(rs_plain, Bytes::make(32, b'\x00'))
if is_bound {
let ss = @crypto.x25519(responder_static.private_key, rs_plain) catch {
e => raise Crypto(e)
}
sym.mix_key(ss)
}
let pt = sym.decrypt_and_hash(enc_payload) catch {
_ => raise AuthenticationFailed
}
let blocks = decode_blocks(pt)
if is_bound {
let ck = sym.chaining_key()
let h = sym.handshake_hash()
let tagset_key = @crypto.hkdf(ck, b"", b"SessionReplyTags", 32) catch {
e => raise Crypto(e)
}
let (_rk, nsr_tagset) = dh_initialize(ck, tagset_key)
(
blocks,
Some({
ck,
h,
local_ephem_priv: b"",
remote_ephem_pub: re_pub,
remote_static_pub: rs_plain,
nsr_tagset,
}),
)
} else {
(blocks, None)
}
}
///|
/// Active bidirectional ECIES-X25519-AEAD-Ratchet session state for an established peer.
pub struct RatchetPeerSession {
remote_static_pub : Bytes
mut send_root_key : Bytes
mut send_tagset : TagSet
mut recv_root_key : Bytes
mut recv_tagset : TagSet
recv_window : Array[(UInt32, Bytes, Bytes)] // (msg_num, tag_8B, symm_key_32B)
mut dh_ratchet_key_id : UInt32
mut local_next_priv : Bytes?
mut local_next_pub : Bytes?
mut remote_next_pub : Bytes?
mut last_used_sec : UInt32
}
///|
fn RatchetPeerSession::refill_recv_window(
self : RatchetPeerSession,
target_size~ : Int32 = 32,
) -> Unit raise RatchetError {
while self.recv_window.length() < target_size {
let (n, tag, key) = self.recv_tagset.next_entry()
self.recv_window.push((n, tag, key))
}
}
///|
fn RatchetPeerSession::try_decrypt_es(
self : RatchetPeerSession,
tag_8 : Bytes,
ct : Bytes,
) -> Array[RatchetBlock]? raise RatchetError {
for idx = 0; idx < self.recv_window.length(); idx = idx + 1 {
let (msg_num, expected_tag, key) = self.recv_window[idx]
if @crypto.ct_eq(expected_tag, tag_8) {
let nonce = make_ecies_nonce(msg_num)
let pt = @crypto.aead_chacha20_poly1305_decrypt(key, nonce, tag_8, ct) catch {
_ => raise AuthenticationFailed
}
let _ = self.recv_window.remove(idx)
self.refill_recv_window()
return Some(decode_blocks(pt))
}
}
None
}
///|
/// Encrypts an Existing Session (`ES`) payload frame (`8B tag || AEAD ciphertext`).
pub fn RatchetPeerSession::encrypt_existing(
self : RatchetPeerSession,
blocks : Array[RatchetBlock],
) -> Bytes raise RatchetError {
let (msg_num, tag_8, key) = self.send_tagset.next_entry()
let pt = encode_blocks(blocks)
let nonce = make_ecies_nonce(msg_num)
let ct = @crypto.aead_chacha20_poly1305_encrypt(key, nonce, tag_8, pt) catch {
e => raise Crypto(e)
}
let w = @encoding.Writer::new(capacity=8 + ct.length())
w.write_bytes(tag_8)
w.write_bytes(ct)
w.to_bytes()
}
///|
/// Advances this session's send/receive tagsets by performing a DH ratchet step
/// with `local_priv` and `remote_pub`.
pub fn RatchetPeerSession::apply_dh_ratchet(
self : RatchetPeerSession,
local_priv : Bytes,
remote_pub : Bytes,
for_send~ : Bool,
) -> Unit raise RatchetError {
let shared = @crypto.x25519(local_priv, remote_pub) catch {
e => raise Crypto(e)
}
if for_send {
let (next_rk, ts) = dh_initialize(self.send_root_key, shared)
self.send_root_key = next_rk
self.send_tagset = ts
} else {
let (next_rk, ts) = dh_initialize(self.recv_root_key, shared)
self.recv_root_key = next_rk
self.recv_tagset = ts
self.recv_window.clear()
self.refill_recv_window()
}
}
///|
/// Responder creates a New Session Reply (`NSR`) from `pending` (obtained via `decrypt_new_session`),
/// returning `(nsr_wire_bytes, established_session)`.
pub fn encrypt_new_session_reply(
pending : PendingNewSession,
ephem_b : ElligatorKeyPair,
blocks : Array[RatchetBlock],
) -> (Bytes, RatchetPeerSession) raise RatchetError {
let (_tag_n, nsr_tag, _nsr_key) = pending.nsr_tagset.next_entry()
let sym = @noise.SymmetricState::from_parts(pending.ck, pending.h)
sym.mix_hash(nsr_tag)
sym.mix_hash(ephem_b.public_key)
let ee = @crypto.x25519(ephem_b.private_key, pending.remote_ephem_pub) catch {
e => raise Crypto(e)
}
sym.mix_key(ee)
let se = @crypto.x25519(ephem_b.private_key, pending.remote_static_pub) catch {
e => raise Crypto(e)
}
sym.mix_key(se)
let key_sec_mac = sym.encrypt_and_hash(b"") catch { e => raise Noise(e) }
let ck = sym.chaining_key()
let h = sym.handshake_hash()
let split_kd = @crypto.hkdf(ck, b"", b"", 64) catch { e => raise Crypto(e) }
let k_ab = r_slice(split_kd, 0, 32)
let k_ba = r_slice(split_kd, 32, 32)
let (root_ab, tagset_ab) = dh_initialize(ck, k_ab)
let (root_ba, tagset_ba) = dh_initialize(ck, k_ba)
let k_payload = @crypto.hkdf(k_ba, b"", b"AttachPayloadKDF", 32) catch {
e => raise Crypto(e)
}
let pt = encode_blocks(blocks)
let enc_payload = @crypto.aead_chacha20_poly1305_encrypt(
k_payload,
Bytes::make(12, b'\x00'),
h,
pt,
) catch {
e => raise Crypto(e)
}
let w = @encoding.Writer::new(capacity=56 + enc_payload.length())
w.write_bytes(nsr_tag)
w.write_bytes(ephem_b.elligator_repr)
w.write_bytes(key_sec_mac)
w.write_bytes(enc_payload)
let sess : RatchetPeerSession = {
remote_static_pub: pending.remote_static_pub,
send_root_key: root_ba,
send_tagset: tagset_ba,
recv_root_key: root_ab,
recv_tagset: tagset_ab,
recv_window: [],
dh_ratchet_key_id: 0U,
local_next_priv: None,
local_next_pub: None,
remote_next_pub: None,
last_used_sec: 0U,
}
sess.refill_recv_window()
(w.to_bytes(), sess)
}
///|
/// Initiator decrypts an incoming New Session Reply (`NSR`), verifying `nsr_tag` and
/// returning `(decoded_blocks, established_session)`.
pub fn decrypt_new_session_reply(
initiator_static : @noise.KeyPair,
pending : PendingNewSession,
nsr_bytes : Bytes,
) -> (Array[RatchetBlock], RatchetPeerSession) raise RatchetError {
if nsr_bytes.length() < 72 {
raise InvalidLength("NewSessionReply shorter than 72 bytes")
}
let nsr_tag = r_slice(nsr_bytes, 0, 8)
let elg_repr = r_slice(nsr_bytes, 8, 32)
let key_sec_mac = r_slice(nsr_bytes, 40, 16)
let enc_payload = r_slice(nsr_bytes, 56, nsr_bytes.length() - 56)
let e_b_pub = @crypto.elligator2_decode(elg_repr) catch {
e => raise Crypto(e)
}
let sym = @noise.SymmetricState::from_parts(pending.ck, pending.h)
sym.mix_hash(nsr_tag)
sym.mix_hash(e_b_pub)
let ee = @crypto.x25519(pending.local_ephem_priv, e_b_pub) catch {
e => raise Crypto(e)
}
sym.mix_key(ee)
let se = @crypto.x25519(initiator_static.private_key, e_b_pub) catch {
e => raise Crypto(e)
}
sym.mix_key(se)
let _ = sym.decrypt_and_hash(key_sec_mac) catch {
_ => raise AuthenticationFailed
}
let ck = sym.chaining_key()
let h = sym.handshake_hash()
let split_kd = @crypto.hkdf(ck, b"", b"", 64) catch { e => raise Crypto(e) }
let k_ab = r_slice(split_kd, 0, 32)
let k_ba = r_slice(split_kd, 32, 32)
let (root_ab, tagset_ab) = dh_initialize(ck, k_ab)
let (root_ba, tagset_ba) = dh_initialize(ck, k_ba)
let k_payload = @crypto.hkdf(k_ba, b"", b"AttachPayloadKDF", 32) catch {
e => raise Crypto(e)
}
let pt = @crypto.aead_chacha20_poly1305_decrypt(
k_payload,
Bytes::make(12, b'\x00'),
h,
enc_payload,
) catch {
_ => raise AuthenticationFailed
}
let blocks = decode_blocks(pt)
let sess : RatchetPeerSession = {
remote_static_pub: pending.remote_static_pub,
send_root_key: root_ab,
send_tagset: tagset_ab,
recv_root_key: root_ba,
recv_tagset: tagset_ba,
recv_window: [],
dh_ratchet_key_id: 0U,
local_next_priv: None,
local_next_pub: None,
remote_next_pub: None,
last_used_sec: 0U,
}
sess.refill_recv_window()
(blocks, sess)
}
///|
/// Proposal 154 ECIES `DatabaseLookup` encrypted DatabaseStore/DatabaseSearchReply payload:
/// `reply_tag (8B) || ChaCha20-Poly1305(reply_key, nonce=0, ad=reply_tag, blocks)`.
pub fn encrypt_ecies_lookup_reply(
reply_key : Bytes,
reply_tag : Bytes,
blocks : Array[RatchetBlock],
) -> Bytes raise RatchetError {
if reply_key.length() != 32 || reply_tag.length() != 8 {
raise InvalidLength("ECIES lookup reply requires 32B key and 8B tag")
}
let pt = encode_blocks(blocks)
let ct = @crypto.aead_chacha20_poly1305_encrypt(
reply_key,
Bytes::make(12, b'\x00'),
reply_tag,
pt,
) catch {
e => raise Crypto(e)
}
let w = @encoding.Writer::new(capacity=8 + ct.length())
w.write_bytes(reply_tag)
w.write_bytes(ct)
w.to_bytes()
}
///|
/// Decrypts a Proposal 154 ECIES `DatabaseLookup` reply using `(reply_key, reply_tag)`.
pub fn decrypt_ecies_lookup_reply(
reply_key : Bytes,
reply_tag : Bytes,
data : Bytes,
) -> Array[RatchetBlock] raise RatchetError {
if data.length() < 24 || reply_key.length() != 32 || reply_tag.length() != 8 {
raise InvalidLength("invalid ECIES lookup reply parameters or length")
}
let wire_tag = r_slice(data, 0, 8)
if !@crypto.ct_eq(wire_tag, reply_tag) {
raise AuthenticationFailed
}
let ct = r_slice(data, 8, data.length() - 8)
let pt = @crypto.aead_chacha20_poly1305_decrypt(
reply_key,
Bytes::make(12, b'\x00'),
reply_tag,
ct,
) catch {
_ => raise AuthenticationFailed
}
decode_blocks(pt)
}
///|
/// Encrypts Garlic blocks to a router's static X25519 key using Proposal 144 `Noise_N_25519_ChaChaPoly_SHA256`
/// (canonical `WrapECIESX25519MessageForRouter`: `raw_ephem_pub (32B) || AEAD ciphertext`).
pub fn encrypt_router_garlic(
remote_static_pub : Bytes,
ephemeral : @noise.KeyPair,
blocks : Array[RatchetBlock],
) -> Bytes raise RatchetError {
if remote_static_pub.length() != 32 {
raise InvalidLength("remote_static_pub must be 32 bytes")
}
let sym = @noise.SymmetricState::initialize(router_garlic_protocol_name)
sym.mix_hash(b"") // null prologue
sym.mix_hash(remote_static_pub)
sym.mix_hash(ephemeral.public_key)
let dh = @crypto.x25519(ephemeral.private_key, remote_static_pub) catch {
e => raise Crypto(e)
}
sym.mix_key(dh)
let pt = encode_blocks(blocks)
let ct = sym.encrypt_and_hash(pt) catch { e => raise Noise(e) }
let w = @encoding.Writer::new(capacity=32 + ct.length())
w.write_bytes(ephemeral.public_key)
w.write_bytes(ct)
w.to_bytes()
}
///|
/// Decrypts a router-targeted `Noise_N_25519_ChaChaPoly_SHA256` Garlic message addressed to `local_static`.
pub fn decrypt_router_garlic(
local_static : @noise.KeyPair,
data : Bytes,
) -> Array[RatchetBlock] raise RatchetError {
if data.length() < 48 {
raise InvalidLength("Router Garlic shorter than 48 bytes")
}
let ephem_pub = r_slice(data, 0, 32)
let ct = r_slice(data, 32, data.length() - 32)
let sym = @noise.SymmetricState::initialize(router_garlic_protocol_name)
sym.mix_hash(b"")
sym.mix_hash(local_static.public_key)
sym.mix_hash(ephem_pub)
let dh = @crypto.x25519(local_static.private_key, ephem_pub) catch {
e => raise Crypto(e)
}
sym.mix_key(dh)
let pt = sym.decrypt_and_hash(ct) catch { _ => raise AuthenticationFailed }
decode_blocks(pt)
}
///|
/// High-level session manager handling New Session, New Session Reply, and Existing Session
/// state transitions for a local I2P Destination.
pub struct RatchetSessionManager {
local_static : @noise.KeyPair
sessions : Array[RatchetPeerSession]
outbound_pending : Array[(Bytes, PendingNewSession)] // (nsr_tag_8, pending)
inbound_pending : Array[PendingNewSession] // waiting to send NSR to remote_static_pub
}
///|
pub fn RatchetSessionManager::new(
local_static : @noise.KeyPair,
) -> RatchetSessionManager {
{ local_static, sessions: [], outbound_pending: [], inbound_pending: [], }
}
///|
fn RatchetSessionManager::find_session(
self : RatchetSessionManager,
remote_static_pub : Bytes,
) -> Int32 {
for i = 0; i < self.sessions.length(); i = i + 1 {
if @crypto.ct_eq(self.sessions[i].remote_static_pub, remote_static_pub) {
return i
}
}
-1
}
///|
/// Drops any established or pending outbound ratchet state for `remote_static_pub`
/// so subsequent sends start a fresh Bound `NewSession` handshake.
pub fn RatchetSessionManager::drop_session(
self : RatchetSessionManager,
remote_static_pub : Bytes,
) -> Unit {
let mut si = 0
while si < self.sessions.length() {
if @crypto.ct_eq(self.sessions[si].remote_static_pub, remote_static_pub) {
let _ = self.sessions.remove(si)
} else {
si += 1
}
}
let mut pi = 0
while pi < self.outbound_pending.length() {
if @crypto.ct_eq(
self.outbound_pending[pi].1.remote_static_pub,
remote_static_pub,
) {
let _ = self.outbound_pending.remove(pi)
} else {
pi += 1
}
}
}
///|
/// Initiates a DH ratchet step (`NextKey` block type 7) for `remote_static_pub`,
/// returning `Some(NextKey(...))` if a session is established.
pub fn RatchetSessionManager::create_next_key_block(
self : RatchetSessionManager,
remote_static_pub : Bytes,
next_rand_32 : () -> Bytes,
) -> RatchetBlock? raise RatchetError {
let sidx = self.find_session(remote_static_pub)
if sidx < 0 {
return None
}
let sess = self.sessions[sidx]
let kp = generate_elligator_keypair(next_rand_32)
sess.dh_ratchet_key_id = sess.dh_ratchet_key_id + 1U
sess.local_next_priv = Some(kp.private_key)
sess.local_next_pub = Some(kp.public_key)
Some(
NextKey(
flags=b'\x05', // key present (0x01) + request reverse (0x04)
key_id=sess.dh_ratchet_key_id,
public_key=Some(kp.public_key),
),
)
}
///|
fn RatchetSessionManager::process_next_keys(
self : RatchetSessionManager,
sess : RatchetPeerSession,
blocks : Array[RatchetBlock],
) -> Unit raise RatchetError {
let _ = self
for blk in blocks {
match blk {
NextKey(flags~, key_id~, public_key~) => {
sess.dh_ratchet_key_id = key_id
match public_key {
Some(rpub) => {
sess.remote_next_pub = Some(rpub)
let is_reverse = (flags.to_int() & 0x02) != 0
if is_reverse {
match sess.local_next_priv {
Some(lpriv) => {
sess.apply_dh_ratchet(lpriv, rpub, for_send=true)
sess.apply_dh_ratchet(lpriv, rpub, for_send=false)
}
None => ()
}
}
}
None => ()
}
}
_ => ()
}
}
}
///|
/// Encrypts `blocks` for `remote_static_pub`:
/// - Uses `Existing Session` if established;
/// - Uses `New Session Reply` if responding to a peer's `New Session`;
/// - Otherwise sends a Bound `New Session` (prepending `DateTime(now_sec)`).
pub fn RatchetSessionManager::encrypt_to_peer(
self : RatchetSessionManager,
remote_static_pub : Bytes,
blocks : Array[RatchetBlock],
now_sec : UInt32,
next_rand_32 : () -> Bytes,
) -> Bytes raise RatchetError {
let sidx = self.find_session(remote_static_pub)
if sidx >= 0 {
let sess = self.sessions[sidx]
if sess.last_used_sec != 0U && now_sec > sess.last_used_sec + 300U {
let _ = self.sessions.remove(sidx)
} else {
sess.last_used_sec = now_sec
return sess.encrypt_existing(blocks)
}
}
// Check if we owe this peer an NSR
for i = 0; i < self.inbound_pending.length(); i = i + 1 {
let p = self.inbound_pending[i]
if @crypto.ct_eq(p.remote_static_pub, remote_static_pub) {
let _ = self.inbound_pending.remove(i)
let ephem_b = generate_elligator_keypair(next_rand_32)
let (wire, sess) = encrypt_new_session_reply(p, ephem_b, blocks)
sess.last_used_sec = now_sec
self.sessions.push(sess)
return wire
}
}
// Initiate Bound New Session (prepending DateTime block if not already present)
let ns_blocks : Array[RatchetBlock] = []
let mut has_dt = false
for b in blocks {
if b is DateTime(_) {
has_dt = true
}
}
if !has_dt {
ns_blocks.push(DateTime(now_sec))
}
for b in blocks {
ns_blocks.push(b)
}
let ephem = generate_elligator_keypair(next_rand_32)
let (wire, pending_opt) = encrypt_new_session(
Some(self.local_static),
remote_static_pub,
ephem,
ns_blocks,
)
match pending_opt {
Some(p) =>
// Pre-register first 4 NSR tags so any reply matches
for _k = 0; _k < 4; _k = _k + 1 {
let (_n, tag, _k32) = p.nsr_tagset.next_entry()
while self.outbound_pending.length() >= 64 {
let _ = self.outbound_pending.remove(0)
}
self.outbound_pending.push((tag, p))
}
None => ()
}
wire
}
///|
/// Decrypts an incoming Garlic ECIES payload (`ES` tag lookup -> `NSR` tag lookup -> `NS`).
/// Returns `(remote_static_pub_if_bound, decoded_blocks)`.
pub fn RatchetSessionManager::decrypt_incoming(
self : RatchetSessionManager,
garlic_data : Bytes,
) -> (Bytes?, Array[RatchetBlock]) raise RatchetError {
if garlic_data.length() >= 24 {
let tag_8 = r_slice(garlic_data, 0, 8)
let ct = r_slice(garlic_data, 8, garlic_data.length() - 8)
// 1. Existing Session lookup
for sess in self.sessions {
match sess.try_decrypt_es(tag_8, ct) {
Some(blocks) => {
self.process_next_keys(sess, blocks)
return (Some(sess.remote_static_pub), blocks)
}
None => ()
}
}
// 2. New Session Reply lookup
for i = 0; i < self.outbound_pending.length(); i = i + 1 {
let (expected_tag, p) = self.outbound_pending[i]
if @crypto.ct_eq(expected_tag, tag_8) {
let (blocks, sess) = decrypt_new_session_reply(
self.local_static,
p,
garlic_data,
)
// Remove all pending entries sharing this PendingNewSession
let mut j = 0
while j < self.outbound_pending.length() {
if @crypto.ct_eq(self.outbound_pending[j].1.h, p.h) {
let _ = self.outbound_pending.remove(j)
} else {
j += 1
}
}
let existing_idx = self.find_session(sess.remote_static_pub)
if existing_idx >= 0 {
self.sessions[existing_idx] = sess
} else {
self.sessions.push(sess)
}
return (Some(sess.remote_static_pub), blocks)
}
}
}
// 3. New Session
let (blocks, pending_opt) = decrypt_new_session(
self.local_static,
garlic_data,
)
match pending_opt {
Some(p) => {
// Replace any older inbound pending from same peer
let mut i = 0
while i < self.inbound_pending.length() {
if @crypto.ct_eq(
self.inbound_pending[i].remote_static_pub,
p.remote_static_pub,
) {
let _ = self.inbound_pending.remove(i)
} else {
i += 1
}
}
self.inbound_pending.push(p)
(Some(p.remote_static_pub), blocks)
}
None => (None, blocks)
}
}