From 772ba86156533910879bce2b3798f53728790c6b Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Wed, 14 Apr 2021 17:17:43 +0700 Subject: [PATCH] Bug fix and preperation for new encryption protocol --- Cargo.lock | 12 +++++++++ Cargo.toml | 1 + src/bc/de.rs | 37 ++++++++++++++++---------- src/bc/model.rs | 38 +++++++++++++++++++++----- src/bc/ser.rs | 50 ++++++++++++++++++++++------------- src/bc/xml_crypto.rs | 28 +++++++++++++++----- src/bc_protocol.rs | 13 +++------ src/bc_protocol/connection.rs | 33 ++++++++++++++--------- src/gst.rs | 6 +---- 9 files changed, 145 insertions(+), 73 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 298e758..64d5001 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -30,6 +30,17 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cff77d8686867eceff3105329d4698d96c2391c176d5d03adc90c7389162b5b8" +[[package]] +name = "atomic_enum" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a57588a20357c74ee9036656b7fad5c54328ee8657c6ff29ba31fd5ea503a1c" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "atty" version = "0.2.14" @@ -777,6 +788,7 @@ checksum = "0419348c027fa7be448d2ae7ea0e4e04c2334c31dc4e74ab29f00a2a7ca69204" name = "neolink" version = "0.3.0" dependencies = [ + "atomic_enum", "cookie-factory", "crossbeam", "env_logger", diff --git a/Cargo.toml b/Cargo.toml index dde0a86..a9acc5f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -35,3 +35,4 @@ yaserde_derive = "0.3.16" xml-rs = "0.8" validator = "0.10" validator_derive = "0.10" +atomic_enum = "0.1.1" diff --git a/src/bc/de.rs b/src/bc/de.rs index c2c7ea5..a6e5240 100644 --- a/src/bc/de.rs +++ b/src/bc/de.rs @@ -99,7 +99,7 @@ fn hex32<'a>() -> impl Fn(&'a [u8]) -> IResult<&'a [u8], String> { }) } -fn bc_legacy_login_msg<'a>(buf: &'a [u8]) -> IResult<&'a [u8], LegacyMsg> { +fn bc_legacy_login_msg(buf: &'_ [u8]) -> IResult<&'_ [u8], LegacyMsg> { let (buf, username) = hex32()(buf)?; let (buf, password) = hex32()(buf)?; @@ -121,16 +121,29 @@ fn bc_modern_msg<'a, 'b>( _ => 0, // If missing payload_offset treat all as payload }; + if header.msg_id == 1 && (header.response_code >> 8) == 0xdd { + // Login reply has the encryption info + // Set that the encryption type now + let encryption_protocol_byte = (header.response_code & 0xff) as usize; + match encryption_protocol_byte { + 0x00 => context.set_encrypted(EncryptionProtocol::Unencrypted), + 0x01 => context.set_encrypted(EncryptionProtocol::VersionOne), + 0x03 => context.set_encrypted(EncryptionProtocol::VersionThree), + _ => context.set_encrypted(EncryptionProtocol::Unknown), + } + } + let (buf, ext_buf) = take(ext_len)(buf)?; let payload_len = header.body_len - ext_len; let (buf, payload_buf) = take(payload_len)(buf)?; let decrypted; - let processed_ext_buf = if !context.get_encrypted() { - ext_buf - } else { - decrypted = xml_crypto::crypt(header.channel_id as u32, ext_buf); - &decrypted + let processed_ext_buf = match context.get_encrypted() { + EncryptionProtocol::Unencrypted => ext_buf, + encryption_protocol => { + decrypted = xml_crypto::crypt(header.channel_id as u32, ext_buf, encryption_protocol); + &decrypted + } }; // Now we'll take the buffer that Nom gave a ref to and parse it. @@ -152,14 +165,10 @@ fn bc_modern_msg<'a, 'b>( let payload; if payload_len > 0 { // Extract remainder of message as binary, if it exists - let decrypted; - let processed_payload_buf = if !context.get_encrypted() { - payload_buf - } else { - decrypted = xml_crypto::crypt(header.channel_id as u32, payload_buf); - &decrypted - }; - if let Ok(xml) = BcXml::try_parse(processed_payload_buf) { + let encryption_protocol = context.get_encrypted(); + let processed_payload_buf = + xml_crypto::crypt(header.channel_id as u32, payload_buf, encryption_protocol); + if let Ok(xml) = BcXml::try_parse(processed_payload_buf.as_slice()) { payload = Some(BcPayloads::BcXml(xml)); } else { payload = Some(BcPayloads::Binary(payload_buf.to_vec())); diff --git a/src/bc/model.rs b/src/bc/model.rs index 05d12fb..ae507ae 100644 --- a/src/bc/model.rs +++ b/src/bc/model.rs @@ -1,6 +1,7 @@ pub use super::xml::{BcPayloads, BcXml, Extension}; +use atomic_enum::atomic_enum; use std::collections::HashSet; -use std::sync::{Arc, atomic::{AtomicBool, Ordering}}; +use std::sync::{atomic::Ordering, Arc}; pub(super) const MAGIC_HEADER: u32 = 0xabcdef0; @@ -70,10 +71,21 @@ pub(super) struct BcSendInfo { pub payload_offset: Option, } +#[atomic_enum] +#[derive(PartialEq)] +pub enum EncryptionProtocol { + Unencrypted = 0, + VersionOne, + VersionThree, + Unknown, +} + #[derive(Debug)] pub struct BcContext { pub(super) in_bin_mode: HashSet, - pub(super) is_encrypted: Arc, + // Arc because it is shared between context + // and connection for deserialisation and serialistion respectivly + pub(super) encryption_protocol: Arc, } impl Bc { @@ -130,16 +142,28 @@ impl BcContext { pub fn new() -> BcContext { BcContext { in_bin_mode: HashSet::new(), - is_encrypted: Default::default(), + encryption_protocol: Arc::new(AtomicEncryptionProtocol::new( + EncryptionProtocol::Unencrypted, + )), } } - pub fn set_encrypted(&mut self, is_encrypted: Arc) { - self.is_encrypted = is_encrypted; + pub fn new_with_encryption_protocol( + encryption_protocol: Arc, + ) -> BcContext { + BcContext { + in_bin_mode: HashSet::new(), + encryption_protocol, + } } - pub fn get_encrypted(&self) -> bool { - self.is_encrypted.load(Ordering::Relaxed) + pub fn set_encrypted(&mut self, encryption_protocol: EncryptionProtocol) { + self.encryption_protocol + .store(encryption_protocol, Ordering::Relaxed); + } + + pub fn get_encrypted(&self) -> EncryptionProtocol { + self.encryption_protocol.load(Ordering::Relaxed) } } diff --git a/src/bc/ser.rs b/src/bc/ser.rs index 3b6df92..7bc13a9 100644 --- a/src/bc/ser.rs +++ b/src/bc/ser.rs @@ -5,12 +5,17 @@ use cookie_factory::bytes::*; use cookie_factory::sequence::tuple; use cookie_factory::{combinator::*, gen}; use cookie_factory::{GenError, SerializeFn, WriteContext}; +use log::error; use std::io::Write; pub type Error = GenError; impl Bc { - pub fn serialize(&self, buf: W, encrypted: bool) -> Result { + pub fn serialize( + &self, + buf: W, + encryption_protocol: EncryptionProtocol, + ) -> Result { // Ideally this would be a combinator, but that would be hairy because we have to // serialize the XML to have the metadata to build the header let body_buf; @@ -20,7 +25,9 @@ impl Bc { BcBody::ModernMsg(ref modern) => { // First serialize ext let (temp_buf, ext_len) = gen( - opt_ref(&modern.extension, |ext| bc_ext(self.meta.channel_id as u32, ext, encrypted)), + opt_ref(&modern.extension, |ext| { + bc_ext(self.meta.channel_id as u32, ext, encryption_protocol) + }), vec![], )?; @@ -39,7 +46,11 @@ impl Bc { // Now get the payload part of the body and add to ext_buf let (temp_buf, _) = gen( opt_ref(&modern.payload, |payload_offset| { - bc_payload(self.meta.channel_id as u32, payload_offset, encrypted) + bc_payload( + self.meta.channel_id as u32, + payload_offset, + encryption_protocol, + ) }), temp_buf, )?; @@ -47,7 +58,10 @@ impl Bc { } BcBody::LegacyMsg(ref legacy) => { - let (buf, _) = gen(bc_legacy(legacy), vec![])?; + let (buf, _) = gen(bc_legacy(legacy), vec![]).map_err(|e| { + error!("Send error: {}", e); + e + })?; body_buf = buf; payload_offset = None; } @@ -62,25 +76,25 @@ impl Bc { } } -fn bc_ext(enc_offset: u32, xml: &Extension, encrypted: bool) -> impl SerializeFn { +fn bc_ext( + enc_offset: u32, + xml: &Extension, + encryption_protocol: EncryptionProtocol, +) -> impl SerializeFn { let xml_bytes = xml.serialize(vec![]).unwrap(); - if encrypted { - let enc_bytes = xml_crypto::crypt(enc_offset, &xml_bytes); - slice(enc_bytes) - } else { - slice(xml_bytes) - } + let enc_bytes = xml_crypto::crypt(enc_offset, &xml_bytes, encryption_protocol); + slice(enc_bytes) } -fn bc_payload(enc_offset: u32, payload: &BcPayloads, encrypted: bool) -> impl SerializeFn { +fn bc_payload( + enc_offset: u32, + payload: &BcPayloads, + encryption_protocol: EncryptionProtocol, +) -> impl SerializeFn { let payload_bytes = match payload { BcPayloads::BcXml(x) => { let xml_bytes = x.serialize(vec![]).unwrap(); - if encrypted { - xml_crypto::crypt(enc_offset, &xml_bytes) - } else { - xml_bytes - } + xml_crypto::crypt(enc_offset, &xml_bytes, encryption_protocol) } BcPayloads::Binary(x) => x.to_owned(), }; @@ -110,7 +124,7 @@ fn bc_header(header: &BcHeader) -> impl SerializeFn { )) } -fn bc_legacy<'a, W: Write>(legacy: &'a LegacyMsg) -> impl SerializeFn + 'a { +fn bc_legacy(legacy: &'_ LegacyMsg) -> impl SerializeFn + '_ { move |out: WriteContext| { use LegacyMsg::*; match legacy { diff --git a/src/bc/xml_crypto.rs b/src/bc/xml_crypto.rs index edfcfe0..efc0c69 100644 --- a/src/bc/xml_crypto.rs +++ b/src/bc/xml_crypto.rs @@ -1,11 +1,27 @@ +use super::model::EncryptionProtocol; +use log::error; + const XML_KEY: [u8; 8] = [0x1F, 0x2D, 0x3C, 0x4B, 0x5A, 0x69, 0x78, 0xFF]; -pub fn crypt(offset: u32, buf: &[u8]) -> Vec { - 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() +pub fn crypt(offset: u32, buf: &[u8], encryption_protocol: EncryptionProtocol) -> Vec { + match encryption_protocol { + EncryptionProtocol::Unencrypted => buf.to_vec(), + EncryptionProtocol::VersionOne => { + 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::VersionThree => { + // New protocol here + unimplemented!(); + } + _ => { + error!("Unknown encryption protocol"); + unimplemented!(); + } + } } #[test] diff --git a/src/bc_protocol.rs b/src/bc_protocol.rs index 9309a2b..09159a9 100644 --- a/src/bc_protocol.rs +++ b/src/bc_protocol.rs @@ -8,8 +8,8 @@ use err_derive::Error; use log::*; use std::io::Write; use std::net::{SocketAddr, ToSocketAddrs}; -use std::time::Duration; use std::sync::atomic::{AtomicU16, Ordering}; +use std::time::Duration; use Md5Trunc::*; @@ -23,7 +23,7 @@ pub struct BcCamera { channel_id: u8, connection: Option, logged_in: bool, - message_num: AtomicU16 + message_num: AtomicU16, } use crate::Never; @@ -157,9 +157,6 @@ impl BcCamera { let legacy_reply = sub_login.rx.recv_timeout(RX_TIMEOUT)?; let nonce; - if let BcMeta {response_code: 0x01dd,..} = legacy_reply.meta { - connection.set_encrypted(true); - } match legacy_reply.body { BcBody::ModernMsg(ModernMsg { payload: @@ -278,11 +275,7 @@ impl BcCamera { Ok(()) } - pub fn start_video( - &self, - data_outs: &mut GstOutputs, - stream_name: &str, - ) -> Result { + pub fn start_video(&self, data_outs: &mut GstOutputs, stream_name: &str) -> Result { let connection = self .connection .as_ref() diff --git a/src/bc_protocol/connection.rs b/src/bc_protocol/connection.rs index 6c8c127..2899b9a 100644 --- a/src/bc_protocol/connection.rs +++ b/src/bc_protocol/connection.rs @@ -1,14 +1,14 @@ use crate::bc; use crate::bc::model::*; -use std::error::Error as StdErr; // Just need the traits use err_derive::Error; use log::*; use socket2::{Domain, Socket, Type}; use std::collections::btree_map::Entry; use std::collections::BTreeMap; +use std::error::Error as StdErr; // Just need the traits use std::net::{Shutdown, SocketAddr, TcpStream}; use std::sync::mpsc::{channel, Receiver, Sender}; -use std::sync::{Arc, Mutex, atomic::{AtomicBool, Ordering}}; +use std::sync::{atomic::Ordering, Arc, Mutex}; use std::thread::JoinHandle; use std::time::Duration; @@ -21,7 +21,9 @@ pub struct BcConnection { connection: Arc>, subscribers: Arc>>>, rx_thread: Option>, - is_encrypted: Arc, + // Arc because it is shared between context + // and connection for deserialisation and serialistion respectivly + encryption_protocol: Arc, } pub struct BcSubscription<'a> { @@ -55,10 +57,13 @@ impl BcConnection { let mut subs = subscribers.clone(); let conn = tcp_conn.try_clone()?; - let is_encrypted = Arc::new(AtomicBool::new(false)); - let connections_isencrypted = is_encrypted.clone(); + let encryption_protocol = Arc::new(AtomicEncryptionProtocol::new( + EncryptionProtocol::Unencrypted, + )); + let connections_encryption_protocol = encryption_protocol.clone(); let rx_thread = std::thread::spawn(move || { - let mut context = BcContext::new(); + let mut context = + BcContext::new_with_encryption_protocol(connections_encryption_protocol); let mut result; while { result = BcConnection::poll(&mut context, &conn, &mut subs); @@ -70,7 +75,6 @@ impl BcConnection { while let Some(e) = cause { error!("caused by: {}", e); cause = e.source(); - } }); @@ -78,7 +82,7 @@ impl BcConnection { connection: Arc::new(Mutex::new(tcp_conn)), subscribers, rx_thread: Some(rx_thread), - is_encrypted, + encryption_protocol, }) } @@ -128,12 +132,12 @@ impl BcConnection { Ok(()) } - pub fn set_encrypted(&self, value: bool) { - self.is_encrypted.store(value, Ordering::Relaxed); + pub fn set_encrypted(&self, value: EncryptionProtocol) { + self.encryption_protocol.store(value, Ordering::Relaxed); } - pub fn get_encrypted(&self) -> bool { - self.is_encrypted.load(Ordering::Relaxed) + pub fn get_encrypted(&self) -> EncryptionProtocol { + self.encryption_protocol.load(Ordering::Relaxed) } } @@ -161,7 +165,10 @@ impl<'a> BcSubscription<'a> { pub fn send(&self, bc: Bc) -> Result<()> { assert!(bc.meta.msg_id == self.msg_id); - bc.serialize(&*self.conn.connection.lock().unwrap(), self.conn.get_encrypted())?; + bc.serialize( + &*self.conn.connection.lock().unwrap(), + self.conn.get_encrypted(), + )?; Ok(()) } } diff --git a/src/gst.rs b/src/gst.rs index 1b4cf4d..53fec3b 100644 --- a/src/gst.rs +++ b/src/gst.rs @@ -13,7 +13,6 @@ use gstreamer_rtsp_server::{ RTSP_PERM_MEDIA_FACTORY_ACCESS, RTSP_PERM_MEDIA_FACTORY_CONSTRUCT, RTSP_TOKEN_MEDIA_FACTORY_ROLE, }; -use itertools::Itertools; use log::*; use std::collections::HashSet; use std::fs; @@ -142,10 +141,7 @@ impl RtspServer { debug!( "Permitting {} to access {}", // This is hashmap or (iter) equivalent of join, it requres itertools - permitted_users - .iter() - .cloned() - .intersperse(", ") + itertools::Itertools::intersperse(permitted_users.iter().cloned(), ", ") .collect::(), paths.join(", ") );