From ec0662e75205e9d00646d77abcba4a0c286e727e Mon Sep 17 00:00:00 2001 From: occheung Date: Sat, 17 Oct 2020 20:10:18 +0800 Subject: [PATCH] session: init --- src/buffer.rs | 2 +- src/key.rs | 18 +- src/lib.rs | 1 + src/main.rs | 105 +++++++++- src/session.rs | 528 +++++++++++++++++++++++++++++++++++++++++++++++++ src/tls.rs | 7 +- 6 files changed, 648 insertions(+), 13 deletions(-) diff --git a/src/buffer.rs b/src/buffer.rs index efb1109..59596a7 100644 --- a/src/buffer.rs +++ b/src/buffer.rs @@ -12,7 +12,7 @@ use crate::key::*; // Only designed to support read or write the entire buffer // TODO: Stricter visibility -pub(crate) struct TlsBuffer<'a> { +pub struct TlsBuffer<'a> { buffer: &'a mut [u8], index: RefCell, } diff --git a/src/key.rs b/src/key.rs index b311dfe..fb4cc24 100644 --- a/src/key.rs +++ b/src/key.rs @@ -9,19 +9,19 @@ use crate::buffer::TlsBuffer; use core::convert::TryFrom; #[derive(Debug, Clone)] -pub(crate) struct HkdfLabel<'a> { +pub struct HkdfLabel<'a> { // Length of hash function - pub(crate) length: u16, + pub length: u16, // Label vector: "tls13 " + label - pub(crate) label_length: u8, - pub(crate) label: &'a [u8], + pub label_length: u8, + pub label: &'a [u8], // Context vector: Hashed message - pub(crate) context_length: u8, - pub(crate) context: &'a [u8], + pub context_length: u8, + pub context: &'a [u8], } // Implementation of Derive-Secret function in RFC8446 -pub(crate) fn derive_secret( +pub fn derive_secret( hkdf: &Hkdf, label: &str, hash: Hash @@ -66,7 +66,7 @@ where // Implementation of HKDF-Expand-Label function in RFC8446 // Secret is embedded inside hkdf through salt and input key material (IKM) -pub(crate) fn hkdf_expand_label( +pub fn hkdf_expand_label( hkdf: &Hkdf, label: &str, context: &str, @@ -104,7 +104,7 @@ where // context_vec: 48 bytes for SHA384 + 1 byte (len) let mut array = [0; 100]; let mut buffer = TlsBuffer::new(&mut array); - buffer.enqueue_hkdf_label(hkdf_label); + buffer.enqueue_hkdf_label(hkdf_label).unwrap(); let info: &[u8] = buffer.into(); hkdf.expand(info, okm).unwrap(); diff --git a/src/lib.rs b/src/lib.rs index 1b6ecdc..941d685 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -9,6 +9,7 @@ pub mod parse; pub mod cipher_suite; pub mod buffer; pub mod key; +pub mod session; // TODO: Implement errors // Details: Encapsulate smoltcp & nom errors diff --git a/src/main.rs b/src/main.rs index 79ce5a6..09bb89b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -8,6 +8,20 @@ use rand_core::CryptoRng; use rand_core::impls; use rand_core::Error; +use p256::{EncodedPoint, AffinePoint, ecdh::EphemeralSecret, ecdh::SharedSecret}; +use aes_gcm::{Aes128Gcm, Aes256Gcm}; +use chacha20poly1305::{ChaCha20Poly1305, Key}; +use ccm::{Ccm, consts::*}; +use aes_gcm::aes::Aes128; +use aes_gcm::{AeadInPlace, NewAead}; +use generic_array::GenericArray; +use sha2::{ Digest, Sha256, Sha384, Sha512 }; +use heapless::Vec; +use hkdf::Hkdf; + +use smoltcp_tls::key::*; +use smoltcp_tls::buffer::TlsBuffer; + struct CountingRng(u64); impl RngCore for CountingRng { @@ -57,5 +71,92 @@ fn main() { 49600 ).unwrap(); - tls_socket.tls_connect(&mut sockets).unwrap(); -} \ No newline at end of file +// tls_socket.tls_connect(&mut sockets).unwrap(); + + let psk: [u8; 32] = [0; 32]; + let early_secret = Hkdf::::new(None, &psk); + let derived_secret = derive_secret( + &early_secret, + "derived", + Sha256::new().chain("") + ); + let (handshake_secret, handshake_secret_hkdf) = Hkdf::::extract( + Some(&derived_secret), + &SHARED_SECRET + ); + let client_handshake_traffic_secret = { + let hkdf_label = HkdfLabel { + length: 32, + label_length: 18, + label: b"tls13 c hs traffic", + context_length: 32, + context: &HELLO_HASH, + }; + let mut array = [0; 100]; + let mut buffer = TlsBuffer::new(&mut array); + buffer.enqueue_hkdf_label(hkdf_label); + let info: &[u8] = buffer.into(); + + // Define output key material (OKM), dynamically sized by hash + let mut okm: GenericArray = GenericArray::default(); + handshake_secret_hkdf.expand(info, &mut okm).unwrap(); + okm + }; + let server_handshake_traffic_secret = { + let hkdf_label = HkdfLabel { + length: 32, + label_length: 18, + label: b"tls13 s hs traffic", + context_length: 32, + context: &HELLO_HASH, + }; + let mut array = [0; 100]; + let mut buffer = TlsBuffer::new(&mut array); + buffer.enqueue_hkdf_label(hkdf_label); + let info: &[u8] = buffer.into(); + + // Define output key material (OKM), dynamically sized by hash + let mut okm: GenericArray = GenericArray::default(); + handshake_secret_hkdf.expand(info, &mut okm).unwrap(); + okm + }; + let client_handshake_write_key = { + let hkdf_label = HkdfLabel { + length: 16, + label_length: 9, + label: b"tls13 key", + context_length: 0, + context: b"", + }; + let mut array = [0; 100]; + let mut buffer = TlsBuffer::new(&mut array); + buffer.enqueue_hkdf_label(hkdf_label); + let info: &[u8] = buffer.into(); + + // Define output key material (OKM), dynamically sized by hash + let mut okm: GenericArray = GenericArray::default(); + Hkdf::::from_prk(&client_handshake_traffic_secret) + .unwrap() + .expand(info, &mut okm); + okm + }; + + println!("{:x?}", client_handshake_traffic_secret); + println!("{:x?}", server_handshake_traffic_secret); + println!("{:x?}", client_handshake_write_key); + +} + +const SHARED_SECRET: [u8; 32] = [ + 0xdf, 0x4a, 0x29, 0x1b, 0xaa, 0x1e, 0xb7, 0xcf, + 0xa6, 0x93, 0x4b, 0x29, 0xb4, 0x74, 0xba, 0xad, + 0x26, 0x97, 0xe2, 0x9f, 0x1f, 0x92, 0x0d, 0xcc, + 0x77, 0xc8, 0xa0, 0xa0, 0x88, 0x44, 0x76, 0x24 +]; + +const HELLO_HASH: [u8; 32] = [ + 0xda, 0x75, 0xce, 0x11, 0x39, 0xac, 0x80, 0xda, + 0xe4, 0x04, 0x4d, 0xa9, 0x32, 0x35, 0x0c, 0xf6, + 0x5c, 0x97, 0xcc, 0xc9, 0xe3, 0x3f, 0x1e, 0x6f, + 0x7d, 0x2d, 0x4b, 0x18, 0xb7, 0x36, 0xff, 0xd5 +]; \ No newline at end of file diff --git a/src/session.rs b/src/session.rs index e69de29..42ddcb5 100644 --- a/src/session.rs +++ b/src/session.rs @@ -0,0 +1,528 @@ +use p256::{ EncodedPoint, ecdh::EphemeralSecret }; +use heapless::{ Vec, consts::* }; +use sha2::{ Digest, Sha256, Sha384, digest::FixedOutput }; +use aes_gcm::{ Aes128Gcm, Aes256Gcm, aes::Aes128 }; +use aes_gcm::{ AeadInPlace, NewAead, aead::Buffer }; +use chacha20poly1305::ChaCha20Poly1305; +use ccm::Ccm; +use hkdf::Hkdf; +use generic_array::GenericArray; + +use core::convert::AsRef; +use core::cell::RefCell; + +use crate::tls::TlsState; +use crate::tls_packet::CipherSuite; +use crate::key::*; +use crate::Error; + +type Aes128Ccm = Ccm; + +pub(crate) struct Session { + state: TlsState, + role: TlsRole, + // Session ID for this session + session_id: Option<[u8; 32]>, + // Changed cipher spec + changed_cipher_spec: bool, + // Handshake secret, Master secret + // Early secret is computed right before HS + latest_secret: Option>, + // Hash functions needed + hash: Hash, + // Ephemeral secret for ECDHE key exchange + ecdhe_secret: Option, + // Block ciphers for client & server + client_cipher: Option, + server_cipher: Option, + // Traffic secret for client & server + // Keeping traffic secret for key re-computation + client_traffic_secret: Option>, + server_traffic_secret: Option>, + // Nonce (IV) for client & server + // Always 12 bytes long + client_nonce: Option>, + server_nonce: Option>, +} + +impl Session { + pub(crate) fn new(role: TlsRole) -> Self { + let hash = Hash::Undetermined { + sha256: Sha256::new(), + sha384: Sha384::new(), + }; + Self { + state: TlsState::START, + role, + session_id: None, + changed_cipher_spec: false, + latest_secret: None, + hash, + ecdhe_secret: None, + client_cipher: None, + server_cipher: None, + client_traffic_secret: None, + server_traffic_secret: None, + client_nonce: None, + server_nonce: None, + } + } + + // State transition from START to WAIT_SH + pub(crate) fn client_update_for_ch( + &mut self, + ecdhe_secret: EphemeralSecret, + session_id: [u8; 32], + ch_slice: &[u8] + ) { + // Handle inappropriate call to move state + if self.state != TlsState::START || self.role != TlsRole::Client { + todo!() + } + self.ecdhe_secret = Some(ecdhe_secret); + self.session_id = Some(session_id); + self.hash.update(ch_slice); + self.state = TlsState::WAIT_SH; + } + + // State transition from WAIT_SH to WAIT_EE + pub(crate) fn client_update_for_sh( + &mut self, + cipher_suite: CipherSuite, + encoded_point: EncodedPoint, + sh_slice: &[u8] + ) { + // Handle inappropriate call to move state + if self.state != TlsState::WAIT_SH || self.role != TlsRole::Client { + todo!() + } + // Generate ECDHE shared secret + // Remove private secret + let ecdhe_shared_secret = + self.ecdhe_secret + .take() + .unwrap() + .diffie_hellman(&encoded_point) + .unwrap(); + + // Generate Handshake secret + match cipher_suite { + CipherSuite::TLS_AES_128_GCM_SHA256 | + CipherSuite::TLS_CHACHA20_POLY1305_SHA256 | + CipherSuite::TLS_AES_128_CCM_SHA256 => { + // Select 1 hash function, then update the hash + self.hash = Hash::select_sha256(self.hash.clone()); + self.hash.update(sh_slice); + + // Find early secret in terms wrapped in HKDF + let empty_psk: GenericArray::OutputSize> = Default::default(); + let early_secret_hkdf = + Hkdf::::new(None, &empty_psk); + + // Find handshake secret + let empty_hash = Sha256::new().chain(""); + let derived_secret = derive_secret( + &early_secret_hkdf, + "derived", + empty_hash + ); + + let (handshake_secret, handshake_secret_hkdf) = + Hkdf::::extract( + Some(&derived_secret), + ecdhe_shared_secret.as_bytes() + ); + + let client_handshake_traffic_secret = derive_secret( + &handshake_secret_hkdf, + "c hs traffic", + self.hash.get_sha256_clone() + ); + + let server_handshake_traffic_secret = derive_secret( + &handshake_secret_hkdf, + "s hs traffic", + self.hash.get_sha256_clone() + ); + + let client_handshake_traffic_secret_hkdf = Hkdf::::from_prk(&client_handshake_traffic_secret).unwrap(); + let server_handshake_traffic_secret_hkdf = Hkdf::::from_prk(&server_handshake_traffic_secret).unwrap(); + + // Prepare holder for key and IV + let client_handshake_key: Vec = { + let mut client_handshake_key_holder: Vec = match cipher_suite { + // 16 bytes key size + CipherSuite::TLS_AES_128_GCM_SHA256 | + CipherSuite::TLS_AES_128_CCM_SHA256 => { + Vec::from_slice(&[0; 16]).unwrap() + }, + // 32 bytes key size + CipherSuite::TLS_CHACHA20_POLY1305_SHA256 => { + Vec::from_slice(&[0; 32]).unwrap() + }, + // Not using Sha256 (AES_GCM_256) / not supported (CCM_8) + _ => unreachable!() + }; + hkdf_expand_label( + &client_handshake_traffic_secret_hkdf, + "key", + "", + &mut client_handshake_key_holder + ); + client_handshake_key_holder + }; + + let client_handshake_iv: Vec = { + let mut client_handshake_iv_holder = Vec::from_slice(&[0; 12]).unwrap(); + hkdf_expand_label( + &client_handshake_traffic_secret_hkdf, + "iv", + "", + &mut client_handshake_iv_holder + ); + client_handshake_iv_holder + }; + + let server_handshake_key: Vec = { + let mut server_handshake_key_holder: Vec = match cipher_suite { + // 16 bytes key size + CipherSuite::TLS_AES_128_GCM_SHA256 | + CipherSuite::TLS_AES_128_CCM_SHA256 => { + Vec::from_slice(&[0; 16]).unwrap() + }, + // 32 bytes key size + CipherSuite::TLS_CHACHA20_POLY1305_SHA256 => { + Vec::from_slice(&[0; 32]).unwrap() + }, + // Not using Sha256 (AES_GCM_256) / not supported (CCM_8) + _ => unreachable!() + }; + hkdf_expand_label( + &server_handshake_traffic_secret_hkdf, + "key", + "", + &mut server_handshake_key_holder + ); + server_handshake_key_holder + }; + + let server_handshake_iv: Vec = { + let mut server_handshake_iv_holder = Vec::from_slice(&[0; 12]).unwrap(); + hkdf_expand_label( + &client_handshake_traffic_secret_hkdf, + "iv", + "", + &mut server_handshake_iv_holder + ); + server_handshake_iv_holder + }; + + // Store nonce + self.client_nonce = Some(client_handshake_iv); + self.server_nonce = Some(server_handshake_iv); + + // Construct cipher from key & IV for client & server + // Store the ciphers + match cipher_suite { + CipherSuite::TLS_AES_128_GCM_SHA256 => { + let client_handshake_cipher = Aes128Gcm::new( + GenericArray::from_slice(&client_handshake_key) + ); + let server_handshake_cipher = Aes128Gcm::new( + GenericArray::from_slice(&server_handshake_key) + ); + self.client_cipher = Some( + Cipher::Aes128Gcm { + aes128gcm: client_handshake_cipher + } + ); + self.server_cipher = Some( + Cipher::Aes128Gcm { + aes128gcm: server_handshake_cipher + } + ); + }, + CipherSuite::TLS_CHACHA20_POLY1305_SHA256 => { + let client_handshake_cipher = ChaCha20Poly1305::new( + GenericArray::from_slice(&client_handshake_key) + ); + let server_handshake_cipher = ChaCha20Poly1305::new( + GenericArray::from_slice(&server_handshake_key) + ); + self.client_cipher = Some( + Cipher::Chacha20poly1305 { + chacha20poly1305: client_handshake_cipher + } + ); + self.server_cipher = Some( + Cipher::Chacha20poly1305 { + chacha20poly1305: server_handshake_cipher + } + ); + }, + CipherSuite::TLS_AES_128_CCM_SHA256 => { + let client_handshake_cipher = Aes128Ccm::new( + GenericArray::from_slice(&client_handshake_key) + ); + let server_handshake_cipher = Aes128Ccm::new( + GenericArray::from_slice(&server_handshake_key) + ); + self.client_cipher = Some( + Cipher::Ccm { + ccm: client_handshake_cipher + } + ); + self.server_cipher = Some( + Cipher::Ccm { + ccm: server_handshake_cipher + } + ); + }, + _ => unreachable!() + } + } + CipherSuite::TLS_AES_256_GCM_SHA384 => { + // Select 1 hash function, then update the hash + self.hash = Hash::select_sha384(self.hash.clone()); + self.hash.update(sh_slice); + + // Find early secret in terms wrapped in HKDF + let empty_psk: GenericArray::OutputSize> = Default::default(); + let early_secret_hkdf = + Hkdf::::new(None, &empty_psk); + + // Find handshake secret + let empty_hash = Sha384::new().chain(""); + let derived_secret = derive_secret( + &early_secret_hkdf, + "derived", + empty_hash + ); + + let (handshake_secret, handshake_secret_hkdf) = + Hkdf::::extract( + Some(&derived_secret), + ecdhe_shared_secret.as_bytes() + ); + + let client_handshake_traffic_secret = derive_secret( + &handshake_secret_hkdf, + "c hs traffic", + self.hash.get_sha384_clone() + ); + + let server_handshake_traffic_secret = derive_secret( + &handshake_secret_hkdf, + "s hs traffic", + self.hash.get_sha384_clone() + ); + + let client_handshake_traffic_secret_hkdf = Hkdf::::from_prk(&client_handshake_traffic_secret).unwrap(); + let server_handshake_traffic_secret_hkdf = Hkdf::::from_prk(&server_handshake_traffic_secret).unwrap(); + + // Prepare holder for key and IV + let client_handshake_key: Vec = { + // 32 bytes key size + let mut client_handshake_key_holder: Vec = + Vec::from_slice(&[0; 32]).unwrap(); + + hkdf_expand_label( + &client_handshake_traffic_secret_hkdf, + "key", + "", + &mut client_handshake_key_holder + ); + client_handshake_key_holder + }; + + let client_handshake_iv: Vec = { + let mut client_handshake_iv_holder = Vec::from_slice(&[0; 12]).unwrap(); + hkdf_expand_label( + &client_handshake_traffic_secret_hkdf, + "iv", + "", + &mut client_handshake_iv_holder + ); + client_handshake_iv_holder + }; + + let server_handshake_key: Vec = { + // 32 bytes key size + let mut server_handshake_key_holder: Vec = + Vec::from_slice(&[0; 32]).unwrap(); + + hkdf_expand_label( + &server_handshake_traffic_secret_hkdf, + "key", + "", + &mut server_handshake_key_holder + ); + server_handshake_key_holder + }; + + let server_handshake_iv: Vec = { + let mut server_handshake_iv_holder = Vec::from_slice(&[0; 12]).unwrap(); + hkdf_expand_label( + &client_handshake_traffic_secret_hkdf, + "iv", + "", + &mut server_handshake_iv_holder + ); + server_handshake_iv_holder + }; + + // Store nonce + self.client_nonce = Some(client_handshake_iv); + self.server_nonce = Some(server_handshake_iv); + + let client_handshake_cipher = Aes256Gcm::new( + GenericArray::from_slice(&client_handshake_key) + ); + let server_handshake_cipher = Aes256Gcm::new( + GenericArray::from_slice(&server_handshake_key) + ); + self.client_cipher = Some( + Cipher::Aes256Gcm { + aes256gcm: client_handshake_cipher + } + ); + self.server_cipher = Some( + Cipher::Aes256Gcm { + aes256gcm: server_handshake_cipher + } + ); + + } + CipherSuite::TLS_AES_128_CCM_8_SHA256 => { + unreachable!() + } + } + self.state = TlsState::WAIT_EE; + } + + pub(crate) fn verify_session_id_echo(&self, session_id_echo: &[u8]) -> bool { + if let Some(session_id_inner) = self.session_id { + session_id_inner == session_id_echo + } else { + false + } + } + + pub(crate) fn get_tls_state(&self) -> TlsState { + self.state + } +} + +#[derive(Debug, PartialEq, Eq, Clone, Copy)] +pub(crate) enum TlsRole { + Client, + Server, +} + +#[derive(Debug, Clone)] +pub(crate) enum Hash { + Undetermined { + sha256: Sha256, + sha384: Sha384, + }, + Sha256 { + sha256: Sha256 + }, + Sha384 { + sha384: Sha384 + }, +} + +impl Hash { + pub(crate) fn update(&mut self, data: &[u8]) { + match self { + Self::Undetermined { sha256, sha384 } => { + sha256.update(data); + sha384.update(data); + }, + Self::Sha256 { sha256 } => { + sha256.update(data); + }, + Self::Sha384 { sha384 } => { + sha384.update(data); + }, + } + } + + pub(crate) fn select_sha256(self) -> Self { + match self { + Self::Undetermined { sha256, sha384 } => { + Self::Sha256 { + sha256 + } + }, + _ => unreachable!() + } + } + + pub(crate) fn select_sha384(self) -> Self { + match self { + Self::Undetermined { sha256, sha384 } => { + Self::Sha384 { + sha384 + } + }, + _ => unreachable!() + } + } + + pub(crate) fn get_sha256_clone(&mut self) -> Sha256 { + if let Self::Sha256 { sha256 } = self { + sha256.clone() + } else { + unreachable!() + } + } + + pub(crate) fn get_sha384_clone(&mut self) -> Sha384 { + if let Self::Sha384 { sha384 } = self { + sha384.clone() + } else { + unreachable!() + } + } +} + +pub(crate) enum Cipher { + Aes128Gcm { + aes128gcm: Aes128Gcm + }, + Aes256Gcm { + aes256gcm: Aes256Gcm + }, + Chacha20poly1305 { + chacha20poly1305: ChaCha20Poly1305 + }, + Ccm { + ccm: Aes128Ccm + }, +} + +impl Cipher { + pub(crate) fn encrypt_in_place( + &mut self, + nonce: &GenericArray, + associated_data: &[u8], + buffer: &mut dyn Buffer + ) -> Result<(), Error> { + match self { + Cipher::Aes128Gcm { aes128gcm } => { + aes128gcm.encrypt_in_place(nonce, associated_data, buffer) + }, + Cipher::Aes256Gcm { aes256gcm } => { + aes256gcm.encrypt_in_place(nonce, associated_data, buffer) + }, + Cipher::Chacha20poly1305 { chacha20poly1305 } => { + chacha20poly1305.encrypt_in_place(nonce, associated_data, buffer) + }, + Cipher::Ccm { ccm } => { + ccm.encrypt_in_place(nonce, associated_data, buffer) + } + }.map_err(|_| Error::EncryptionError) + } +} \ No newline at end of file diff --git a/src/tls.rs b/src/tls.rs index 991c23a..31e6c0e 100644 --- a/src/tls.rs +++ b/src/tls.rs @@ -37,10 +37,11 @@ use crate::tls_packet::*; use crate::parse::parse_tls_repr; use crate::cipher_suite::CipherSuite; use crate::buffer::TlsBuffer; +use crate::session::{Session, TlsRole}; #[derive(Debug, PartialEq, Eq, Clone, Copy)] #[allow(non_camel_case_types)] -enum TlsState { +pub(crate) enum TlsState { START, WAIT_SH, WAIT_EE, @@ -62,6 +63,7 @@ pub struct TlsSocket received_change_cipher_spec: RefCell>, cipher: RefCell>, handshake_sha256: RefCell, + session: RefCell, } impl TlsSocket { @@ -85,6 +87,9 @@ impl TlsSocket { received_change_cipher_spec: RefCell::new(None), cipher: RefCell::new(None), handshake_sha256: RefCell::new(Sha256::new()), + session: RefCell::new( + Session::new(TlsRole::Client) + ), } }