535 lines
14 KiB
MoonBit
535 lines
14 KiB
MoonBit
///|
|
|
/// Errors raised by the Noise_XK_25519_ChaChaPoly_SHA256 / NTCP2 protocol engine.
|
|
#derive(Eq, Debug)
|
|
pub suberror NoiseError {
|
|
Crypto(@crypto.CryptoError)
|
|
InvalidState(String)
|
|
InvalidLength(String)
|
|
NonceOverflow
|
|
}
|
|
|
|
///|
|
|
/// Noise Protocol Name used by I2P NTCP2 (`Noise_XKaesobfse+hs2+hs3_25519_ChaChaPoly_SHA256`
|
|
/// or standard `Noise_XK_25519_ChaChaPoly_SHA256`).
|
|
pub let noise_xk_protocol_name : Bytes = b"Noise_XK_25519_ChaChaPoly_SHA256"
|
|
|
|
///|
|
|
pub let ntcp2_protocol_name : Bytes = b"Noise_XKaesobfse+hs2+hs3_25519_ChaChaPoly_SHA256"
|
|
|
|
///|
|
|
fn make_noise_nonce(n : UInt64) -> Bytes {
|
|
// Noise ChaChaPoly nonce: 4 zero bytes followed by 64-bit little-endian counter
|
|
let buf = FixedArray::make(12, b'\x00')
|
|
for i = 0; i < 8; i = i + 1 {
|
|
buf[4 + i] = ((n >> (i * 8)) & 0xFFUL).to_byte()
|
|
}
|
|
Bytes::from_array(buf)
|
|
}
|
|
|
|
///|
|
|
fn slice_bytes(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_bytes(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)
|
|
}
|
|
|
|
///|
|
|
/// Noise HKDF(chaining_key, input_key_material) -> (output1, output2) (each 32 bytes).
|
|
fn noise_hkdf2(ck : Bytes, ikm : Bytes) -> (Bytes, Bytes) {
|
|
let temp_key = @crypto.hmac_sha256(ck, ikm)
|
|
let out1 = @crypto.hmac_sha256(temp_key, b"\x01")
|
|
let out2 = @crypto.hmac_sha256(temp_key, concat_bytes(out1, b"\x02"))
|
|
(out1, out2)
|
|
}
|
|
|
|
///|
|
|
/// Noise CipherState (ChaCha20-Poly1305 with 64-bit counter nonce).
|
|
pub struct CipherState {
|
|
mut key : Bytes?
|
|
mut nonce : UInt64
|
|
}
|
|
|
|
///|
|
|
pub fn CipherState::empty() -> CipherState {
|
|
{ key: None, nonce: 0UL, }
|
|
}
|
|
|
|
///|
|
|
pub fn CipherState::initialize_key(self : CipherState, key : Bytes) -> Unit {
|
|
self.key = Some(key)
|
|
self.nonce = 0UL
|
|
}
|
|
|
|
///|
|
|
pub fn CipherState::has_key(self : CipherState) -> Bool {
|
|
self.key is Some(_)
|
|
}
|
|
|
|
///|
|
|
pub fn CipherState::encrypt_with_ad(
|
|
self : CipherState,
|
|
ad : Bytes,
|
|
plaintext : Bytes,
|
|
) -> Bytes raise NoiseError {
|
|
match self.key {
|
|
None => plaintext
|
|
Some(k) => {
|
|
if self.nonce == 0xFFFFFFFFFFFFFFFFUL {
|
|
raise NonceOverflow
|
|
}
|
|
let nonce = make_noise_nonce(self.nonce)
|
|
self.nonce = self.nonce + 1UL
|
|
@crypto.aead_chacha20_poly1305_encrypt(k, nonce, ad, plaintext) catch {
|
|
e => raise Crypto(e)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
///|
|
|
pub fn CipherState::decrypt_with_ad(
|
|
self : CipherState,
|
|
ad : Bytes,
|
|
ciphertext : Bytes,
|
|
) -> Bytes raise NoiseError {
|
|
match self.key {
|
|
None => ciphertext
|
|
Some(k) => {
|
|
if self.nonce == 0xFFFFFFFFFFFFFFFFUL {
|
|
raise NonceOverflow
|
|
}
|
|
let nonce = make_noise_nonce(self.nonce)
|
|
let pt = @crypto.aead_chacha20_poly1305_decrypt(k, nonce, ad, ciphertext) catch {
|
|
e => raise Crypto(e)
|
|
}
|
|
self.nonce = self.nonce + 1UL
|
|
pt
|
|
}
|
|
}
|
|
}
|
|
|
|
///|
|
|
/// Noise SymmetricState (chaining key `ck`, handshake hash `h`, and `CipherState`).
|
|
pub struct SymmetricState {
|
|
mut ck : Bytes
|
|
mut h : Bytes
|
|
cipher : CipherState
|
|
}
|
|
|
|
///|
|
|
pub fn SymmetricState::initialize(protocol_name : Bytes) -> SymmetricState {
|
|
let h = if protocol_name.length() <= 32 {
|
|
let padded = FixedArray::make(32, b'\x00')
|
|
for i = 0; i < protocol_name.length(); i = i + 1 {
|
|
padded[i] = protocol_name[i]
|
|
}
|
|
Bytes::from_array(padded)
|
|
} else {
|
|
@crypto.sha256(protocol_name)
|
|
}
|
|
{ ck: h, h, cipher: CipherState::empty(), }
|
|
}
|
|
|
|
///|
|
|
pub fn SymmetricState::mix_key(self : SymmetricState, ikm : Bytes) -> Unit {
|
|
let (ck, temp_k) = noise_hkdf2(self.ck, ikm)
|
|
self.ck = ck
|
|
self.cipher.initialize_key(temp_k)
|
|
}
|
|
|
|
///|
|
|
pub fn SymmetricState::mix_hash(self : SymmetricState, data : Bytes) -> Unit {
|
|
self.h = @crypto.sha256(concat_bytes(self.h, data))
|
|
}
|
|
|
|
///|
|
|
pub fn SymmetricState::encrypt_and_hash(
|
|
self : SymmetricState,
|
|
plaintext : Bytes,
|
|
) -> Bytes raise NoiseError {
|
|
let ct = self.cipher.encrypt_with_ad(self.h, plaintext)
|
|
self.mix_hash(ct)
|
|
ct
|
|
}
|
|
|
|
///|
|
|
pub fn SymmetricState::decrypt_and_hash(
|
|
self : SymmetricState,
|
|
ciphertext : Bytes,
|
|
) -> Bytes raise NoiseError {
|
|
let pt = self.cipher.decrypt_with_ad(self.h, ciphertext)
|
|
self.mix_hash(ciphertext)
|
|
pt
|
|
}
|
|
|
|
///|
|
|
pub fn SymmetricState::handshake_hash(self : SymmetricState) -> Bytes {
|
|
self.h
|
|
}
|
|
|
|
///|
|
|
pub fn SymmetricState::chaining_key(self : SymmetricState) -> Bytes {
|
|
self.ck
|
|
}
|
|
|
|
///|
|
|
pub fn SymmetricState::split(
|
|
self : SymmetricState,
|
|
) -> (CipherState, CipherState) {
|
|
let (k1, k2) = noise_hkdf2(self.ck, b"")
|
|
let c1 = CipherState::empty()
|
|
let c2 = CipherState::empty()
|
|
c1.initialize_key(k1)
|
|
c2.initialize_key(k2)
|
|
(c1, c2)
|
|
}
|
|
|
|
///|
|
|
/// X25519 static/ephemeral keypair for Noise_XK.
|
|
#derive(Eq, Debug)
|
|
pub(all) struct KeyPair {
|
|
private_key : Bytes
|
|
public_key : Bytes
|
|
}
|
|
|
|
///|
|
|
pub fn KeyPair::from_private(private_key : Bytes) -> KeyPair raise NoiseError {
|
|
let public_key = @crypto.x25519_public_key(private_key) catch {
|
|
e => raise Crypto(e)
|
|
}
|
|
{ private_key, public_key, }
|
|
}
|
|
|
|
///|
|
|
/// Post-handshake bidirectional encrypted transport session.
|
|
pub struct TransportSession {
|
|
send_cipher : CipherState
|
|
recv_cipher : CipherState
|
|
handshake_hash : Bytes
|
|
remote_static : Bytes
|
|
}
|
|
|
|
///|
|
|
pub fn TransportSession::encrypt(
|
|
self : TransportSession,
|
|
plaintext : Bytes,
|
|
) -> Bytes raise NoiseError {
|
|
self.send_cipher.encrypt_with_ad(b"", plaintext)
|
|
}
|
|
|
|
///|
|
|
pub fn TransportSession::decrypt(
|
|
self : TransportSession,
|
|
ciphertext : Bytes,
|
|
) -> Bytes raise NoiseError {
|
|
self.recv_cipher.decrypt_with_ad(b"", ciphertext)
|
|
}
|
|
|
|
///|
|
|
pub fn TransportSession::handshake_hash(self : TransportSession) -> Bytes {
|
|
self.handshake_hash
|
|
}
|
|
|
|
///|
|
|
pub fn TransportSession::remote_static(self : TransportSession) -> Bytes {
|
|
self.remote_static
|
|
}
|
|
|
|
///|
|
|
/// `Noise_XK_25519_ChaChaPoly_SHA256` HandshakeState:
|
|
/// ```
|
|
/// <- s (pre-message: responder's static key known to initiator)
|
|
/// ...
|
|
/// -> e, es (Message 1: SessionRequest)
|
|
/// <- e, ee (Message 2: SessionCreated)
|
|
/// -> s, se (Message 3: SessionConfirmed)
|
|
/// ```
|
|
pub struct HandshakeState {
|
|
symmetric : SymmetricState
|
|
initiator : Bool
|
|
s : KeyPair
|
|
mut e : KeyPair?
|
|
mut rs : Bytes?
|
|
mut re : Bytes?
|
|
mut step : Int32 // 0 -> msg1, 1 -> msg2, 2 -> msg3, 3 -> done
|
|
}
|
|
|
|
///|
|
|
/// Initializes a `Noise_XK` initiator handshake state (knows responder's static key `rs`).
|
|
pub fn HandshakeState::new_initiator(
|
|
local_static : KeyPair,
|
|
remote_static : Bytes,
|
|
protocol_name~ : Bytes = noise_xk_protocol_name,
|
|
prologue~ : Bytes = b"",
|
|
) -> HandshakeState raise NoiseError {
|
|
if remote_static.length() != 32 {
|
|
raise InvalidLength("remote_static must be 32 bytes")
|
|
}
|
|
let sym = SymmetricState::initialize(protocol_name)
|
|
sym.mix_hash(prologue)
|
|
// Pre-message: <- s
|
|
sym.mix_hash(remote_static)
|
|
{
|
|
symmetric: sym,
|
|
initiator: true,
|
|
s: local_static,
|
|
e: None,
|
|
rs: Some(remote_static),
|
|
re: None,
|
|
step: 0,
|
|
}
|
|
}
|
|
|
|
///|
|
|
/// Initializes a `Noise_XK` responder handshake state.
|
|
pub fn HandshakeState::new_responder(
|
|
local_static : KeyPair,
|
|
protocol_name~ : Bytes = noise_xk_protocol_name,
|
|
prologue~ : Bytes = b"",
|
|
) -> HandshakeState {
|
|
let sym = SymmetricState::initialize(protocol_name)
|
|
sym.mix_hash(prologue)
|
|
// Pre-message: <- s
|
|
sym.mix_hash(local_static.public_key)
|
|
{
|
|
symmetric: sym,
|
|
initiator: false,
|
|
s: local_static,
|
|
e: None,
|
|
rs: None,
|
|
re: None,
|
|
step: 0,
|
|
}
|
|
}
|
|
|
|
///|
|
|
/// Sets the local ephemeral keypair before sending Message 1 (initiator) or Message 2 (responder).
|
|
pub fn HandshakeState::set_ephemeral(
|
|
self : HandshakeState,
|
|
ephemeral : KeyPair,
|
|
) -> Unit {
|
|
self.e = Some(ephemeral)
|
|
}
|
|
|
|
///|
|
|
/// Writes the next handshake message (`-> e, es`, `<- e, ee`, or `-> s, se`).
|
|
pub fn HandshakeState::write_message(
|
|
self : HandshakeState,
|
|
payload : Bytes,
|
|
) -> Bytes raise NoiseError {
|
|
if self.step == 0 && self.initiator {
|
|
// Message 1: -> e, es
|
|
let ephem = match self.e {
|
|
Some(kp) => kp
|
|
None =>
|
|
raise InvalidState("initiator ephemeral key must be set for msg 1")
|
|
}
|
|
let rs = match self.rs {
|
|
Some(k) => k
|
|
None => raise InvalidState("remote static key missing")
|
|
}
|
|
self.symmetric.mix_hash(ephem.public_key)
|
|
let dh_es = @crypto.x25519(ephem.private_key, rs) catch {
|
|
e => raise Crypto(e)
|
|
}
|
|
self.symmetric.mix_key(dh_es)
|
|
let enc_payload = self.symmetric.encrypt_and_hash(payload)
|
|
self.step = 1
|
|
concat_bytes(ephem.public_key, enc_payload)
|
|
} else if self.step == 1 && !self.initiator {
|
|
// Message 2: <- e, ee
|
|
let ephem = match self.e {
|
|
Some(kp) => kp
|
|
None =>
|
|
raise InvalidState("responder ephemeral key must be set for msg 2")
|
|
}
|
|
let re = match self.re {
|
|
Some(k) => k
|
|
None => raise InvalidState("remote ephemeral key missing")
|
|
}
|
|
self.symmetric.mix_hash(ephem.public_key)
|
|
let dh_ee = @crypto.x25519(ephem.private_key, re) catch {
|
|
e => raise Crypto(e)
|
|
}
|
|
self.symmetric.mix_key(dh_ee)
|
|
let enc_payload = self.symmetric.encrypt_and_hash(payload)
|
|
self.step = 2
|
|
concat_bytes(ephem.public_key, enc_payload)
|
|
} else if self.step == 2 && self.initiator {
|
|
// Message 3: -> s, se
|
|
let re = match self.re {
|
|
Some(k) => k
|
|
None => raise InvalidState("remote ephemeral key missing")
|
|
}
|
|
let enc_s = self.symmetric.encrypt_and_hash(self.s.public_key)
|
|
let dh_se = @crypto.x25519(self.s.private_key, re) catch {
|
|
e => raise Crypto(e)
|
|
}
|
|
self.symmetric.mix_key(dh_se)
|
|
let enc_payload = self.symmetric.encrypt_and_hash(payload)
|
|
self.step = 3
|
|
concat_bytes(enc_s, enc_payload)
|
|
} else {
|
|
raise InvalidState(
|
|
"write_message invalid for step=\{self.step}, initiator=\{self.initiator}",
|
|
)
|
|
}
|
|
}
|
|
|
|
///|
|
|
/// Reads and authenticates the next handshake message, returning its decrypted payload.
|
|
pub fn HandshakeState::read_message(
|
|
self : HandshakeState,
|
|
message : Bytes,
|
|
) -> Bytes raise NoiseError {
|
|
if self.step == 0 && !self.initiator {
|
|
// Message 1: -> e, es
|
|
if message.length() < 32 {
|
|
raise InvalidLength("msg 1 shorter than 32 bytes")
|
|
}
|
|
let re = slice_bytes(message, 0, 32)
|
|
self.re = Some(re)
|
|
self.symmetric.mix_hash(re)
|
|
let dh_es = @crypto.x25519(self.s.private_key, re) catch {
|
|
e => raise Crypto(e)
|
|
}
|
|
self.symmetric.mix_key(dh_es)
|
|
let pt = self.symmetric.decrypt_and_hash(
|
|
slice_bytes(message, 32, message.length() - 32),
|
|
)
|
|
self.step = 1
|
|
pt
|
|
} else if self.step == 1 && self.initiator {
|
|
// Message 2: <- e, ee
|
|
if message.length() < 32 {
|
|
raise InvalidLength("msg 2 shorter than 32 bytes")
|
|
}
|
|
let re = slice_bytes(message, 0, 32)
|
|
self.re = Some(re)
|
|
self.symmetric.mix_hash(re)
|
|
let ephem = match self.e {
|
|
Some(kp) => kp
|
|
None => raise InvalidState("initiator ephemeral key missing")
|
|
}
|
|
let dh_ee = @crypto.x25519(ephem.private_key, re) catch {
|
|
e => raise Crypto(e)
|
|
}
|
|
self.symmetric.mix_key(dh_ee)
|
|
let pt = self.symmetric.decrypt_and_hash(
|
|
slice_bytes(message, 32, message.length() - 32),
|
|
)
|
|
self.step = 2
|
|
pt
|
|
} else if self.step == 2 && !self.initiator {
|
|
// Message 3: -> s, se (encrypted static key is 32 + 16 = 48 bytes)
|
|
if message.length() < 48 {
|
|
raise InvalidLength("msg 3 shorter than 48 bytes")
|
|
}
|
|
let rs = self.symmetric.decrypt_and_hash(slice_bytes(message, 0, 48))
|
|
self.rs = Some(rs)
|
|
let ephem = match self.e {
|
|
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.symmetric.mix_key(dh_se)
|
|
let pt = self.symmetric.decrypt_and_hash(
|
|
slice_bytes(message, 48, message.length() - 48),
|
|
)
|
|
self.step = 3
|
|
pt
|
|
} else {
|
|
raise InvalidState(
|
|
"read_message invalid for step=\{self.step}, initiator=\{self.initiator}",
|
|
)
|
|
}
|
|
}
|
|
|
|
///|
|
|
/// Completes the handshake and splits into a bidirectional `TransportSession`.
|
|
pub fn HandshakeState::into_transport(
|
|
self : HandshakeState,
|
|
) -> TransportSession raise NoiseError {
|
|
if self.step != 3 {
|
|
raise InvalidState("handshake not complete (step=\{self.step})")
|
|
}
|
|
let rs = match self.rs {
|
|
Some(k) => k
|
|
None => raise InvalidState("remote static key missing")
|
|
}
|
|
let (c1, c2) = self.symmetric.split()
|
|
let (send_cipher, recv_cipher) = if self.initiator {
|
|
(c1, c2)
|
|
} else {
|
|
(c2, c1)
|
|
}
|
|
{
|
|
send_cipher,
|
|
recv_cipher,
|
|
handshake_hash: self.symmetric.handshake_hash(),
|
|
remote_static: rs,
|
|
}
|
|
}
|
|
|
|
///|
|
|
/// NTCP2 Data Phase frame length obfuscation using SipHash-2-4 (per NTCP2 specification).
|
|
/// Maintains a chaining 8-byte IV updated as `IV_n = SipHash-2-4(k, IV_{n-1})`.
|
|
pub struct SipHashLengthMask {
|
|
key : Bytes // 16-byte SipHash key
|
|
mut iv : Bytes // 8-byte running IV
|
|
}
|
|
|
|
///|
|
|
pub fn SipHashLengthMask::new(
|
|
key : Bytes,
|
|
initial_iv : Bytes,
|
|
) -> SipHashLengthMask raise NoiseError {
|
|
if key.length() != 16 {
|
|
raise InvalidLength("NTCP2 SipHash key must be 16 bytes")
|
|
}
|
|
if initial_iv.length() != 8 {
|
|
raise InvalidLength("NTCP2 SipHash IV must be 8 bytes")
|
|
}
|
|
{ key, iv: initial_iv, }
|
|
}
|
|
|
|
///|
|
|
/// Advances the SipHash IV and returns the next 16-bit XOR length mask.
|
|
pub fn SipHashLengthMask::next_mask(
|
|
self : SipHashLengthMask,
|
|
) -> UInt32 raise NoiseError {
|
|
let h = @crypto.siphash_2_4(self.key, self.iv) catch { e => raise Crypto(e) }
|
|
let next_iv = FixedArray::make(8, b'\x00')
|
|
for i = 0; i < 8; i = i + 1 {
|
|
next_iv[i] = ((h >> (i * 8)) & 0xFFUL).to_byte()
|
|
}
|
|
self.iv = Bytes::from_array(next_iv)
|
|
// Low 16 bits of the 64-bit SipHash-2-4 output (per I2P NTCP2 spec)
|
|
(h & 0xFFFFUL).to_uint()
|
|
}
|
|
|
|
///|
|
|
/// Obfuscates or de-obfuscates a 16-bit NTCP2 frame length with the next SipHash mask.
|
|
pub fn SipHashLengthMask::xor_length(
|
|
self : SipHashLengthMask,
|
|
len : UInt32,
|
|
) -> UInt32 raise NoiseError {
|
|
(len ^ self.next_mask()) & 0xFFFFU
|
|
}
|