broke something

This commit is contained in:
mamoniot 2023-03-09 13:52:19 -05:00
parent 02ea954329
commit 6eaf0ffd6e
No known key found for this signature in database
GPG key ID: ADCCDBBE0E3D3B3B
2 changed files with 1735 additions and 28 deletions

1701
zssp/src/zssp (copy).rs Normal file

File diff suppressed because it is too large Load diff

View file

@ -12,7 +12,7 @@
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
use std::num::NonZeroU64; use std::num::NonZeroU64;
use std::sync::atomic::{AtomicI64, AtomicU64, Ordering}; use std::sync::atomic::{AtomicI64, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, RwLock, Weak}; use std::sync::{Arc, Mutex, RwLock, Weak, MutexGuard};
use zerotier_crypto::aes::{Aes, AesGcm}; use zerotier_crypto::aes::{Aes, AesGcm};
use zerotier_crypto::hash::{hmac_sha512, SHA384, SHA384_HASH_SIZE}; use zerotier_crypto::hash::{hmac_sha512, SHA384, SHA384_HASH_SIZE};
@ -83,7 +83,7 @@ pub struct Session<Application: ApplicationLayer> {
psk: Secret<BASE_KEY_SIZE>, psk: Secret<BASE_KEY_SIZE>,
send_counter: AtomicU64, send_counter: AtomicU64,
receive_window: [AtomicU64; COUNTER_WINDOW_MAX_OOO], receive_window: [AtomicU64; COUNTER_WINDOW_MAX_OOO],
header_protection_cipher: Aes, header_protection_cipher: Mutex<Aes>,
state: RwLock<State>, state: RwLock<State>,
defrag: [Mutex<Fragged<Application::IncomingPacketBuffer, MAX_FRAGMENTS>>; COUNTER_WINDOW_MAX_OOO], defrag: [Mutex<Fragged<Application::IncomingPacketBuffer, MAX_FRAGMENTS>>; COUNTER_WINDOW_MAX_OOO],
} }
@ -216,7 +216,7 @@ impl<Application: ApplicationLayer> Context<Application> {
state.remote_session_id, state.remote_session_id,
0, 0,
2, 2,
Some(&session.header_protection_cipher), Some(&mut *session.get_header_cipher()),
); );
} }
false false
@ -314,7 +314,7 @@ impl<Application: ApplicationLayer> Context<Application> {
psk, psk,
send_counter: AtomicU64::new(3), // 1 and 2 are reserved for init and final ack send_counter: AtomicU64::new(3), // 1 and 2 are reserved for init and final ack
receive_window: std::array::from_fn(|_| AtomicU64::new(0)), receive_window: std::array::from_fn(|_| AtomicU64::new(0)),
header_protection_cipher: Aes::new(&header_protection_key), header_protection_cipher: Mutex::new(Aes::new(&header_protection_key)),
state: RwLock::new(State { state: RwLock::new(State {
remote_session_id: None, remote_session_id: None,
keys: [None, None], keys: [None, None],
@ -357,7 +357,7 @@ impl<Application: ApplicationLayer> Context<Application> {
} }
// Encrypt and add authentication tag. // Encrypt and add authentication tag.
let gcm = AesGcm::new( let mut gcm = AesGcm::new(
&kbkdf::<AES_256_KEY_SIZE, KBKDF_KEY_USAGE_LABEL_KEX_ES>(noise_es.as_bytes()) &kbkdf::<AES_256_KEY_SIZE, KBKDF_KEY_USAGE_LABEL_KEX_ES>(noise_es.as_bytes())
); );
gcm.reset_init_gcm(&create_message_nonce(PACKET_TYPE_ALICE_NOISE_XK_INIT, 1)); gcm.reset_init_gcm(&create_message_nonce(PACKET_TYPE_ALICE_NOISE_XK_INIT, 1));
@ -443,7 +443,7 @@ impl<Application: ApplicationLayer> Context<Application> {
debug_assert!(!self.sessions.read().unwrap().incoming.contains_key(&local_session_id)); debug_assert!(!self.sessions.read().unwrap().incoming.contains_key(&local_session_id));
session session
.header_protection_cipher .get_header_cipher()
.decrypt_block_in_place(&mut incoming_packet[HEADER_PROTECT_ENCRYPT_START..HEADER_PROTECT_ENCRYPT_END]); .decrypt_block_in_place(&mut incoming_packet[HEADER_PROTECT_ENCRYPT_START..HEADER_PROTECT_ENCRYPT_END]);
let (key_index, packet_type, fragment_count, fragment_no, incoming_counter) = parse_packet_header(&incoming_packet); let (key_index, packet_type, fragment_count, fragment_no, incoming_counter) = parse_packet_header(&incoming_packet);
@ -604,7 +604,7 @@ impl<Application: ApplicationLayer> Context<Application> {
if let Some(session) = session { if let Some(session) = session {
let state = session.state.read().unwrap(); let state = session.state.read().unwrap();
if let Some(key) = state.keys[key_index].as_ref() { if let Some(key) = state.keys[key_index].as_ref() {
let c = key.get_receive_cipher(); let mut c = key.get_receive_cipher();
c.reset_init_gcm(&incoming_message_nonce); c.reset_init_gcm(&incoming_message_nonce);
let mut data_len = 0; let mut data_len = 0;
@ -730,7 +730,7 @@ impl<Application: ApplicationLayer> Context<Application> {
let noise_h_next = mix_hash(&noise_h, &pkt_assembled[HEADER_SIZE..]); let noise_h_next = mix_hash(&noise_h, &pkt_assembled[HEADER_SIZE..]);
// Decrypt and authenticate init packet, also proving that caller knows our static identity. // Decrypt and authenticate init packet, also proving that caller knows our static identity.
let gcm = AesGcm::new( let mut gcm = AesGcm::new(
&kbkdf::<AES_256_KEY_SIZE, KBKDF_KEY_USAGE_LABEL_KEX_ES>(noise_es.as_bytes()) &kbkdf::<AES_256_KEY_SIZE, KBKDF_KEY_USAGE_LABEL_KEX_ES>(noise_es.as_bytes())
); );
gcm.reset_init_gcm(&incoming_message_nonce); gcm.reset_init_gcm(&incoming_message_nonce);
@ -780,7 +780,7 @@ impl<Application: ApplicationLayer> Context<Application> {
ack.bob_hk_ciphertext = bob_hk_ciphertext; ack.bob_hk_ciphertext = bob_hk_ciphertext;
// Encrypt main section of reply and attach tag. // Encrypt main section of reply and attach tag.
let gcm = AesGcm::new( let mut gcm = AesGcm::new(
&kbkdf::<AES_256_KEY_SIZE, KBKDF_KEY_USAGE_LABEL_KEX_ES_EE>(noise_es_ee.as_bytes()) &kbkdf::<AES_256_KEY_SIZE, KBKDF_KEY_USAGE_LABEL_KEX_ES_EE>(noise_es_ee.as_bytes())
); );
gcm.reset_init_gcm(&create_message_nonce(PACKET_TYPE_BOB_NOISE_XK_ACK, 1)); gcm.reset_init_gcm(&create_message_nonce(PACKET_TYPE_BOB_NOISE_XK_ACK, 1));
@ -834,7 +834,7 @@ impl<Application: ApplicationLayer> Context<Application> {
Some(alice_session_id), Some(alice_session_id),
0, 0,
1, 1,
Some(&Aes::new(&header_protection_key)), Some(&mut Aes::new(&header_protection_key)),
)?; )?;
return Ok(ReceiveResult::Ok(session)); return Ok(ReceiveResult::Ok(session));
@ -882,7 +882,7 @@ impl<Application: ApplicationLayer> Context<Application> {
let noise_h_next = mix_hash(&mix_hash(&outgoing_offer.noise_h, bob_noise_e.as_bytes()), &pkt_assembled[HEADER_SIZE..]); let noise_h_next = mix_hash(&mix_hash(&outgoing_offer.noise_h, bob_noise_e.as_bytes()), &pkt_assembled[HEADER_SIZE..]);
// Decrypt and authenticate Bob's reply. // Decrypt and authenticate Bob's reply.
let gcm = AesGcm::new( let mut gcm = AesGcm::new(
&kbkdf::<AES_256_KEY_SIZE, KBKDF_KEY_USAGE_LABEL_KEX_ES_EE>(noise_es_ee.as_bytes()) &kbkdf::<AES_256_KEY_SIZE, KBKDF_KEY_USAGE_LABEL_KEX_ES_EE>(noise_es_ee.as_bytes())
); );
gcm.reset_init_gcm(&incoming_message_nonce); gcm.reset_init_gcm(&incoming_message_nonce);
@ -927,7 +927,7 @@ impl<Application: ApplicationLayer> Context<Application> {
let mut enc_start = reply_len; let mut enc_start = reply_len;
reply_len = append_to_slice(&mut reply_buffer, reply_len, alice_s_public_blob)?; reply_len = append_to_slice(&mut reply_buffer, reply_len, alice_s_public_blob)?;
let gcm = AesGcm::new( let mut gcm = AesGcm::new(
&kbkdf::<AES_256_KEY_SIZE, KBKDF_KEY_USAGE_LABEL_KEX_ES_EE_HK>(&hmac_sha512( &kbkdf::<AES_256_KEY_SIZE, KBKDF_KEY_USAGE_LABEL_KEX_ES_EE_HK>(&hmac_sha512(
noise_es_ee.as_bytes(), noise_es_ee.as_bytes(),
hk.as_bytes(), hk.as_bytes(),
@ -948,7 +948,7 @@ impl<Application: ApplicationLayer> Context<Application> {
enc_start = reply_len; enc_start = reply_len;
reply_len = append_to_slice(&mut reply_buffer, reply_len, metadata)?; reply_len = append_to_slice(&mut reply_buffer, reply_len, metadata)?;
let gcm = AesGcm::new( let mut gcm = AesGcm::new(
&kbkdf::<AES_256_KEY_SIZE, KBKDF_KEY_USAGE_LABEL_KEX_ES_EE_SE_HK_PSK>(noise_es_ee_se_hk_psk.as_bytes()) &kbkdf::<AES_256_KEY_SIZE, KBKDF_KEY_USAGE_LABEL_KEX_ES_EE_SE_HK_PSK>(noise_es_ee_se_hk_psk.as_bytes())
); );
gcm.reset_init_gcm(&reply_message_nonce); gcm.reset_init_gcm(&reply_message_nonce);
@ -979,7 +979,7 @@ impl<Application: ApplicationLayer> Context<Application> {
Some(bob_session_id), Some(bob_session_id),
0, 0,
2, 2,
Some(&session.header_protection_cipher), Some(&mut *session.get_header_cipher()),
)?; )?;
return Ok(ReceiveResult::Ok(Some(session))); return Ok(ReceiveResult::Ok(Some(session)));
@ -1076,7 +1076,7 @@ impl<Application: ApplicationLayer> Context<Application> {
psk, psk,
send_counter: AtomicU64::new(2), // 1 was already used during negotiation send_counter: AtomicU64::new(2), // 1 was already used during negotiation
receive_window: std::array::from_fn(|_| AtomicU64::new(0)), receive_window: std::array::from_fn(|_| AtomicU64::new(0)),
header_protection_cipher: Aes::new(&incoming.header_protection_key), header_protection_cipher: Mutex::new(Aes::new(&incoming.header_protection_key)),
state: RwLock::new(State { state: RwLock::new(State {
remote_session_id: Some(incoming.alice_session_id), remote_session_id: Some(incoming.alice_session_id),
keys: [ keys: [
@ -1126,7 +1126,7 @@ impl<Application: ApplicationLayer> Context<Application> {
// Only the current "Alice" accepts rekeys initiated by the current "Bob." These roles // Only the current "Alice" accepts rekeys initiated by the current "Bob." These roles
// flip with each rekey event. // flip with each rekey event.
if !key.bob { if !key.bob {
let c = key.get_receive_cipher(); let mut c = key.get_receive_cipher();
c.reset_init_gcm(&incoming_message_nonce); c.reset_init_gcm(&incoming_message_nonce);
c.crypt_in_place(&mut pkt_assembled[RekeyInit::ENC_START..RekeyInit::AUTH_START]); c.crypt_in_place(&mut pkt_assembled[RekeyInit::ENC_START..RekeyInit::AUTH_START]);
let aead_authentication_ok = c.finish_decrypt(&pkt_assembled[RekeyInit::AUTH_START..]); let aead_authentication_ok = c.finish_decrypt(&pkt_assembled[RekeyInit::AUTH_START..]);
@ -1158,14 +1158,14 @@ impl<Application: ApplicationLayer> Context<Application> {
counter, counter,
); );
let c = key.get_send_cipher(counter)?; let mut c = key.get_send_cipher(counter)?;
c.reset_init_gcm(&create_message_nonce(PACKET_TYPE_REKEY_ACK, counter)); c.reset_init_gcm(&create_message_nonce(PACKET_TYPE_REKEY_ACK, counter));
c.crypt_in_place(&mut reply_buf[RekeyAck::ENC_START..RekeyAck::AUTH_START]); c.crypt_in_place(&mut reply_buf[RekeyAck::ENC_START..RekeyAck::AUTH_START]);
reply_buf[RekeyAck::AUTH_START..].copy_from_slice(&c.finish_encrypt()); reply_buf[RekeyAck::AUTH_START..].copy_from_slice(&c.finish_encrypt());
key.return_send_cipher(c); key.return_send_cipher(c);
session session
.header_protection_cipher .get_header_cipher()
.encrypt_block_in_place(&mut reply_buf[HEADER_PROTECT_ENCRYPT_START..HEADER_PROTECT_ENCRYPT_END]); .encrypt_block_in_place(&mut reply_buf[HEADER_PROTECT_ENCRYPT_START..HEADER_PROTECT_ENCRYPT_END]);
send(Some(&session), &mut reply_buf); send(Some(&session), &mut reply_buf);
@ -1213,7 +1213,7 @@ impl<Application: ApplicationLayer> Context<Application> {
if let Some(key) = state.keys[key_index].as_ref() { if let Some(key) = state.keys[key_index].as_ref() {
// Only the current "Bob" initiates rekeys and expects this ACK. // Only the current "Bob" initiates rekeys and expects this ACK.
if key.bob { if key.bob {
let c = key.get_receive_cipher(); let mut c = key.get_receive_cipher();
c.reset_init_gcm(&incoming_message_nonce); c.reset_init_gcm(&incoming_message_nonce);
c.crypt_in_place(&mut pkt_assembled[RekeyAck::ENC_START..RekeyAck::AUTH_START]); c.crypt_in_place(&mut pkt_assembled[RekeyAck::ENC_START..RekeyAck::AUTH_START]);
let aead_authentication_ok = c.finish_decrypt(&pkt_assembled[RekeyAck::AUTH_START..]); let aead_authentication_ok = c.finish_decrypt(&pkt_assembled[RekeyAck::AUTH_START..]);
@ -1283,7 +1283,7 @@ impl<Application: ApplicationLayer> Session<Application> {
if let Some(session_key) = state.keys[state.current_key].as_ref() { if let Some(session_key) = state.keys[state.current_key].as_ref() {
let counter = self.get_next_outgoing_counter().ok_or(Error::MaxKeyLifetimeExceeded)?.get(); let counter = self.get_next_outgoing_counter().ok_or(Error::MaxKeyLifetimeExceeded)?.get();
let c = session_key.get_send_cipher(counter)?; let mut c = session_key.get_send_cipher(counter)?;
c.reset_init_gcm(&create_message_nonce(PACKET_TYPE_DATA, counter)); c.reset_init_gcm(&create_message_nonce(PACKET_TYPE_DATA, counter));
let fragment_count = (((data.len() + AES_GCM_TAG_SIZE) as f32) / (mtu_sized_buffer.len() - HEADER_SIZE) as f32).ceil() as usize; let fragment_count = (((data.len() + AES_GCM_TAG_SIZE) as f32) / (mtu_sized_buffer.len() - HEADER_SIZE) as f32).ceil() as usize;
@ -1314,7 +1314,7 @@ impl<Application: ApplicationLayer> Session<Application> {
fragment_size = tagged_fragment_size; fragment_size = tagged_fragment_size;
} }
self.header_protection_cipher self.get_header_cipher()
.encrypt_block_in_place(&mut mtu_sized_buffer[HEADER_PROTECT_ENCRYPT_START..HEADER_PROTECT_ENCRYPT_END]); .encrypt_block_in_place(&mut mtu_sized_buffer[HEADER_PROTECT_ENCRYPT_START..HEADER_PROTECT_ENCRYPT_END]);
send(&mut mtu_sized_buffer[..fragment_size]); send(&mut mtu_sized_buffer[..fragment_size]);
} }
@ -1335,12 +1335,12 @@ impl<Application: ApplicationLayer> Session<Application> {
if let Some(session_key) = state.keys[state.current_key].as_ref() { if let Some(session_key) = state.keys[state.current_key].as_ref() {
let counter = self.get_next_outgoing_counter().ok_or(Error::MaxKeyLifetimeExceeded)?.get(); let counter = self.get_next_outgoing_counter().ok_or(Error::MaxKeyLifetimeExceeded)?.get();
let mut nop = [0u8; HEADER_SIZE + AES_GCM_TAG_SIZE]; let mut nop = [0u8; HEADER_SIZE + AES_GCM_TAG_SIZE];
let c = session_key.get_send_cipher(counter)?; let mut c = session_key.get_send_cipher(counter)?;
c.reset_init_gcm(&create_message_nonce(PACKET_TYPE_NOP, counter)); c.reset_init_gcm(&create_message_nonce(PACKET_TYPE_NOP, counter));
nop[HEADER_SIZE..].copy_from_slice(&c.finish_encrypt()); nop[HEADER_SIZE..].copy_from_slice(&c.finish_encrypt());
session_key.return_send_cipher(c); session_key.return_send_cipher(c);
set_packet_header(&mut nop, 1, 0, PACKET_TYPE_NOP, u64::from(remote_session_id), state.current_key, counter); set_packet_header(&mut nop, 1, 0, PACKET_TYPE_NOP, u64::from(remote_session_id), state.current_key, counter);
self.header_protection_cipher self.get_header_cipher()
.encrypt_block_in_place(&mut nop[HEADER_PROTECT_ENCRYPT_START..HEADER_PROTECT_ENCRYPT_END]); .encrypt_block_in_place(&mut nop[HEADER_PROTECT_ENCRYPT_START..HEADER_PROTECT_ENCRYPT_END]);
send(&mut nop); send(&mut nop);
} }
@ -1381,7 +1381,7 @@ impl<Application: ApplicationLayer> Session<Application> {
if let Some(remote_session_id) = state.remote_session_id { if let Some(remote_session_id) = state.remote_session_id {
if let Some(key) = state.keys[state.current_key].as_ref() { if let Some(key) = state.keys[state.current_key].as_ref() {
if let Some(counter) = self.get_next_outgoing_counter() { if let Some(counter) = self.get_next_outgoing_counter() {
if let Ok(gcm) = key.get_send_cipher(counter.get()) { if let Ok(mut gcm) = key.get_send_cipher(counter.get()) {
gcm.reset_init_gcm(&create_message_nonce(PACKET_TYPE_REKEY_INIT, counter.get())); gcm.reset_init_gcm(&create_message_nonce(PACKET_TYPE_REKEY_INIT, counter.get()));
gcm.crypt_in_place(&mut rekey_buf[RekeyInit::ENC_START..RekeyInit::AUTH_START]); gcm.crypt_in_place(&mut rekey_buf[RekeyInit::ENC_START..RekeyInit::AUTH_START]);
rekey_buf[RekeyInit::AUTH_START..].copy_from_slice(&gcm.finish_encrypt()); rekey_buf[RekeyInit::AUTH_START..].copy_from_slice(&gcm.finish_encrypt());
@ -1400,7 +1400,7 @@ impl<Application: ApplicationLayer> Session<Application> {
drop(state); drop(state);
self.header_protection_cipher self.get_header_cipher()
.encrypt_block_in_place(&mut rekey_buf[HEADER_PROTECT_ENCRYPT_START..HEADER_PROTECT_ENCRYPT_END]); .encrypt_block_in_place(&mut rekey_buf[HEADER_PROTECT_ENCRYPT_START..HEADER_PROTECT_ENCRYPT_END]);
send(&mut rekey_buf); send(&mut rekey_buf);
@ -1431,6 +1431,12 @@ impl<Application: ApplicationLayer> Session<Application> {
let prev_counter = self.receive_window[(counter as usize) % COUNTER_WINDOW_MAX_OOO].fetch_max(counter, Ordering::AcqRel); let prev_counter = self.receive_window[(counter as usize) % COUNTER_WINDOW_MAX_OOO].fetch_max(counter, Ordering::AcqRel);
prev_counter < counter && counter.wrapping_sub(prev_counter) < COUNTER_WINDOW_MAX_SKIP_AHEAD prev_counter < counter && counter.wrapping_sub(prev_counter) < COUNTER_WINDOW_MAX_SKIP_AHEAD
} }
#[inline(always)]
fn get_header_cipher<'a>(&'a self) -> MutexGuard<'a, Aes>{
self.header_protection_cipher.lock().unwrap()
}
} }
#[inline(always)] #[inline(always)]
@ -1493,7 +1499,7 @@ fn send_with_fragmentation<SendFunction: FnMut(&mut [u8])>(
remote_session_id: Option<SessionId>, remote_session_id: Option<SessionId>,
key_index: usize, key_index: usize,
counter: u64, counter: u64,
header_protect_cipher: Option<&Aes>, mut header_protect_cipher: Option<&mut Aes>,
) -> Result<(), Error> { ) -> Result<(), Error> {
let packet_len = packet.len(); let packet_len = packet.len();
let recipient_session_id = remote_session_id.map_or(SessionId::NONE, |s| u64::from(s)); let recipient_session_id = remote_session_id.map_or(SessionId::NONE, |s| u64::from(s));
@ -1511,7 +1517,7 @@ fn send_with_fragmentation<SendFunction: FnMut(&mut [u8])>(
key_index, key_index,
counter, counter,
); );
if let Some(hcc) = header_protect_cipher { if let Some(hcc) = header_protect_cipher.take() {
hcc.encrypt_block_in_place(&mut fragment[HEADER_PROTECT_ENCRYPT_START..HEADER_PROTECT_ENCRYPT_END]); hcc.encrypt_block_in_place(&mut fragment[HEADER_PROTECT_ENCRYPT_START..HEADER_PROTECT_ENCRYPT_END]);
} }
send(fragment); send(fragment);
@ -1634,7 +1640,7 @@ impl<'a> PktReader<'a> {
fn read_decrypt_auth<'b>(&'b mut self, l: usize, k: Secret<AES_256_KEY_SIZE>, gcm_aad: &[u8], nonce: &[u8]) -> Result<&'b [u8], Error> { fn read_decrypt_auth<'b>(&'b mut self, l: usize, k: Secret<AES_256_KEY_SIZE>, gcm_aad: &[u8], nonce: &[u8]) -> Result<&'b [u8], Error> {
let mut tmp = self.1 + l; let mut tmp = self.1 + l;
if (tmp + AES_GCM_TAG_SIZE) <= self.0.len() { if (tmp + AES_GCM_TAG_SIZE) <= self.0.len() {
let gcm = AesGcm::new(&k); let mut gcm = AesGcm::new(&k);
gcm.reset_init_gcm(nonce); gcm.reset_init_gcm(nonce);
gcm.aad(gcm_aad); gcm.aad(gcm_aad);
gcm.crypt_in_place(&mut self.0[self.1..tmp]); gcm.crypt_in_place(&mut self.0[self.1..tmp]);