Avoid recreating the AES key

This commit is contained in:
QuantumEntangledAndy committed 2024-04-11 09:33:50 +07:00
1 parent 8f8d9e6f78
commit 7f8ccc6806
7 files changed
+137 -100

No files matched your search

+8 -7
View File
@@ -33,18 +33,19 @@ impl Encoder<Bc> 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<u8> = 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),
)),
_ => {
+122
View File
@@ -0,0 +1,122 @@
use aes::{
cipher::{AsyncStreamCipher, KeyIvInit},
Aes128,
};
use cfb_mode::{Decryptor, Encryptor};
type Aes128CfbEnc = Encryptor<Aes128>;
type Aes128CfbDec = Decryptor<Aes128>;
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<u8> {
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<u8> {
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[..]);
}
+2 -3
View File
@@ -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)) => {
+2 -1
View File
@@ -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;
+1 -17
View File
@@ -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<u32>,
}
/// 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,
+2 -3
View File
@@ -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<W: Write>(
encryption_protocol: &EncryptionProtocol,
) -> impl SerializeFn<W> {
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<W: Write>(
// "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(),
};
-69
View File
@@ -1,69 +0,0 @@
use super::model::EncryptionProtocol;
use aes::{
cipher::{AsyncStreamCipher, KeyIvInit},
Aes128,
};
use cfb_mode::{Decryptor, Encryptor};
type Aes128CfbEnc = Encryptor<Aes128>;
type Aes128CfbDec = Decryptor<Aes128>;
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<u8> {
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<u8> {
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[..]);
}