feat: add ratchet, streaming, SU3 reseed, and router floodfill
- Add ratchet/ with ECIES-X25519-AEAD-Ratchet (Proposal 144), Garlic cloves, and ECIES DatabaseLookup replies - Add streaming/ with Ed25519-signed I2P Streaming (SYN/ACK/NACK/CLOSE/RESET, retransmit, window) and Repliable/Raw Datagrams - Add common/su3.mbt to parse and verify reseed .su3 bundles - Add Elligator2 encoding in crypto/ and OfflineSignature support in LeaseSet2 (flags bit 0) - Router: NTCP2 peer pool, floodfill NetDB crawl, transit tunnel relay, and Garlic/Streaming bridge - cmd/router: add --peer-dir, --su3, --reseed, --floodfill, --no-clock-skew - cmd/client: add --dest for persistent destination keys - Mark Phase 6 complete in README and document the transport scope (NTCP2 only, no SSU2)
This commit is contained in:
1 parent
8eafa11b22
commit
ae72b00323
54 files changed
+9607
-704
No files matched your search
@@ -0,0 +1,322 @@
|
||||
///|
|
||||
/// Proposal 144 ECIES-X25519-AEAD-Ratchet payload block codec & Garlic Clove delivery instructions.
|
||||
|
||||
///|
|
||||
#derive(Eq, Debug)
|
||||
pub suberror RatchetError {
|
||||
Crypto(@crypto.CryptoError)
|
||||
Noise(@noise.NoiseError)
|
||||
Encoding(@encoding.EncodingError)
|
||||
Common(@common.CommonError)
|
||||
I2np(@i2np.I2npError)
|
||||
InvalidLength(String)
|
||||
InvalidFormat(String)
|
||||
UnknownSession
|
||||
AuthenticationFailed
|
||||
}
|
||||
|
||||
///|
|
||||
/// Delivery target inside a Garlic Clove block (Block Type 11).
|
||||
#derive(Eq, Debug)
|
||||
pub(all) enum GarlicDelivery {
|
||||
Local
|
||||
Destination(@common.Hash)
|
||||
Router(@common.Hash)
|
||||
Tunnel(@common.Hash, UInt32)
|
||||
}
|
||||
|
||||
///|
|
||||
fn encode_garlic_delivery(
|
||||
delivery : GarlicDelivery,
|
||||
w : @encoding.Writer,
|
||||
) -> Unit {
|
||||
match delivery {
|
||||
Local => w.write_u8(b'\x00')
|
||||
Destination(h) => {
|
||||
w.write_u8(b'\x20') // delivery type 1 (bits 6..5 = 01)
|
||||
h.encode(w)
|
||||
}
|
||||
Router(h) => {
|
||||
w.write_u8(b'\x40') // delivery type 2 (bits 6..5 = 10)
|
||||
h.encode(w)
|
||||
}
|
||||
Tunnel(gw, tid) => {
|
||||
w.write_u8(b'\x60') // delivery type 3 (bits 6..5 = 11)
|
||||
gw.encode(w)
|
||||
w.write_u32_be(tid)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn decode_garlic_delivery(
|
||||
r : @encoding.Reader,
|
||||
) -> GarlicDelivery raise RatchetError {
|
||||
let flag = (r.read_u8() catch { e => raise Encoding(e) }).to_int()
|
||||
if (flag & 0x80) != 0 {
|
||||
// Individual clove encryption is unsupported/unused in ECIES
|
||||
let _ = r.read_bytes(32) catch { e => raise Encoding(e) }
|
||||
}
|
||||
let dtype = (flag >> 5) & 0x03
|
||||
let res : GarlicDelivery = match dtype {
|
||||
0 => Local
|
||||
1 => {
|
||||
let h = @common.Hash::decode(r) catch { e => raise Common(e) }
|
||||
Destination(h)
|
||||
}
|
||||
2 => {
|
||||
let h = @common.Hash::decode(r) catch { e => raise Common(e) }
|
||||
Router(h)
|
||||
}
|
||||
_ => {
|
||||
let gw = @common.Hash::decode(r) catch { e => raise Common(e) }
|
||||
let tid = r.read_u32_be() catch { e => raise Encoding(e) }
|
||||
Tunnel(gw, tid)
|
||||
}
|
||||
}
|
||||
if (flag & 0x10) != 0 {
|
||||
let _ = r.read_u32_be() catch { e => raise Encoding(e) }
|
||||
}
|
||||
res
|
||||
}
|
||||
|
||||
///|
|
||||
/// Proposal 144 ECIES-X25519-AEAD-Ratchet payload blocks.
|
||||
#derive(Eq, Debug)
|
||||
pub(all) enum RatchetBlock {
|
||||
/// Type 0: DateTime (4-byte uint32 Unix timestamp in seconds).
|
||||
DateTime(UInt32)
|
||||
/// Type 4: Termination (`reason`, `additional_data`).
|
||||
Termination(reason~ : Byte, additional_data~ : Bytes)
|
||||
/// Type 5: Options.
|
||||
Options(Bytes)
|
||||
/// Type 6: MessageNumber (`pn` uint16 BE previous chain length).
|
||||
MessageNumber(UInt32)
|
||||
/// Type 7: NextKey (`flags`, `key_id` uint16 BE, optional 32-byte X25519 public key).
|
||||
NextKey(flags~ : Byte, key_id~ : UInt32, public_key~ : Bytes?)
|
||||
/// Type 8: Ack (pairs of `(key_id, msg_num)` uint16 BE).
|
||||
Ack(Array[(UInt32, UInt32)])
|
||||
/// Type 9: AckRequest (`flags` 1 byte).
|
||||
AckRequest(Byte)
|
||||
/// Type 11: GarlicClove (`delivery`, 9-byte short I2NP header + payload bytes).
|
||||
GarlicClove(delivery~ : GarlicDelivery, i2np_short~ : Bytes)
|
||||
/// Type 254: Padding (must be last block if present).
|
||||
Padding(Bytes)
|
||||
/// Fallback for other block types.
|
||||
Unknown(Byte, Bytes)
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn RatchetBlock::encode(
|
||||
self : RatchetBlock,
|
||||
w : @encoding.Writer,
|
||||
) -> Unit raise RatchetError {
|
||||
match self {
|
||||
DateTime(ts) => {
|
||||
w.write_u8(b'\x00')
|
||||
w.write_u16_be(4U)
|
||||
w.write_u32_be(ts)
|
||||
}
|
||||
Termination(reason~, additional_data~) => {
|
||||
let sz = 1 + additional_data.length()
|
||||
if sz > 65535 {
|
||||
raise InvalidLength("Termination block exceeds 65535 bytes")
|
||||
}
|
||||
w.write_u8(b'\x04')
|
||||
w.write_u16_be(sz.reinterpret_as_uint())
|
||||
w.write_u8(reason)
|
||||
w.write_bytes(additional_data)
|
||||
}
|
||||
Options(data) => {
|
||||
if data.length() > 65535 {
|
||||
raise InvalidLength("Options block exceeds 65535 bytes")
|
||||
}
|
||||
w.write_u8(b'\x05')
|
||||
w.write_u16_be(data.length().reinterpret_as_uint())
|
||||
w.write_bytes(data)
|
||||
}
|
||||
MessageNumber(pn) => {
|
||||
w.write_u8(b'\x06')
|
||||
w.write_u16_be(2U)
|
||||
w.write_u16_be(pn)
|
||||
}
|
||||
NextKey(flags~, key_id~, public_key~) => {
|
||||
let bw = @encoding.Writer::new(capacity=35)
|
||||
bw.write_u8(flags)
|
||||
bw.write_u16_be(key_id)
|
||||
match public_key {
|
||||
Some(pk) => {
|
||||
if pk.length() != 32 {
|
||||
raise InvalidLength("NextKey public_key must be 32 bytes")
|
||||
}
|
||||
bw.write_bytes(pk)
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
let body = bw.to_bytes()
|
||||
w.write_u8(b'\x07')
|
||||
w.write_u16_be(body.length().reinterpret_as_uint())
|
||||
w.write_bytes(body)
|
||||
}
|
||||
Ack(pairs) => {
|
||||
let sz = pairs.length() * 4
|
||||
if sz > 65535 {
|
||||
raise InvalidLength("Ack block exceeds 65535 bytes")
|
||||
}
|
||||
w.write_u8(b'\x08')
|
||||
w.write_u16_be(sz.reinterpret_as_uint())
|
||||
for p in pairs {
|
||||
w.write_u16_be(p.0)
|
||||
w.write_u16_be(p.1)
|
||||
}
|
||||
}
|
||||
AckRequest(flags) => {
|
||||
w.write_u8(b'\x09')
|
||||
w.write_u16_be(1U)
|
||||
w.write_u8(flags)
|
||||
}
|
||||
GarlicClove(delivery~, i2np_short~) => {
|
||||
let bw = @encoding.Writer::new(capacity=40 + i2np_short.length())
|
||||
encode_garlic_delivery(delivery, bw)
|
||||
bw.write_bytes(i2np_short)
|
||||
let body = bw.to_bytes()
|
||||
if body.length() > 65535 {
|
||||
raise InvalidLength("GarlicClove block exceeds 65535 bytes")
|
||||
}
|
||||
w.write_u8(b'\x0b')
|
||||
w.write_u16_be(body.length().reinterpret_as_uint())
|
||||
w.write_bytes(body)
|
||||
}
|
||||
Padding(data) => {
|
||||
if data.length() > 65535 {
|
||||
raise InvalidLength("Padding block exceeds 65535 bytes")
|
||||
}
|
||||
w.write_u8(b'\xfe')
|
||||
w.write_u16_be(data.length().reinterpret_as_uint())
|
||||
w.write_bytes(data)
|
||||
}
|
||||
Unknown(t, data) => {
|
||||
if data.length() > 65535 {
|
||||
raise InvalidLength("Ratchet block exceeds 65535 bytes")
|
||||
}
|
||||
w.write_u8(t)
|
||||
w.write_u16_be(data.length().reinterpret_as_uint())
|
||||
w.write_bytes(data)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn encode_blocks(blocks : Array[RatchetBlock]) -> Bytes raise RatchetError {
|
||||
let w = @encoding.Writer::new(capacity=256)
|
||||
for blk in blocks {
|
||||
blk.encode(w)
|
||||
}
|
||||
w.to_bytes()
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn decode_blocks(data : Bytes) -> Array[RatchetBlock] raise RatchetError {
|
||||
let r = @encoding.Reader::new(data)
|
||||
let out : Array[RatchetBlock] = []
|
||||
while !r.is_eof() {
|
||||
let btype = r.read_u8() catch { e => raise Encoding(e) }
|
||||
let size = (r.read_u16_be() catch { e => raise Encoding(e) }).reinterpret_as_int()
|
||||
let body = r.read_bytes(size) catch { e => raise Encoding(e) }
|
||||
match btype.to_int() {
|
||||
0 => {
|
||||
if size != 4 {
|
||||
raise InvalidLength("DateTime block must be 4 bytes, got \{size}")
|
||||
}
|
||||
let br = @encoding.Reader::new(body)
|
||||
let ts = br.read_u32_be() catch { e => raise Encoding(e) }
|
||||
out.push(DateTime(ts))
|
||||
}
|
||||
4 => {
|
||||
if size < 1 {
|
||||
raise InvalidLength("Termination block must be at least 1 byte")
|
||||
}
|
||||
let br = @encoding.Reader::new(body)
|
||||
let reason = br.read_u8() catch { e => raise Encoding(e) }
|
||||
out.push(Termination(reason~, additional_data=br.read_remaining()))
|
||||
}
|
||||
5 => out.push(Options(body))
|
||||
6 => {
|
||||
if size != 2 {
|
||||
raise InvalidLength(
|
||||
"MessageNumber block must be 2 bytes, got \{size}",
|
||||
)
|
||||
}
|
||||
let br = @encoding.Reader::new(body)
|
||||
let pn = br.read_u16_be() catch { e => raise Encoding(e) }
|
||||
out.push(MessageNumber(pn))
|
||||
}
|
||||
7 => {
|
||||
if size < 3 {
|
||||
raise InvalidLength("NextKey block shorter than 3 bytes")
|
||||
}
|
||||
let br = @encoding.Reader::new(body)
|
||||
let flags = br.read_u8() catch { e => raise Encoding(e) }
|
||||
let key_id = br.read_u16_be() catch { e => raise Encoding(e) }
|
||||
let public_key = if (flags.to_int() & 0x01) != 0 {
|
||||
Some(br.read_bytes(32) catch { e => raise Encoding(e) })
|
||||
} else {
|
||||
None
|
||||
}
|
||||
out.push(NextKey(flags~, key_id~, public_key~))
|
||||
}
|
||||
8 => {
|
||||
if size % 4 != 0 {
|
||||
raise InvalidLength("Ack block size must be multiple of 4 bytes")
|
||||
}
|
||||
let br = @encoding.Reader::new(body)
|
||||
let pairs : Array[(UInt32, UInt32)] = []
|
||||
while !br.is_eof() {
|
||||
let kid = br.read_u16_be() catch { e => raise Encoding(e) }
|
||||
let n = br.read_u16_be() catch { e => raise Encoding(e) }
|
||||
pairs.push((kid, n))
|
||||
}
|
||||
out.push(Ack(pairs))
|
||||
}
|
||||
9 => {
|
||||
if size != 1 {
|
||||
raise InvalidLength("AckRequest block must be 1 byte")
|
||||
}
|
||||
out.push(AckRequest(body[0]))
|
||||
}
|
||||
11 => {
|
||||
let br = @encoding.Reader::new(body)
|
||||
let delivery = decode_garlic_delivery(br)
|
||||
let i2np_short = br.read_remaining()
|
||||
out.push(GarlicClove(delivery~, i2np_short~))
|
||||
}
|
||||
254 => out.push(Padding(body))
|
||||
_ => out.push(Unknown(btype, body))
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
///|
|
||||
/// Builds a `GarlicClove` block (type 11) wrapping a 9-byte short I2NP message.
|
||||
pub fn garlic_clove_block(
|
||||
delivery : GarlicDelivery,
|
||||
msg_id : UInt32,
|
||||
expiration_sec : UInt32,
|
||||
payload : @i2np.I2npPayload,
|
||||
) -> RatchetBlock raise RatchetError {
|
||||
let short_msg = @i2np.encode_short_message(msg_id, expiration_sec, payload) catch {
|
||||
e => raise I2np(e)
|
||||
}
|
||||
GarlicClove(delivery~, i2np_short=short_msg)
|
||||
}
|
||||
|
||||
///|
|
||||
/// Decodes the 9-byte short I2NP message inside a `GarlicClove` block.
|
||||
pub fn decode_garlic_clove_i2np(
|
||||
i2np_short : Bytes,
|
||||
) -> (@i2np.ShortHeader, @i2np.I2npPayload) raise RatchetError {
|
||||
@i2np.decode_short_message(@encoding.Reader::new(i2np_short)) catch {
|
||||
e => raise I2np(e)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,783 @@
|
||||
///|
|
||||
/// 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"
|
||||
|
||||
///|
|
||||
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?
|
||||
}
|
||||
|
||||
///|
|
||||
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,
|
||||
}
|
||||
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,
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
///|
|
||||
/// 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
|
||||
}
|
||||
|
||||
///|
|
||||
/// 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 {
|
||||
return self.sessions[sidx].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)
|
||||
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()
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import {
|
||||
"experiments/moon_i2p/encoding",
|
||||
"experiments/moon_i2p/crypto",
|
||||
"experiments/moon_i2p/common",
|
||||
"experiments/moon_i2p/i2np",
|
||||
"experiments/moon_i2p/noise",
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
// Generated using `moon info`, DON'T EDIT IT
|
||||
package "experiments/moon_i2p/ratchet"
|
||||
|
||||
import {
|
||||
"experiments/moon_i2p/common",
|
||||
"experiments/moon_i2p/crypto",
|
||||
"experiments/moon_i2p/encoding",
|
||||
"experiments/moon_i2p/i2np",
|
||||
"experiments/moon_i2p/noise",
|
||||
"moonbitlang/core/debug",
|
||||
}
|
||||
|
||||
// Values
|
||||
pub fn decode_blocks(Bytes) -> Array[RatchetBlock] raise RatchetError
|
||||
|
||||
pub fn decode_garlic_clove_i2np(Bytes) -> (@i2np.ShortHeader, @i2np.I2npPayload) raise RatchetError
|
||||
|
||||
pub fn decrypt_ecies_lookup_reply(Bytes, Bytes, Bytes) -> Array[RatchetBlock] raise RatchetError
|
||||
|
||||
pub fn decrypt_new_session(@noise.KeyPair, Bytes) -> (Array[RatchetBlock], PendingNewSession?) raise RatchetError
|
||||
|
||||
pub fn decrypt_new_session_reply(@noise.KeyPair, PendingNewSession, Bytes) -> (Array[RatchetBlock], RatchetPeerSession) raise RatchetError
|
||||
|
||||
pub fn dh_initialize(Bytes, Bytes) -> (Bytes, TagSet) raise RatchetError
|
||||
|
||||
pub let ecies_protocol_name : Bytes
|
||||
|
||||
pub fn encode_blocks(Array[RatchetBlock]) -> Bytes raise RatchetError
|
||||
|
||||
pub fn encrypt_ecies_lookup_reply(Bytes, Bytes, Array[RatchetBlock]) -> Bytes raise RatchetError
|
||||
|
||||
pub fn encrypt_new_session(@noise.KeyPair?, Bytes, ElligatorKeyPair, Array[RatchetBlock]) -> (Bytes, PendingNewSession?) raise RatchetError
|
||||
|
||||
pub fn encrypt_new_session_reply(PendingNewSession, ElligatorKeyPair, Array[RatchetBlock]) -> (Bytes, RatchetPeerSession) raise RatchetError
|
||||
|
||||
pub fn garlic_clove_block(GarlicDelivery, UInt32, UInt32, @i2np.I2npPayload) -> RatchetBlock raise RatchetError
|
||||
|
||||
pub fn generate_elligator_keypair(() -> Bytes) -> ElligatorKeyPair raise RatchetError
|
||||
|
||||
// Errors
|
||||
#derive(Eq, @debug.Debug)
|
||||
pub suberror RatchetError {
|
||||
Crypto(@crypto.CryptoError)
|
||||
Noise(@noise.NoiseError)
|
||||
Encoding(@encoding.EncodingError)
|
||||
Common(@common.CommonError)
|
||||
I2np(@i2np.I2npError)
|
||||
InvalidLength(String)
|
||||
InvalidFormat(String)
|
||||
UnknownSession
|
||||
AuthenticationFailed
|
||||
}
|
||||
|
||||
// Types and methods
|
||||
#derive(Eq, @debug.Debug)
|
||||
pub(all) struct ElligatorKeyPair {
|
||||
private_key : Bytes
|
||||
public_key : Bytes
|
||||
elligator_repr : Bytes
|
||||
}
|
||||
|
||||
#derive(Eq, @debug.Debug)
|
||||
pub(all) enum GarlicDelivery {
|
||||
Local
|
||||
Destination(@common.Hash)
|
||||
Router(@common.Hash)
|
||||
Tunnel(@common.Hash, UInt32)
|
||||
}
|
||||
|
||||
pub struct PendingNewSession {
|
||||
ck : Bytes
|
||||
h : Bytes
|
||||
local_ephem_priv : Bytes
|
||||
remote_ephem_pub : Bytes
|
||||
remote_static_pub : Bytes
|
||||
nsr_tagset : TagSet
|
||||
}
|
||||
|
||||
#derive(Eq, @debug.Debug)
|
||||
pub(all) enum RatchetBlock {
|
||||
DateTime(UInt32)
|
||||
Termination(reason~ : Byte, additional_data~ : Bytes)
|
||||
Options(Bytes)
|
||||
MessageNumber(UInt32)
|
||||
NextKey(flags~ : Byte, key_id~ : UInt32, public_key~ : Bytes?)
|
||||
Ack(Array[(UInt32, UInt32)])
|
||||
AckRequest(Byte)
|
||||
GarlicClove(delivery~ : GarlicDelivery, i2np_short~ : Bytes)
|
||||
Padding(Bytes)
|
||||
Unknown(Byte, Bytes)
|
||||
}
|
||||
pub fn RatchetBlock::encode(Self, @encoding.Writer) -> Unit raise RatchetError
|
||||
|
||||
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)]
|
||||
mut dh_ratchet_key_id : UInt32
|
||||
mut local_next_priv : Bytes?
|
||||
mut local_next_pub : Bytes?
|
||||
mut remote_next_pub : Bytes?
|
||||
}
|
||||
pub fn RatchetPeerSession::apply_dh_ratchet(Self, Bytes, Bytes, for_send~ : Bool) -> Unit raise RatchetError
|
||||
pub fn RatchetPeerSession::encrypt_existing(Self, Array[RatchetBlock]) -> Bytes raise RatchetError
|
||||
|
||||
pub struct RatchetSessionManager {
|
||||
local_static : @noise.KeyPair
|
||||
sessions : Array[RatchetPeerSession]
|
||||
outbound_pending : Array[(Bytes, PendingNewSession)]
|
||||
inbound_pending : Array[PendingNewSession]
|
||||
}
|
||||
pub fn RatchetSessionManager::create_next_key_block(Self, Bytes, () -> Bytes) -> RatchetBlock? raise RatchetError
|
||||
pub fn RatchetSessionManager::decrypt_incoming(Self, Bytes) -> (Bytes?, Array[RatchetBlock]) raise RatchetError
|
||||
pub fn RatchetSessionManager::encrypt_to_peer(Self, Bytes, Array[RatchetBlock], UInt32, () -> Bytes) -> Bytes raise RatchetError
|
||||
pub fn RatchetSessionManager::new(@noise.KeyPair) -> Self
|
||||
|
||||
pub struct TagSet {
|
||||
mut tag_ck : Bytes
|
||||
sesstag_const : Bytes
|
||||
mut symm_ck : Bytes
|
||||
mut msg_num : UInt32
|
||||
}
|
||||
pub fn TagSet::next_entry(Self) -> (UInt32, Bytes, Bytes) raise RatchetError
|
||||
|
||||
// Type aliases
|
||||
|
||||
// Traits
|
||||
@@ -0,0 +1,165 @@
|
||||
///|
|
||||
fn det_rand_gen(seed_init : Byte) -> () -> Bytes {
|
||||
let ctr : Ref[Int32] = { val: seed_init.to_int(), }
|
||||
fn() {
|
||||
let idx = ctr.val
|
||||
ctr.val = idx + 1
|
||||
let w = @encoding.Writer::new(capacity=8)
|
||||
w.write_u32_be(idx.reinterpret_as_uint())
|
||||
@crypto.sha256(w.to_bytes())
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
test "Proposal 144 GarlicClove and RatchetBlock encode/decode round-trip" {
|
||||
let clove = @ratchet.garlic_clove_block(
|
||||
Destination(@common.Hash::sha256(b"dest-a")),
|
||||
42U,
|
||||
1700000600U,
|
||||
Data(data=b"hello-clove"),
|
||||
)
|
||||
let blocks : Array[@ratchet.RatchetBlock] = [
|
||||
DateTime(1700000123U),
|
||||
Options(b"\x01\x02"),
|
||||
MessageNumber(5U),
|
||||
NextKey(flags=b'\x05', key_id=1U, public_key=Some(Bytes::make(32, b'\xaa'))),
|
||||
Ack([(1U, 3U), (1U, 4U)]),
|
||||
AckRequest(b'\x00'),
|
||||
clove,
|
||||
Padding(b"\x00\x00\x00"),
|
||||
]
|
||||
let wire = @ratchet.encode_blocks(blocks)
|
||||
let decoded = @ratchet.decode_blocks(wire)
|
||||
assert_eq(decoded, blocks)
|
||||
match decoded[6] {
|
||||
GarlicClove(delivery~, i2np_short~) => {
|
||||
assert_eq(delivery, Destination(@common.Hash::sha256(b"dest-a")))
|
||||
let (hdr, payload) = @ratchet.decode_garlic_clove_i2np(i2np_short)
|
||||
assert_eq(hdr.msg_id, 42U)
|
||||
assert_eq(payload, Data(data=b"hello-clove"))
|
||||
}
|
||||
_ => fail("expected GarlicClove")
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
test "Proposal 144 ECIES-X25519-AEAD-Ratchet NS -> NSR -> bidirectional ES + DH ratchet + Unbound + DSM" {
|
||||
let alice_s = @noise.KeyPair::from_private(
|
||||
@crypto.sha256(b"alice-ecies-static"),
|
||||
)
|
||||
let bob_s = @noise.KeyPair::from_private(@crypto.sha256(b"bob-ecies-static"))
|
||||
let alice_mgr = @ratchet.RatchetSessionManager::new(alice_s)
|
||||
let bob_mgr = @ratchet.RatchetSessionManager::new(bob_s)
|
||||
let rand_a = det_rand_gen(b'\x10')
|
||||
let rand_b = det_rand_gen(b'\x50')
|
||||
|
||||
// 1. Alice -> Bob: Bound New Session
|
||||
let c1 = @ratchet.garlic_clove_block(
|
||||
Local,
|
||||
1U,
|
||||
1700000600U,
|
||||
Data(data=b"msg-1-ns"),
|
||||
)
|
||||
let ns_wire = alice_mgr.encrypt_to_peer(
|
||||
bob_s.public_key,
|
||||
[c1],
|
||||
1700000100U,
|
||||
rand_a,
|
||||
)
|
||||
let (bob_from, bob_dec1) = bob_mgr.decrypt_incoming(ns_wire)
|
||||
assert_eq(bob_from, Some(alice_s.public_key))
|
||||
assert_eq(bob_dec1.length(), 2) // DateTime + GarlicClove
|
||||
|
||||
// 2. Bob -> Alice: New Session Reply (NSR)
|
||||
let c2 = @ratchet.garlic_clove_block(
|
||||
Local,
|
||||
2U,
|
||||
1700000600U,
|
||||
Data(data=b"msg-2-nsr"),
|
||||
)
|
||||
let nsr_wire = bob_mgr.encrypt_to_peer(
|
||||
alice_s.public_key,
|
||||
[c2],
|
||||
1700000101U,
|
||||
rand_b,
|
||||
)
|
||||
let (alice_from, alice_dec2) = alice_mgr.decrypt_incoming(nsr_wire)
|
||||
assert_eq(alice_from, Some(bob_s.public_key))
|
||||
assert_eq(alice_dec2, [c2])
|
||||
|
||||
// 3. Alice <-> Bob: Existing Session (ES) bidirectional messages
|
||||
for i = 0; i < 4; i = i + 1 {
|
||||
let ca = @ratchet.garlic_clove_block(
|
||||
Local,
|
||||
(10 + i).reinterpret_as_uint(),
|
||||
1700000600U,
|
||||
Data(data=b"alice-es"),
|
||||
)
|
||||
let w_ab = alice_mgr.encrypt_to_peer(
|
||||
bob_s.public_key,
|
||||
[ca],
|
||||
1700000102U,
|
||||
rand_a,
|
||||
)
|
||||
let (f1, d1) = bob_mgr.decrypt_incoming(w_ab)
|
||||
assert_eq(f1, Some(alice_s.public_key))
|
||||
assert_eq(d1, [ca])
|
||||
|
||||
let cb = @ratchet.garlic_clove_block(
|
||||
Local,
|
||||
(20 + i).reinterpret_as_uint(),
|
||||
1700000600U,
|
||||
Data(data=b"bob-es"),
|
||||
)
|
||||
let w_ba = bob_mgr.encrypt_to_peer(
|
||||
alice_s.public_key,
|
||||
[cb],
|
||||
1700000103U,
|
||||
rand_b,
|
||||
)
|
||||
let (f2, d2) = alice_mgr.decrypt_incoming(w_ba)
|
||||
assert_eq(f2, Some(bob_s.public_key))
|
||||
assert_eq(d2, [cb])
|
||||
}
|
||||
|
||||
// 3b. DH Ratchet rotation with NextKey block
|
||||
match alice_mgr.create_next_key_block(bob_s.public_key, rand_a) {
|
||||
Some(nk_blk) => {
|
||||
let w_nk = alice_mgr.encrypt_to_peer(
|
||||
bob_s.public_key,
|
||||
[nk_blk],
|
||||
1700000105U,
|
||||
rand_a,
|
||||
)
|
||||
let (_, d_nk) = bob_mgr.decrypt_incoming(w_nk)
|
||||
assert_eq(d_nk, [nk_blk])
|
||||
}
|
||||
None => fail("expected NextKey block on established session")
|
||||
}
|
||||
|
||||
// 4. Unbound New Session
|
||||
let ephem_u = @ratchet.generate_elligator_keypair(rand_a)
|
||||
let (ub_wire, ub_pending) = @ratchet.encrypt_new_session(
|
||||
None,
|
||||
bob_s.public_key,
|
||||
ephem_u,
|
||||
[DateTime(1700000110U), GarlicClove(delivery=Local, i2np_short=b"unbound")],
|
||||
)
|
||||
assert_true(ub_pending is None)
|
||||
let (ub_dec, ub_rx_pending) = @ratchet.decrypt_new_session(bob_s, ub_wire)
|
||||
assert_true(ub_rx_pending is None)
|
||||
assert_eq(ub_dec.length(), 2)
|
||||
|
||||
// 5. Proposal 154 ECIES DatabaseLookup reply round-trip
|
||||
let rkey = Bytes::make(32, b'\x91')
|
||||
let rtag = Bytes::make(8, b'\x92')
|
||||
let dsm_blk = @ratchet.garlic_clove_block(
|
||||
Local,
|
||||
99U,
|
||||
1700000600U,
|
||||
Data(data=b"dsm-ls2"),
|
||||
)
|
||||
let enc_dsm = @ratchet.encrypt_ecies_lookup_reply(rkey, rtag, [dsm_blk])
|
||||
let dec_dsm = @ratchet.decrypt_ecies_lookup_reply(rkey, rtag, enc_dsm)
|
||||
assert_eq(dec_dsm, [dsm_blk])
|
||||
}
|
||||
Reference in new issue
Block a user