From 7f8ccc680660e520ca8a8726cc717f9ea5526e40 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Thu, 11 Apr 2024 09:33:50 +0700 Subject: [PATCH] Avoid recreating the AES key --- crates/core/src/bc/codex.rs | 15 ++-- crates/core/src/bc/crypto.rs | 122 +++++++++++++++++++++++++++++++ crates/core/src/bc/de.rs | 5 +- crates/core/src/bc/mod.rs | 3 +- crates/core/src/bc/model.rs | 18 +---- crates/core/src/bc/ser.rs | 5 +- crates/core/src/bc/xml_crypto.rs | 69 ----------------- 7 files changed, 137 insertions(+), 100 deletions(-) create mode 100644 crates/core/src/bc/crypto.rs delete mode 100644 crates/core/src/bc/xml_crypto.rs diff --git a/crates/core/src/bc/codex.rs b/crates/core/src/bc/codex.rs index c74e524..6c24266 100644 --- a/crates/core/src/bc/codex.rs +++ b/crates/core/src/bc/codex.rs @@ -33,18 +33,19 @@ impl Encoder for BcCodex { fn encode(&mut self, item: Bc, dst: &mut BytesMut) -> Result<()> { // let context = self.context.read().unwrap(); + const BC_ENCRYPTED: EncryptionProtocol = EncryptionProtocol::BCEncrypt; let buf: Vec = Default::default(); - let enc_protocol: EncryptionProtocol = match self.context.get_encrypted() { - EncryptionProtocol::Aes(_) | EncryptionProtocol::FullAes(_) + let enc_protocol: &EncryptionProtocol = match self.context.get_encrypted() { + EncryptionProtocol::Aes { .. } | EncryptionProtocol::FullAes { .. } if item.meta.msg_id == 1 => { // During login the encyption protocol cannot go higher than BCEncrypt // even if we support AES. (BUt it can go lower i.e. None) - EncryptionProtocol::BCEncrypt + &BC_ENCRYPTED } - n => *n, + n => n, }; - let buf = item.serialize(buf, &enc_protocol)?; + let buf = item.serialize(buf, enc_protocol)?; dst.extend_from_slice(buf.as_slice()); Ok(()) } @@ -117,10 +118,10 @@ impl Decoder for BcCodex { match encryption_protocol_byte { 0x00 => self.context.set_encrypted(EncryptionProtocol::Unencrypted), 0x01 => self.context.set_encrypted(EncryptionProtocol::BCEncrypt), - 0x02 => self.context.set_encrypted(EncryptionProtocol::Aes( + 0x02 => self.context.set_encrypted(EncryptionProtocol::aes( self.context.credentials.make_aeskey(nonce), )), - 0x12 => self.context.set_encrypted(EncryptionProtocol::FullAes( + 0x12 => self.context.set_encrypted(EncryptionProtocol::full_aes( self.context.credentials.make_aeskey(nonce), )), _ => { diff --git a/crates/core/src/bc/crypto.rs b/crates/core/src/bc/crypto.rs new file mode 100644 index 0000000..4ae05ad --- /dev/null +++ b/crates/core/src/bc/crypto.rs @@ -0,0 +1,122 @@ +use aes::{ + cipher::{AsyncStreamCipher, KeyIvInit}, + Aes128, +}; +use cfb_mode::{Decryptor, Encryptor}; + +type Aes128CfbEnc = Encryptor; +type Aes128CfbDec = Decryptor; + +const XML_KEY: [u8; 8] = [0x1F, 0x2D, 0x3C, 0x4B, 0x5A, 0x69, 0x78, 0xFF]; +const IV: &[u8] = b"0123456789abcdef"; + +/// These are the encyption modes supported by the camera +/// +/// The mode is negotiated during login +#[derive(Debug, Clone)] +pub enum EncryptionProtocol { + /// Older camera use no encryption + Unencrypted, + /// Camera/Firmwares before 2021 use BCEncrypt which is a simple XOr + BCEncrypt, + /// Latest cameras/firmwares use Aes with the key derived from + /// the camera's password and the negotiated NONCE + Aes { + /// The encryptor + enc: Aes128CfbEnc, + /// The decryptor + dec: Aes128CfbDec, + }, + /// Same as Aes but the media stream is also encrypted and not just + /// the control commands + FullAes { + /// The encryptor + enc: Aes128CfbEnc, + /// The decryptor + dec: Aes128CfbDec, + }, +} + +impl EncryptionProtocol { + /// Helper to make unencrypted + pub fn unencrypted() -> Self { + EncryptionProtocol::Unencrypted + } + /// Helper to make bcencrypted + pub fn bcencrypt() -> Self { + EncryptionProtocol::BCEncrypt + } + /// Helper to make aes + pub fn aes(key: [u8; 16]) -> Self { + EncryptionProtocol::Aes { + enc: Aes128CfbEnc::new(key.as_slice().into(), IV.into()), + dec: Aes128CfbDec::new(key.as_slice().into(), IV.into()), + } + } + /// Helper to make full aes + pub fn full_aes(key: [u8; 16]) -> Self { + EncryptionProtocol::FullAes { + enc: Aes128CfbEnc::new(key.as_slice().into(), IV.into()), + dec: Aes128CfbDec::new(key.as_slice().into(), IV.into()), + } + } + + /// Decrypt the data, offset comes from the header of the packet + pub fn decrypt(&self, offset: u32, buf: &[u8]) -> Vec { + match self { + EncryptionProtocol::Unencrypted => buf.to_vec(), + EncryptionProtocol::BCEncrypt => { + let key_iter = XML_KEY.iter().cycle().skip(offset as usize % 8); + key_iter + .zip(buf) + .map(|(key, i)| *i ^ key ^ (offset as u8)) + .collect() + } + EncryptionProtocol::Aes { dec, .. } | EncryptionProtocol::FullAes { dec, .. } => { + // AES decryption + + let mut decrypted = buf.to_vec(); + dec.clone().decrypt(&mut decrypted); + decrypted + } + } + } + + /// Encrypt the data, offset comes from the header of the packet + pub fn encrypt(&self, offset: u32, buf: &[u8]) -> Vec { + match self { + EncryptionProtocol::Unencrypted => { + // Encrypt is the same as decrypt + self.decrypt(offset, buf) + } + EncryptionProtocol::BCEncrypt => { + // Encrypt is the same as decrypt + self.decrypt(offset, buf) + } + EncryptionProtocol::Aes { enc, .. } | EncryptionProtocol::FullAes { enc, .. } => { + // AES encryption + let mut encrypted = buf.to_vec(); + enc.clone().encrypt(&mut encrypted); + encrypted + } + } + } +} + +#[test] +fn test_xml_crypto() { + let sample = include_bytes!("samples/xml_crypto_sample1.bin"); + let should_be = include_bytes!("samples/xml_crypto_sample1_plaintext.bin"); + + let decrypted = EncryptionProtocol::BCEncrypt.decrypt(0, &sample[..]); + assert_eq!(decrypted, &should_be[..]); +} + +#[test] +fn test_xml_crypto_roundtrip() { + let zeros: [u8; 256] = [0; 256]; + + let decrypted = EncryptionProtocol::BCEncrypt.encrypt(0, &zeros[..]); + let encrypted = EncryptionProtocol::BCEncrypt.decrypt(0, &decrypted[..]); + assert_eq!(encrypted, &zeros[..]); +} diff --git a/crates/core/src/bc/de.rs b/crates/core/src/bc/de.rs index 7dc3736..fe72307 100644 --- a/crates/core/src/bc/de.rs +++ b/crates/core/src/bc/de.rs @@ -1,5 +1,4 @@ use super::model::*; -use super::xml_crypto; use crate::Error; use bytes::{Buf, BytesMut}; use log::*; @@ -104,7 +103,7 @@ fn bc_modern_msg<'a>( let processed_ext_buf = match context.get_encrypted() { EncryptionProtocol::Unencrypted => ext_buf, encryption_protocol => { - decrypted = xml_crypto::decrypt(header.channel_id as u32, ext_buf, encryption_protocol); + decrypted = encryption_protocol.decrypt(header.channel_id as u32, ext_buf); &decrypted } }; @@ -179,7 +178,7 @@ fn bc_modern_msg<'a>( }; let processed_payload_buf = - xml_crypto::decrypt(header.channel_id as u32, payload_buf, encryption_protocol); + encryption_protocol.decrypt(header.channel_id as u32, payload_buf); if context.in_bin_mode.contains(&(header.msg_num)) || in_binary { payload = match (context.get_encrypted(), encrypted_len) { (EncryptionProtocol::FullAes { .. }, Some(encrypted_len)) => { diff --git a/crates/core/src/bc/mod.rs b/crates/core/src/bc/mod.rs index 01b797c..61dff92 100644 --- a/crates/core/src/bc/mod.rs +++ b/crates/core/src/bc/mod.rs @@ -38,6 +38,7 @@ pub mod ser; /// Contains the structs for the know xmls of payloads and extension pub mod xml; -mod xml_crypto; +/// Contains the encryption protocols +pub mod crypto; pub(crate) mod codex; diff --git a/crates/core/src/bc/model.rs b/crates/core/src/bc/model.rs index 8ddbd87..f377161 100644 --- a/crates/core/src/bc/model.rs +++ b/crates/core/src/bc/model.rs @@ -1,5 +1,6 @@ use crate::Credentials; +pub use super::crypto::EncryptionProtocol; pub use super::xml::{BcPayloads, BcXml, Extension}; use std::collections::HashSet; @@ -210,23 +211,6 @@ pub(super) struct BcSendInfo { pub payload_offset: Option, } -/// These are the encyption modes supported by the camera -/// -/// The mode is negotiated during login -#[derive(Debug, Clone, Copy)] -pub enum EncryptionProtocol { - /// Older camera use no encryption - Unencrypted, - /// Camera/Firmwares before 2021 use BCEncrypt which is a simple XOr - BCEncrypt, - /// Latest cameras/firmwares use Aes with the key derived from - /// the camera's password and the negotiated NONCE - Aes([u8; 16]), - /// Same as Aes but the media stream is also encrypted and not just - /// the control commands - FullAes([u8; 16]), -} - #[derive(Debug)] pub(crate) struct BcContext { pub(crate) credentials: Credentials, diff --git a/crates/core/src/bc/ser.rs b/crates/core/src/bc/ser.rs index 56c99db..14aa5f3 100644 --- a/crates/core/src/bc/ser.rs +++ b/crates/core/src/bc/ser.rs @@ -1,5 +1,4 @@ use super::model::*; -use super::xml_crypto; use cookie_factory::bytes::*; use cookie_factory::sequence::tuple; use cookie_factory::{combinator::*, gen}; @@ -79,7 +78,7 @@ fn bc_ext( encryption_protocol: &EncryptionProtocol, ) -> impl SerializeFn { let xml_bytes = xml.serialize(vec![]).unwrap(); - let enc_bytes = xml_crypto::encrypt(enc_offset, &xml_bytes, encryption_protocol); + let enc_bytes = encryption_protocol.encrypt(enc_offset, &xml_bytes); slice(enc_bytes) } @@ -95,7 +94,7 @@ fn bc_payload( // "Seialised as: {:?}", // std::str::from_utf8(xml_bytes.as_ref()) // ); - xml_crypto::encrypt(enc_offset, &xml_bytes, encryption_protocol) + encryption_protocol.encrypt(enc_offset, &xml_bytes) } BcPayloads::Binary(x) => x.to_owned(), }; diff --git a/crates/core/src/bc/xml_crypto.rs b/crates/core/src/bc/xml_crypto.rs deleted file mode 100644 index bf0f086..0000000 --- a/crates/core/src/bc/xml_crypto.rs +++ /dev/null @@ -1,69 +0,0 @@ -use super::model::EncryptionProtocol; -use aes::{ - cipher::{AsyncStreamCipher, KeyIvInit}, - Aes128, -}; -use cfb_mode::{Decryptor, Encryptor}; - -type Aes128CfbEnc = Encryptor; -type Aes128CfbDec = Decryptor; - -const XML_KEY: [u8; 8] = [0x1F, 0x2D, 0x3C, 0x4B, 0x5A, 0x69, 0x78, 0xFF]; -const IV: &[u8] = b"0123456789abcdef"; - -pub fn decrypt(offset: u32, buf: &[u8], encryption_protocol: &EncryptionProtocol) -> Vec { - match encryption_protocol { - EncryptionProtocol::Unencrypted => buf.to_vec(), - EncryptionProtocol::BCEncrypt => { - let key_iter = XML_KEY.iter().cycle().skip(offset as usize % 8); - key_iter - .zip(buf) - .map(|(key, i)| *i ^ key ^ (offset as u8)) - .collect() - } - EncryptionProtocol::Aes(aeskey) | EncryptionProtocol::FullAes(aeskey) => { - // AES decryption - - let mut decrypted = buf.to_vec(); - Aes128CfbDec::new(aeskey.into(), IV.into()).decrypt(&mut decrypted); - decrypted - } - } -} - -pub fn encrypt(offset: u32, buf: &[u8], encryption_protocol: &EncryptionProtocol) -> Vec { - match encryption_protocol { - EncryptionProtocol::Unencrypted => { - // Encrypt is the same as decrypt - decrypt(offset, buf, encryption_protocol) - } - EncryptionProtocol::BCEncrypt => { - // Encrypt is the same as decrypt - decrypt(offset, buf, encryption_protocol) - } - EncryptionProtocol::Aes(aeskey) | EncryptionProtocol::FullAes(aeskey) => { - // AES encryption - let mut encrypted = buf.to_vec(); - Aes128CfbEnc::new(aeskey.into(), IV.into()).encrypt(&mut encrypted); - encrypted - } - } -} - -#[test] -fn test_xml_crypto() { - let sample = include_bytes!("samples/xml_crypto_sample1.bin"); - let should_be = include_bytes!("samples/xml_crypto_sample1_plaintext.bin"); - - let decrypted = decrypt(0, &sample[..], &EncryptionProtocol::BCEncrypt); - assert_eq!(decrypted, &should_be[..]); -} - -#[test] -fn test_xml_crypto_roundtrip() { - let zeros: [u8; 256] = [0; 256]; - - let decrypted = encrypt(0, &zeros[..], &EncryptionProtocol::BCEncrypt); - let encrypted = decrypt(0, &decrypted[..], &EncryptionProtocol::BCEncrypt); - assert_eq!(encrypted, &zeros[..]); -}