Changed crypto

This commit is contained in:
Dennis Schwerdel 2021-02-09 23:50:00 +01:00
parent dd665784c6
commit 21d58f25a3
5 changed files with 106 additions and 206 deletions

View File

@ -1,7 +1,7 @@
use super::{ use super::{core::test_speed, rotate::RotationState};
core::{test_speed, CryptoCore}, pub use super::{
init::{self, InitResult, InitState, CLOSING}, core::{CryptoCore, EXTRA_LEN, TAG_LEN},
rotate::RotationState init::{is_init_message, INIT_MESSAGE_FIRST_BYTE, InitState, InitResult}
}; };
use crate::{ use crate::{
error::Error, error::Error,
@ -20,8 +20,8 @@ use std::{fmt::Debug, io::Read, num::NonZeroU32, sync::Arc, time::Duration};
const SALT: &[u8; 32] = b"vpncloudVPNCLOUDvpncl0udVpnCloud"; const SALT: &[u8; 32] = b"vpncloudVPNCLOUDvpncl0udVpnCloud";
const INIT_MESSAGE_FIRST_BYTE: u8 = 0xff;
const MESSAGE_TYPE_ROTATION: u8 = 0x10; pub const MESSAGE_TYPE_ROTATION: u8 = 0x10;
pub type Ed25519PublicKey = [u8; ED25519_PUBLIC_KEY_LEN]; pub type Ed25519PublicKey = [u8; ED25519_PUBLIC_KEY_LEN];
pub type EcdhPublicKey = UnparsedPublicKey<SmallVec<[u8; 96]>>; pub type EcdhPublicKey = UnparsedPublicKey<SmallVec<[u8; 96]>>;
@ -180,175 +180,84 @@ impl Crypto {
Ok(result) Ok(result)
} }
pub fn peer_instance<P: Payload>(&self, payload: P) -> PeerCrypto<P> { pub fn peer_instance<P: Payload>(&self, payload: P) -> InitState<P> {
PeerCrypto::new( InitState::new(self.node_id, payload, self.key_pair.clone(), self.trusted_keys.clone(), self.algorithms.clone())
self.node_id,
payload,
self.key_pair.clone(),
self.trusted_keys.clone(),
self.algorithms.clone()
)
} }
} }
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq)]
pub enum MessageResult<P: Payload> { pub enum MessageResult {
Message(u8), Message(u8),
Initialized(P),
InitializedWithReply(P),
Reply, Reply,
None None
} }
pub struct PeerCrypto<P: Payload> { pub enum PeerCrypto {
#[allow(dead_code)] Encrypted {
node_id: NodeId, last_init_message: Vec<u8>,
init: Option<InitState<P>>, algorithm: &'static Algorithm,
rotation: Option<RotationState>, rotation: RotationState,
unencrypted: bool, core: Arc<CryptoCore>,
core: Option<CryptoCore>, rotate_counter: usize
rotate_counter: usize },
Unencrypted {
last_init_message: Vec<u8>
}
} }
impl<P: Payload> PeerCrypto<P> { impl PeerCrypto {
pub fn new(
node_id: NodeId, init_payload: P, key_pair: Arc<Ed25519KeyPair>, trusted_keys: Arc<[Ed25519PublicKey]>,
algorithms: Algorithms
) -> Self
{
Self {
node_id,
init: Some(InitState::new(node_id, init_payload, key_pair, trusted_keys, algorithms)),
rotation: None,
unencrypted: false,
core: None,
rotate_counter: 0
}
}
fn get_init(&mut self) -> Result<&mut InitState<P>, Error> {
if let Some(init) = &mut self.init {
Ok(init)
} else {
Err(Error::InvalidCryptoState("Initialization already finished"))
}
}
fn get_core(&mut self) -> Result<&mut CryptoCore, Error> {
if let Some(core) = &mut self.core {
Ok(core)
} else {
Err(Error::InvalidCryptoState("Crypto core not ready yet"))
}
}
fn get_rotation(&mut self) -> Result<&mut RotationState, Error> {
if let Some(rotation) = &mut self.rotation {
Ok(rotation)
} else {
Err(Error::InvalidCryptoState("Key rotation not initialized"))
}
}
pub fn initialize(&mut self, out: &mut MsgBuffer) -> Result<(), Error> {
let init = self.get_init()?;
if init.stage() != init::STAGE_PING {
Err(Error::InvalidCryptoState("Initialization already ongoing"))
} else {
init.send_ping(out);
out.prepend_byte(INIT_MESSAGE_FIRST_BYTE);
Ok(())
}
}
pub fn has_init(&self) -> bool {
self.init.is_some()
}
pub fn is_ready(&self) -> bool {
self.core.is_some()
}
pub fn algorithm_name(&self) -> &'static str { pub fn algorithm_name(&self) -> &'static str {
if let Some(ref core) = self.core { match self {
let algo = core.algorithm(); PeerCrypto::Encrypted { algorithm, .. } => {
if algo == &aead::CHACHA20_POLY1305 { match *algorithm {
"CHACHA20" x if x == &aead::CHACHA20_POLY1305 => "CHACHA20",
} else if algo == &aead::AES_128_GCM { x if x == &aead::AES_128_GCM => "AES128",
"AES128" x if x == &aead::AES_256_GCM => "AES256",
} else if algo == &aead::AES_256_GCM { _ => unreachable!()
"AES256" }
} else {
unreachable!()
} }
} else { PeerCrypto::Unencrypted { .. } => "PLAIN"
"PLAIN"
} }
} }
fn handle_init_message(&mut self, buffer: &mut MsgBuffer) -> Result<MessageResult<P>, Error> { fn handle_init_message(&mut self, buffer: &mut MsgBuffer) -> Result<MessageResult, Error> {
let result = self.get_init()?.handle_init(buffer)?; // TODO: parse message stage
if !buffer.is_empty() { // TODO: depending on stage resend last message
buffer.prepend_byte(INIT_MESSAGE_FIRST_BYTE); Ok(MessageResult::None)
}
match result {
InitResult::Continue => Ok(MessageResult::Reply),
InitResult::Success { peer_payload, is_initiator } => {
self.core = self.get_init()?.take_core();
if self.core.is_none() {
self.unencrypted = true;
}
if self.get_init()?.stage() == init::CLOSING {
self.init = None
}
if self.core.is_some() {
self.rotation = Some(RotationState::new(!is_initiator, buffer));
}
if !is_initiator {
if self.unencrypted {
return Ok(MessageResult::Initialized(peer_payload))
}
assert!(!buffer.is_empty());
buffer.prepend_byte(MESSAGE_TYPE_ROTATION);
self.encrypt_message(buffer)?;
}
Ok(MessageResult::InitializedWithReply(peer_payload))
}
}
} }
fn handle_rotate_message(&mut self, data: &[u8]) -> Result<(), Error> { fn handle_rotate_message(&mut self, data: &[u8]) -> Result<(), Error> {
if self.unencrypted { match self {
return Ok(()) PeerCrypto::Encrypted { rotation, core, algorithm, .. } => {
if let Some(rot) = rotation.handle_message(data)? {
let key = LessSafeKey::new(UnboundKey::new(algorithm, &rot.key[..algorithm.key_len()]).unwrap());
core.rotate_key(key, rot.id, rot.use_for_sending);
}
Ok(())
}
PeerCrypto::Unencrypted { .. } => Err(Error::Crypto("Rotation when unencrypted"))
} }
if let Some(rot) = self.get_rotation()?.handle_message(data)? {
let core = self.get_core()?;
let algo = core.algorithm();
let key = LessSafeKey::new(UnboundKey::new(algo, &rot.key[..algo.key_len()]).unwrap());
core.rotate_key(key, rot.id, rot.use_for_sending);
}
Ok(())
} }
fn encrypt_message(&mut self, buffer: &mut MsgBuffer) -> Result<(), Error> { fn encrypt_message(&mut self, buffer: &mut MsgBuffer) {
if self.unencrypted { // HOT PATH
return Ok(()) if let PeerCrypto::Encrypted { core, .. } = self {
core.encrypt(buffer)
} }
self.get_core()?.encrypt(buffer);
Ok(())
} }
fn decrypt_message(&mut self, buffer: &mut MsgBuffer) -> Result<(), Error> { fn decrypt_message(&mut self, buffer: &mut MsgBuffer) -> Result<(), Error> {
// HOT PATH // HOT PATH
if self.unencrypted { if let PeerCrypto::Encrypted { core, .. } = self {
return Ok(()) core.decrypt(buffer)
} else {
Ok(())
} }
self.get_core()?.decrypt(buffer)
} }
pub fn handle_message(&mut self, buffer: &mut MsgBuffer) -> Result<MessageResult<P>, Error> { pub fn handle_message(&mut self, buffer: &mut MsgBuffer) -> Result<MessageResult, Error> {
// HOT PATH // HOT PATH
if buffer.is_empty() { if buffer.is_empty() {
return Err(Error::InvalidCryptoState("No message in buffer")) return Err(Error::InvalidCryptoState("No message in buffer"))
@ -356,7 +265,6 @@ impl<P: Payload> PeerCrypto<P> {
if is_init_message(buffer.buffer()) { if is_init_message(buffer.buffer()) {
// COLD PATH // COLD PATH
debug!("Received init message"); debug!("Received init message");
buffer.take_prefix();
self.handle_init_message(buffer) self.handle_init_message(buffer)
} else { } else {
// HOT PATH // HOT PATH
@ -375,54 +283,35 @@ impl<P: Payload> PeerCrypto<P> {
} }
} }
pub fn send_message(&mut self, type_: u8, buffer: &mut MsgBuffer) -> Result<(), Error> { pub fn send_message(&mut self, type_: u8, buffer: &mut MsgBuffer) {
// HOT PATH // HOT PATH
assert_ne!(type_, MESSAGE_TYPE_ROTATION); assert_ne!(type_, MESSAGE_TYPE_ROTATION);
buffer.prepend_byte(type_); buffer.prepend_byte(type_);
self.encrypt_message(buffer) self.encrypt_message(buffer);
} }
pub fn every_second(&mut self, out: &mut MsgBuffer) -> Result<MessageResult<P>, Error> { pub fn every_second(&mut self, out: &mut MsgBuffer) -> MessageResult {
out.clear(); out.clear();
if let Some(ref mut core) = self.core { if let PeerCrypto::Encrypted { core, rotation, rotate_counter, algorithm, .. } = self {
core.every_second() core.every_second();
} *rotate_counter += 1;
if let Some(ref mut init) = self.init { if *rotate_counter >= ROTATE_INTERVAL {
init.every_second(out)?; *rotate_counter = 0;
} if let Some(rot) = rotation.cycle(out) {
if self.init.as_ref().map(|i| i.stage()).unwrap_or(CLOSING) == CLOSING { let key = LessSafeKey::new(UnboundKey::new(algorithm, &rot.key[..algorithm.key_len()]).unwrap());
self.init = None
}
if !out.is_empty() {
out.prepend_byte(INIT_MESSAGE_FIRST_BYTE);
return Ok(MessageResult::Reply)
}
if let Some(ref mut rotate) = self.rotation {
self.rotate_counter += 1;
if self.rotate_counter >= ROTATE_INTERVAL {
self.rotate_counter = 0;
if let Some(rot) = rotate.cycle(out) {
let core = self.get_core()?;
let algo = core.algorithm();
let key = LessSafeKey::new(UnboundKey::new(algo, &rot.key[..algo.key_len()]).unwrap());
core.rotate_key(key, rot.id, rot.use_for_sending); core.rotate_key(key, rot.id, rot.use_for_sending);
} }
if !out.is_empty() { if !out.is_empty() {
out.prepend_byte(MESSAGE_TYPE_ROTATION); out.prepend_byte(MESSAGE_TYPE_ROTATION);
self.encrypt_message(out)?; self.encrypt_message(out);
return Ok(MessageResult::Reply) return MessageResult::Reply
} }
} }
} }
Ok(MessageResult::None) MessageResult::None
} }
} }
pub fn is_init_message(msg: &[u8]) -> bool {
// HOT PATH
!msg.is_empty() && msg[0] == INIT_MESSAGE_FIRST_BYTE
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
@ -430,7 +319,7 @@ mod tests {
use crate::types::NODE_ID_BYTES; use crate::types::NODE_ID_BYTES;
fn create_node(config: &Config) -> PeerCrypto<Vec<u8>> { fn create_node(config: &Config) -> InitState<Vec<u8>> {
let rng = SystemRandom::new(); let rng = SystemRandom::new();
let mut node_id = [0; NODE_ID_BYTES]; let mut node_id = [0; NODE_ID_BYTES];
rng.fill(&mut node_id).unwrap(); rng.fill(&mut node_id).unwrap();
@ -445,23 +334,28 @@ mod tests {
let mut node2 = create_node(&config); let mut node2 = create_node(&config);
let mut msg = MsgBuffer::new(16); let mut msg = MsgBuffer::new(16);
node1.initialize(&mut msg).unwrap(); node1.send_ping(&mut msg);
assert!(!msg.is_empty()); assert!(!msg.is_empty());
debug!("Node1 -> Node2"); debug!("Node1 -> Node2");
let res = node2.handle_message(&mut msg).unwrap(); let res = node2.handle_init(&mut msg).unwrap();
assert_eq!(res, MessageResult::Reply); assert_eq!(res, InitResult::Continue);
assert!(!msg.is_empty()); assert!(!msg.is_empty());
debug!("Node1 <- Node2"); debug!("Node1 <- Node2");
let res = node1.handle_message(&mut msg).unwrap(); let res = node1.handle_init(&mut msg).unwrap();
assert_eq!(res, MessageResult::InitializedWithReply(vec![])); assert_eq!(res, InitResult::Success { peer_payload: vec![], is_initiator: false });
assert!(!msg.is_empty()); assert!(!msg.is_empty());
debug!("Node1 -> Node2"); debug!("Node1 -> Node2");
let res = node2.handle_message(&mut msg).unwrap(); let res = node2.handle_init(&mut msg).unwrap();
assert_eq!(res, MessageResult::InitializedWithReply(vec![])); assert_eq!(res, InitResult::Success { peer_payload: vec![], is_initiator: true });
assert!(!msg.is_empty()); assert!(msg.is_empty());
let node1 = node1.finish(&mut msg);
assert!(msg.is_empty());
let node2 = node2.finish(&mut msg);
assert!(msg.is_empty());
debug!("Node1 <- Node2"); debug!("Node1 <- Node2");
let res = node1.handle_message(&mut msg).unwrap(); let res = node1.handle_message(&mut msg).unwrap();
@ -473,11 +367,11 @@ mod tests {
buffer.set_length(1000); buffer.set_length(1000);
rng.fill(buffer.message_mut()).unwrap(); rng.fill(buffer.message_mut()).unwrap();
for _ in 0..1000 { for _ in 0..1000 {
node1.send_message(1, &mut buffer).unwrap(); node1.send_message(1, &mut buffer);
let res = node2.handle_message(&mut buffer).unwrap(); let res = node2.handle_message(&mut buffer).unwrap();
assert_eq!(res, MessageResult::Message(1)); assert_eq!(res, MessageResult::Message(1));
match node1.every_second(&mut msg).unwrap() { match node1.every_second(&mut msg) {
MessageResult::None => (), MessageResult::None => (),
MessageResult::Reply => { MessageResult::Reply => {
let res = node2.handle_message(&mut msg).unwrap(); let res = node2.handle_message(&mut msg).unwrap();
@ -485,7 +379,7 @@ mod tests {
} }
other => assert_eq!(other, MessageResult::None) other => assert_eq!(other, MessageResult::None)
} }
match node2.every_second(&mut msg).unwrap() { match node2.every_second(&mut msg) {
MessageResult::None => (), MessageResult::None => (),
MessageResult::Reply => { MessageResult::Reply => {
let res = node1.handle_message(&mut msg).unwrap(); let res = node1.handle_message(&mut msg).unwrap();

View File

@ -58,8 +58,8 @@
use super::{ use super::{
core::{CryptoCore, EXTRA_LEN}, core::{CryptoCore, EXTRA_LEN},
rotate::RotationState, rotate::RotationState,
Algorithms, EcdhPrivateKey, EcdhPublicKey, Ed25519PublicKey, Error, MsgBuffer, Payload, PeerCrypto, Algorithms, EcdhPrivateKey, EcdhPublicKey, Ed25519PublicKey, Payload, PeerCrypto,
MESSAGE_TYPE_ROTATION common::MESSAGE_TYPE_ROTATION
}; };
use crate::{error::Error, types::NodeId, util::MsgBuffer}; use crate::{error::Error, types::NodeId, util::MsgBuffer};
use byteorder::{NetworkEndian, ReadBytesExt, WriteBytesExt}; use byteorder::{NetworkEndian, ReadBytesExt, WriteBytesExt};
@ -679,16 +679,22 @@ impl<P: Payload> InitState<P> {
pub fn finish(self, buffer: &mut MsgBuffer) -> PeerCrypto { pub fn finish(self, buffer: &mut MsgBuffer) -> PeerCrypto {
assert!(buffer.is_empty()); assert!(buffer.is_empty());
let rotation = if self.crypto.is_some() { Some(RotationState::new(!self.is_initiator, buffer)) } else { None }; if let Some(crypto) = self.crypto {
if !buffer.is_empty() { let rotation = RotationState::new(!self.is_initiator, buffer);
buffer.prepend_byte(MESSAGE_TYPE_ROTATION); if !buffer.is_empty() {
} buffer.prepend_byte(MESSAGE_TYPE_ROTATION);
PeerCrypto { }
algorithm: self.crypto.map(|c| c.algorithm()), PeerCrypto::Encrypted {
core: self.crypto, algorithm: crypto.algorithm(),
rotation, core: crypto,
rotate_counter: 0, rotation,
last_init_message: self.last_message rotate_counter: 0,
last_init_message: self.last_message.unwrap()
}
} else {
PeerCrypto::Unencrypted {
last_init_message: self.last_message.unwrap()
}
} }
} }
} }

View File

@ -80,7 +80,7 @@ pub struct GenericCloud<D: Device, P: Protocol, S: Socket, TS: TimeSource> {
peers: HashMap<SocketAddr, PeerData, Hash>, peers: HashMap<SocketAddr, PeerData, Hash>,
reconnect_peers: SmallVec<[ReconnectEntry; 3]>, reconnect_peers: SmallVec<[ReconnectEntry; 3]>,
own_addresses: AddrList, own_addresses: AddrList,
pending_inits: HashMap<SocketAddr, PeerCrypto<NodeInfo>, Hash>, pending_inits: HashMap<SocketAddr, InitState<NodeInfo>, Hash>,
table: ClaimTable<TS>, table: ClaimTable<TS>,
socket: S, socket: S,
device: D, device: D,

View File

@ -30,7 +30,7 @@ impl SharedPeerCrypto {
} }
} }
pub fn for_each(&mut self, mut callback: impl FnMut(SocketAddr, &mut PeerCrypto<NodeInfo>) -> Result<(), Error>) -> Result<(), Error> { pub fn for_each(&mut self, mut callback: impl FnMut(SocketAddr, &mut CryptoCore) -> Result<(), Error>) -> Result<(), Error> {
let mut peers = self.peers.lock(); let mut peers = self.peers.lock();
for (k, v) in peers.iter_mut() { for (k, v) in peers.iter_mut() {
callback(*k, v)? callback(*k, v)?

View File

@ -13,9 +13,9 @@ use std::{
}; };
pub use crate::{ pub use crate::{
cloud::GenericCloud,
config::{Config, CryptoConfig}, config::{Config, CryptoConfig},
device::{MockDevice, Type}, device::{MockDevice, Type},
engine::GenericCloud,
net::MockSocket, net::MockSocket,
payload::{Frame, Packet, Protocol}, payload::{Frame, Packet, Protocol},
types::Range, types::Range,
@ -44,8 +44,8 @@ impl DebugLogger {
impl log::Log for DebugLogger { impl log::Log for DebugLogger {
#[inline] #[inline]
fn enabled(&self, metadata: &log::Metadata) -> bool { fn enabled(&self, _metadata: &log::Metadata) -> bool {
log::max_level() > metadata.level() true
} }
#[inline] #[inline]
@ -79,7 +79,7 @@ impl<P: Protocol> Simulator<P> {
pub fn new() -> Self { pub fn new() -> Self {
init_debug_logger(); init_debug_logger();
MockTimeSource::set_time(0); MockTimeSource::set_time(0);
Self { next_port: 1, nodes: HashMap::default(), messages: VecDeque::with_capacity(10) } Self { next_port: 1, nodes: HashMap::default(), messages: VecDeque::default() }
} }
pub fn add_node(&mut self, nat: bool, config: &Config) -> SocketAddr { pub fn add_node(&mut self, nat: bool, config: &Config) -> SocketAddr {