diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml index 2728304..d6a782c 100644 --- a/crates/core/Cargo.toml +++ b/crates/core/Cargo.toml @@ -20,5 +20,6 @@ yaserde_derive = "0.3.16" xml-rs = "0.8" [dev-dependencies] +assert_matches = "1.5.0" env_logger = "*" indoc = "0.3" diff --git a/crates/core/src/bc/model.rs b/crates/core/src/bc/model.rs index 588e282..e4f1215 100644 --- a/crates/core/src/bc/model.rs +++ b/crates/core/src/bc/model.rs @@ -53,7 +53,7 @@ pub struct Bc { #[allow(clippy::large_enum_variant)] pub enum BcBody { /// Legacy is unsupported except for login where it is used - /// to negociate the initial login and upgrade to modern + /// to negotiate the initial login and upgrade to modern LegacyMsg(LegacyMsg), /// Modern is the current reolink protocol it is mostly /// xml based @@ -64,7 +64,7 @@ pub enum BcBody { /// /// The first payload is extension which describes the second payload. If the /// `payload_offset` is `0` then their is no `extension` (usually because it has -/// already been negociated in a previous message) and it is `None` +/// already been negotiated in a previous message) and it is `None` /// /// The second payload contains the actual data of interest and is all bytes after /// the `payload_offset` up to the `body_len`. If `payload_offset` @@ -153,7 +153,7 @@ pub(super) struct BcSendInfo { /// These are the encyption modes supported by the camera /// -/// The mode is negociated during login +/// The mode is negotiated during login #[derive(Debug, Clone)] pub enum EncryptionProtocol { /// Older camera use no encryption @@ -161,7 +161,7 @@ pub enum EncryptionProtocol { /// 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 negociated NONCE + /// the camera's password and the negotiated NONCE Aes(Option<[u8; 16]>), } diff --git a/crates/core/src/bc/xml.rs b/crates/core/src/bc/xml.rs index 1aea64a..2ce5a5c 100644 --- a/crates/core/src/bc/xml.rs +++ b/crates/core/src/bc/xml.rs @@ -95,7 +95,7 @@ pub struct Encryption { #[yaserde(rename = "type")] /// The hashing algorithm used. Only observed the value of "md5" pub type_: String, - /// The nonce used to negociate the login and to generate the AES key + /// The nonce used to negotiate the login and to generate the AES key pub nonce: String, } diff --git a/crates/core/src/bcmedia/de.rs b/crates/core/src/bcmedia/de.rs index 67de1f9..1fd7e1b 100644 --- a/crates/core/src/bcmedia/de.rs +++ b/crates/core/src/bcmedia/de.rs @@ -312,7 +312,7 @@ fn bcmedia_adpcm(buf: &[u8]) -> IResult<&[u8], BcMediaAdpcm> { #[cfg(test)] mod tests { use super::Error; - use crate::bc_protocol::filesub::FileSubscriber; + use crate::bc_protocol::FileSubscriber; use crate::bcmedia::model::*; use env_logger::Env; use log::*; diff --git a/crates/core/src/bcudp/crc.rs b/crates/core/src/bcudp/crc.rs new file mode 100644 index 0000000..150a0e7 --- /dev/null +++ b/crates/core/src/bcudp/crc.rs @@ -0,0 +1,79 @@ +const TABLE: [u32; 1024] = [ + 0x0, 0x0, 0x0, 0x0, 0x96, 0x30, 0x7, 0x77, 0x2C, 0x61, 0xE, 0xEE, 0xBA, 0x51, 0x9, 0x99, 0x19, + 0xC4, 0x6D, 0x7, 0x8F, 0xF4, 0x6A, 0x70, 0x35, 0xA5, 0x63, 0xE9, 0xA3, 0x95, 0x64, 0x9E, 0x32, + 0x88, 0xDB, 0xE, 0xA4, 0xB8, 0xDC, 0x79, 0x1E, 0xE9, 0xD5, 0xE0, 0x88, 0xD9, 0xD2, 0x97, 0x2B, + 0x4C, 0xB6, 0x9, 0xBD, 0x7C, 0xB1, 0x7E, 0x7, 0x2D, 0xB8, 0xE7, 0x91, 0x1D, 0xBF, 0x90, 0x64, + 0x10, 0xB7, 0x1D, 0xF2, 0x20, 0xB0, 0x6A, 0x48, 0x71, 0xB9, 0xF3, 0xDE, 0x41, 0xBE, 0x84, 0x7D, + 0xD4, 0xDA, 0x1A, 0xEB, 0xE4, 0xDD, 0x6D, 0x51, 0xB5, 0xD4, 0xF4, 0xC7, 0x85, 0xD3, 0x83, 0x56, + 0x98, 0x6C, 0x13, 0xC0, 0xA8, 0x6B, 0x64, 0x7A, 0xF9, 0x62, 0xFD, 0xEC, 0xC9, 0x65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3, 0x1B, 0xDF, 0x5, 0x5A, 0x8D, 0xEF, 0x02, 0x2D, +]; + +pub(crate) fn calc_crc(payload: &[u8]) -> u32 { + let mut r: u32 = 0; + for &val in payload.iter() { + let offset = (((val as u32 ^ r) & 0xFF) << 2) as usize; + let val: u32 = TABLE[offset + 3] << 24 + | TABLE[offset + 2] << 16 + | TABLE[offset + 1] << 8 + | TABLE[offset]; + r = val ^ (r >> 8); + } + r +} diff --git a/crates/core/src/bcudp/de.rs b/crates/core/src/bcudp/de.rs new file mode 100644 index 0000000..1b3d6e8 --- /dev/null +++ b/crates/core/src/bcudp/de.rs @@ -0,0 +1,339 @@ +use super::{crc::calc_crc, model::*, xml::*, xml_crypto::decrypt}; +use err_derive::Error; +use nom::IResult; +use nom::{ + combinator::*, + error::{make_error, ErrorKind}, + number::streaming::*, + take, take_str, Err, +}; +use std::io::Read; + +/// The error types used during deserialisation +#[derive(Debug, Error)] +pub enum Error { + /// A Nom parsing error usually a malformed packet + #[error(display = "Parsing error")] + NomError(String), + /// An IO error such as the stream being dropped + #[error(display = "I/O error")] + IoError(#[error(source)] std::io::Error), +} +type NomErrorType<'a> = nom::error::Error<&'a [u8]>; + +impl<'a> From>> for Error { + fn from(k: nom::Err>) -> Self { + let reason = match k { + nom::Err::Error(e) => format!("Nom Error: {:?}", e), + nom::Err::Failure(e) => format!("Nom Error: {:?}", e), + _ => "Unknown Nom error".to_string(), + }; + Error::NomError(reason) + } +} + +fn read_from_reader(mut parser: P, mut rdr: R) -> Result +where + R: Read, + E: for<'a> From>> + From, + P: FnMut(&[u8]) -> nom::IResult<&[u8], O>, +{ + let mut input: Vec = Vec::new(); + loop { + let to_read = match parser(&input) { + Ok((_, parsed)) => return Ok(parsed), + Err(nom::Err::Incomplete(needed)) => { + match needed { + nom::Needed::Unknown => std::num::NonZeroUsize::new(1).unwrap(), // read one byte + nom::Needed::Size(len) => len, + } + } + Err(e) => return Err(e.into()), + }; + + if 0 == (&mut rdr) + .take(to_read.get() as u64) + .read_to_end(&mut input)? + { + return Err(std::io::Error::new( + std::io::ErrorKind::UnexpectedEof, + "Read returned 0 bytes", + ) + .into()); + } + } +} + +impl BcUdp { + pub(crate) fn deserialize(r: R) -> Result { + // Throw away the nom-specific return types + read_from_reader(|reader| bcudp(reader), r) + } +} + +fn bcudp(buf: &[u8]) -> IResult<&[u8], BcUdp> { + let (buf, magic) = verify(le_u32, |x| { + matches!( + *x, + MAGIC_HEADER_UDP_NEGO | MAGIC_HEADER_UDP_ACK | MAGIC_HEADER_UDP_DATA + ) + })(buf)?; + + match magic { + MAGIC_HEADER_UDP_NEGO => { + let (buf, payload) = udp_disc(buf)?; + Ok((buf, BcUdp::Discovery(payload))) + } + MAGIC_HEADER_UDP_ACK => { + let (buf, payload) = udp_ack(buf)?; + Ok((buf, BcUdp::Ack(payload))) + } + MAGIC_HEADER_UDP_DATA => { + let (buf, payload) = udp_data(buf)?; + Ok((buf, BcUdp::Data(payload))) + } + _ => unreachable!(), + } +} + +fn udp_disc(buf: &[u8]) -> IResult<&[u8], UdpDiscovery> { + let (buf, payload_size) = le_u32(buf)?; + let (buf, _unknown_a) = verify(le_u32, |&x| x == 1)(buf)?; + let (buf, tid) = le_u32(buf)?; + let (buf, checksum) = le_u32(buf)?; + let (buf, enc_data_slice) = take!(buf, payload_size)?; + + let actual_checksum = calc_crc(enc_data_slice); + assert_eq!(checksum, actual_checksum); + + let decrypted_payload = decrypt(tid, enc_data_slice); + let payload = UdpXml::try_parse(decrypted_payload.as_slice()) + .map_err(|_| Err::Error(make_error(buf, ErrorKind::MapRes)))?; + + let data = UdpDiscovery { tid, payload }; + Ok((buf, data)) +} + +fn udp_ack(buf: &[u8]) -> IResult<&[u8], UdpAck> { + let (buf, connection_id) = le_u32(buf)?; + let (buf, _unknown_a) = verify(le_u32, |&x| x == 0)(buf)?; + let (buf, _unknown_b) = verify(le_u32, |&x| x == 0)(buf)?; + let (buf, packet_id) = le_u32(buf)?; + let (buf, _unknown_c) = le_u32(buf)?; + let (buf, _unknown_d) = verify(le_u32, |&x| x == 0)(buf)?; + + let data = UdpAck { + connection_id, + packet_id, + }; + Ok((buf, data)) +} + +fn udp_data(buf: &[u8]) -> IResult<&[u8], UdpData> { + let (buf, connection_id) = le_u32(buf)?; + let (buf, _unknown_a) = verify(le_u32, |&x| x == 0)(buf)?; + let (buf, packet_id) = le_u32(buf)?; + let (buf, payload_size) = le_u32(buf)?; + let (buf, payload) = take!(buf, payload_size)?; + + let data = UdpData { + connection_id, + packet_id, + payload: payload.to_vec(), + }; + Ok((buf, data)) +} + +#[cfg(test)] +mod tests { + use super::Error; + use crate::bc_protocol::FileSubscriber; + use crate::bcudp::model::*; + use crate::bcudp::xml::*; + use assert_matches::assert_matches; + use env_logger::Env; + use log::*; + use std::io::ErrorKind; + use std::path::PathBuf; + + fn init() { + let _ = env_logger::Builder::from_env(Env::default().default_filter_or("info")) + .is_test(true) + .try_init(); + } + + fn sample(name: &str) -> PathBuf { + let dir = std::env::current_dir().unwrap(); // This is crate root during cargo test + dir.join("src").join("bcudp").join("samples").join(name) + } + + #[test] + // Tests the decoding of a UdpDiscovery with a discovery xml + fn test_nego_disconnect() { + init(); + + let mut subsciber = FileSubscriber::from_files(vec![sample("udp_negotiate_disc.bin")]); + + let e = BcUdp::deserialize(&mut subsciber); + assert_matches!( + e, + Ok(BcUdp::Discovery(UdpDiscovery { + tid: 96, + payload: UdpXml { + disconnect: Some(Disconnect { + cid: 82000, + did: 80, + }), + .. + }, + })) + ); + } + + #[test] + // Tests the decoding of a UdpDiscovery with a Camera Transmission xml + fn test_nego_cam_transmission() { + init(); + + let mut subsciber = FileSubscriber::from_files(vec![sample("udp_negotiate_camt.bin")]); + + let e = BcUdp::deserialize(&mut subsciber); + assert_matches!( + e, + Ok(BcUdp::Discovery(UdpDiscovery { + tid: 113, + payload: UdpXml { + camera_transmission: Some(CameraTransmission { + sid: 62098713, + conn: conn_str, + cid: 82001, + did: 96, + }), + .. + }, + })) if &conn_str == "local" + ); + } + + #[test] + // Tests the decoding of a UdpDiscovery with a Client Transmission xml + fn test_nego_client_transmission() { + init(); + + let mut subsciber = FileSubscriber::from_files(vec![sample("udp_negotiate_clientt.bin")]); + + let e = BcUdp::deserialize(&mut subsciber); + assert_matches!( + e, + Ok(BcUdp::Discovery(UdpDiscovery { + tid: 1101, + payload: UdpXml { + client_transmission: Some(ClientTransmission { + sid: 62098713, + conn: conn_str, + cid: 82001, + mtu: 1350, + }), + .. + }, + })) if &conn_str == "local" + ); + } + + #[test] + // Tests the decoding of a UdpDiscovery with a Camera CFM xml + fn test_nego_cfm() { + init(); + + let mut subsciber = FileSubscriber::from_files(vec![sample("udp_negotiate_camcfm.bin")]); + + let e = BcUdp::deserialize(&mut subsciber); + assert_matches!( + e, + Ok(BcUdp::Discovery(UdpDiscovery { + tid: 1101, + payload: UdpXml { + camera_cfm: Some(CameraCfm { + sid: 62098713, + conn: conn_str, + rsp: 0, + cid: 82001, + did: 96, + time_r: 0, + }), + .. + }, + })) if &conn_str == "local" + ); + } + + #[test] + // Tests the decoding of an acknoledge packet + fn test_ack() { + init(); + + let mut subsciber = FileSubscriber::from_files(vec![sample("udp_ack.bin")]); + + let e = BcUdp::deserialize(&mut subsciber); + assert_matches!( + e, + Ok(BcUdp::Ack(UdpAck { + connection_id: 80, + packet_id: 2439, + })) + ); + } + + #[test] + // Tests the decoding of an data packet + fn test_data() { + init(); + + let mut subsciber = FileSubscriber::from_files(vec![sample("udp_data.bin")]); + + let e = BcUdp::deserialize(&mut subsciber); + assert_matches!( + e, + Ok(BcUdp::Data(UdpData { + connection_id: 82000, + packet_id: 2439, + payload: payload_data + })) if payload_data.len() == 1176 + ); + } + + #[test] + // Tests the decoding of multiple packets + fn test_multi_packets() { + init(); + + let mut subsciber = FileSubscriber::from_files(vec![ + sample("udp_multi_0.bin"), + sample("udp_multi_1.bin"), + sample("udp_multi_2.bin"), + sample("udp_multi_3.bin"), + sample("udp_multi_4.bin"), + sample("udp_multi_5.bin"), + sample("udp_multi_6.bin"), + sample("udp_multi_7.bin"), + sample("udp_multi_8.bin"), + sample("udp_multi_9.bin"), + ]); + + // Should derealise all of this + loop { + let e = BcUdp::deserialize(&mut subsciber); + match e { + Err(Error::IoError(e)) if e.kind() == ErrorKind::UnexpectedEof => { + // Reach end of files + break; + } + Err(e) => { + error!("{:?}", e); + panic!(); + } + Ok(_) => {} + } + } + } +} diff --git a/crates/core/src/bcudp/mod.rs b/crates/core/src/bcudp/mod.rs new file mode 100644 index 0000000..4c50f65 --- /dev/null +++ b/crates/core/src/bcudp/mod.rs @@ -0,0 +1,32 @@ +//! This module contains the protocol for dealing with UDP. +//! +//! There are three types of packets +//! +//! - Discovery +//! - Ack +//! - Data +//! +//! --- +//! +//! **Discovery**: Deals with setting up the initial connection and including their +//! connection IDs and the MTU +//! +//! --- +//! +//! **Ack**: Is sent after every packet is recieved +//! +//! --- +//! +//! **Data**: Contains a Bc packet payload. This is a stream and one Bc Packet may +//! be split accross multiple UDP Data packets +//! + +mod crc; +mod de; +/// Contains the model describing the top level structures +pub mod model; +mod ser; +/// Contains the udp related xml payloads +pub mod xml; +// Constains routines to de/encrypt udp xml +mod xml_crypto; diff --git a/crates/core/src/bcudp/model.rs b/crates/core/src/bcudp/model.rs new file mode 100644 index 0000000..46c4214 --- /dev/null +++ b/crates/core/src/bcudp/model.rs @@ -0,0 +1,69 @@ +//! The BcUdp Model +//! + +use super::xml::*; + +/// Top level udp packet +#[derive(Debug, PartialEq, Eq)] +pub enum BcUdp { + /// Packet from the negotiate stage when connection info is exchanged + Discovery(UdpDiscovery), + /// Packet to acknoledge receipt of a data packet + Ack(UdpAck), + /// Packet containing the data (or part of the data) of a Bc packet + Data(UdpData), +} + +/// Magic for the UDP Discovery packet +pub const MAGIC_HEADER_UDP_NEGO: u32 = 0x2a87cf3a; + +/// The Discovery packet is sent and received to init a connection +#[derive(Debug, PartialEq, Eq)] +pub struct UdpDiscovery { + // 4 Bytes Magic + // 4 Byte payload size + // 4 Bytes unknown always `01000000` + /// The transmission id is unique to a message and used as an encryption key + pub tid: u32, + // The checksum of the payload + // pub checksum: u32, + /// The payload + pub payload: UdpXml, +} + +/// Magic for the UDP Ack packet +pub const MAGIC_HEADER_UDP_ACK: u32 = 0x2a87cf20; + +/// Send to acknoledge a [`UdpData`] packet. If this is not sent then the camera will +/// resend the packet +#[derive(Debug, PartialEq, Eq)] +pub struct UdpAck { + /// The connection ID of the other party + /// + /// This is negotiated during [`UdpDiscovery`] + pub connection_id: u32, + // Unknown 4 bytes always 0 + /// The ID of the last data packet [`UdpData`] + pub packet_id: u32, + // 2 Bytes Unknown: Observed values `00000000`, `d6010000`, `d7160000` `09e00000` + // 2 Bytes Unknown: Observed values `00000000` +} + +/// Magic for the UDP Data packet +pub const MAGIC_HEADER_UDP_DATA: u32 = 0x2a87cf10; + +/// Contains the data of a [`crate::bc::model::Bc`] packet +#[derive(Debug, PartialEq, Eq)] +pub struct UdpData { + /// The connection ID of the other party + /// + /// This is negotiated during [`UdpDiscovery`] + pub connection_id: u32, + // Unknown 4 bytes always 0 + /// The ID of the data packet + pub packet_id: u32, + // Unknown 4 bytes always 0 + // 4 Byte payload size + /// The payload + pub payload: Vec, +} diff --git a/crates/core/src/bcudp/samples/udp_ack.bin b/crates/core/src/bcudp/samples/udp_ack.bin new file mode 100644 index 0000000..0456b53 Binary files /dev/null and b/crates/core/src/bcudp/samples/udp_ack.bin differ diff --git a/crates/core/src/bcudp/samples/udp_data.bin b/crates/core/src/bcudp/samples/udp_data.bin new file mode 100644 index 0000000..d859d7d Binary files /dev/null and b/crates/core/src/bcudp/samples/udp_data.bin differ diff --git a/crates/core/src/bcudp/samples/udp_multi_0.bin b/crates/core/src/bcudp/samples/udp_multi_0.bin new file mode 100644 index 0000000..040417c Binary files /dev/null and b/crates/core/src/bcudp/samples/udp_multi_0.bin differ diff --git a/crates/core/src/bcudp/samples/udp_multi_1.bin b/crates/core/src/bcudp/samples/udp_multi_1.bin new file mode 100644 index 0000000..9fc66d0 Binary files /dev/null and b/crates/core/src/bcudp/samples/udp_multi_1.bin differ diff --git a/crates/core/src/bcudp/samples/udp_multi_2.bin b/crates/core/src/bcudp/samples/udp_multi_2.bin new file mode 100644 index 0000000..24097da Binary files /dev/null and b/crates/core/src/bcudp/samples/udp_multi_2.bin differ diff --git a/crates/core/src/bcudp/samples/udp_multi_3.bin b/crates/core/src/bcudp/samples/udp_multi_3.bin new file mode 100644 index 0000000..70cb065 Binary files /dev/null and b/crates/core/src/bcudp/samples/udp_multi_3.bin differ diff --git a/crates/core/src/bcudp/samples/udp_multi_4.bin b/crates/core/src/bcudp/samples/udp_multi_4.bin new file mode 100644 index 0000000..a2cedf3 Binary files /dev/null and b/crates/core/src/bcudp/samples/udp_multi_4.bin differ diff --git a/crates/core/src/bcudp/samples/udp_multi_5.bin b/crates/core/src/bcudp/samples/udp_multi_5.bin new file mode 100644 index 0000000..24097da Binary files /dev/null and b/crates/core/src/bcudp/samples/udp_multi_5.bin differ diff --git a/crates/core/src/bcudp/samples/udp_multi_6.bin b/crates/core/src/bcudp/samples/udp_multi_6.bin new file mode 100644 index 0000000..24097da Binary files /dev/null and b/crates/core/src/bcudp/samples/udp_multi_6.bin differ diff --git a/crates/core/src/bcudp/samples/udp_multi_7.bin b/crates/core/src/bcudp/samples/udp_multi_7.bin new file mode 100644 index 0000000..70cb065 Binary files /dev/null and b/crates/core/src/bcudp/samples/udp_multi_7.bin differ diff --git a/crates/core/src/bcudp/samples/udp_multi_8.bin b/crates/core/src/bcudp/samples/udp_multi_8.bin new file mode 100644 index 0000000..24097da Binary files /dev/null and b/crates/core/src/bcudp/samples/udp_multi_8.bin differ diff --git a/crates/core/src/bcudp/samples/udp_multi_9.bin b/crates/core/src/bcudp/samples/udp_multi_9.bin new file mode 100644 index 0000000..24097da Binary files /dev/null and b/crates/core/src/bcudp/samples/udp_multi_9.bin differ diff --git a/crates/core/src/bcudp/samples/udp_negotiate_camcfm.bin b/crates/core/src/bcudp/samples/udp_negotiate_camcfm.bin new file mode 100644 index 0000000..c3c1b0a Binary files /dev/null and b/crates/core/src/bcudp/samples/udp_negotiate_camcfm.bin differ diff --git a/crates/core/src/bcudp/samples/udp_negotiate_camt.bin b/crates/core/src/bcudp/samples/udp_negotiate_camt.bin new file mode 100644 index 0000000..7d3c4eb Binary files /dev/null and b/crates/core/src/bcudp/samples/udp_negotiate_camt.bin differ diff --git a/crates/core/src/bcudp/samples/udp_negotiate_clientt.bin b/crates/core/src/bcudp/samples/udp_negotiate_clientt.bin new file mode 100644 index 0000000..2b4ec01 Binary files /dev/null and b/crates/core/src/bcudp/samples/udp_negotiate_clientt.bin differ diff --git a/crates/core/src/bcudp/samples/udp_negotiate_disc.bin b/crates/core/src/bcudp/samples/udp_negotiate_disc.bin new file mode 100644 index 0000000..34f5789 Binary files /dev/null and b/crates/core/src/bcudp/samples/udp_negotiate_disc.bin differ diff --git a/crates/core/src/bcudp/samples/xml_crypto_sample1.bin b/crates/core/src/bcudp/samples/xml_crypto_sample1.bin new file mode 100644 index 0000000..db2c08c Binary files /dev/null and b/crates/core/src/bcudp/samples/xml_crypto_sample1.bin differ diff --git a/crates/core/src/bcudp/samples/xml_crypto_sample1_plaintext.bin b/crates/core/src/bcudp/samples/xml_crypto_sample1_plaintext.bin new file mode 100644 index 0000000..71d478a --- /dev/null +++ b/crates/core/src/bcudp/samples/xml_crypto_sample1_plaintext.bin @@ -0,0 +1,8 @@ + + +62097899 +local +82000 +80 + + diff --git a/crates/core/src/bcudp/ser.rs b/crates/core/src/bcudp/ser.rs new file mode 100644 index 0000000..04c7887 --- /dev/null +++ b/crates/core/src/bcudp/ser.rs @@ -0,0 +1,183 @@ +use super::{crc::calc_crc, model::*, xml_crypto::encrypt}; +use cookie_factory::bytes::*; +use cookie_factory::sequence::tuple; +use cookie_factory::{combinator::*, gen}; +use cookie_factory::{GenError, SerializeFn}; +use err_derive::Error; +use log::error; +use std::io::Write; + +/// The error types used during serialisation +#[derive(Debug, Error)] +pub enum Error { + /// A Cookie Factor GenError + #[error(display = "Cookie GenError")] + GenError(#[error(source)] GenError), +} + +impl BcUdp { + pub(crate) fn serialize(&self, buf: W) -> Result { + let (buf, _) = match &self { + BcUdp::Discovery(payload) => { + let xml_payload = encrypt(payload.tid, &payload.payload.serialize(vec![]).unwrap()); + gen(bcudp_disc(payload, &xml_payload), buf)? + } + BcUdp::Ack(payload) => gen(bcudp_ack(payload), buf)?, + BcUdp::Data(payload) => { + let binary_payload = &payload.payload; + gen(bcudp_data(payload, binary_payload), buf)? + } + }; + + Ok(buf) + } +} + +fn bcudp_disc<'a, W: 'a + Write>( + payload: &'a UdpDiscovery, + xml_payload: &'a [u8], +) -> impl SerializeFn + 'a { + let checksum = calc_crc(xml_payload); + tuple(( + le_u32(MAGIC_HEADER_UDP_NEGO), + le_u32(xml_payload.len() as u32), + le_u32(1), + le_u32(payload.tid), + le_u32(checksum), + slice(xml_payload), + )) +} + +fn bcudp_ack<'a, W: 'a + Write>(payload: &'a UdpAck) -> impl SerializeFn + 'a { + tuple(( + le_u32(MAGIC_HEADER_UDP_ACK), + le_u32(payload.connection_id), + le_u32(0), + le_u32(0), + le_u32(payload.packet_id), + le_u32(0), + le_u32(0), + )) +} + +fn bcudp_data<'a, W: 'a + Write>( + payload: &'a UdpData, + binary_payload: &'a [u8], +) -> impl SerializeFn + 'a { + tuple(( + le_u32(MAGIC_HEADER_UDP_DATA), + le_u32(payload.connection_id), + le_u32(0), + le_u32(payload.packet_id), + le_u32(binary_payload.len() as u32), + slice(binary_payload), + )) +} + +#[cfg(test)] +mod tests { + use crate::bcudp::model::*; + use env_logger::Env; + + fn init() { + let _ = env_logger::Builder::from_env(Env::default().default_filter_or("info")) + .is_test(true) + .try_init(); + } + + #[test] + // Tests the decoding of a UdpDiscovery with a discovery xml + fn test_nego_disconnect() { + init(); + + let sample = include_bytes!("samples/udp_negotiate_disc.bin"); + + let msg = BcUdp::deserialize(&sample[..]).unwrap(); + let ser_buf = msg.serialize(vec![]).unwrap(); + let msg2 = BcUdp::deserialize::<&[u8]>(ser_buf.as_ref()).unwrap(); + assert_eq!(msg, msg2); + // Raw samples don't quite match exactly + // because the yaserde for xml puts spaces and new lines in different places + // then the raw data from the camera so we skip this last assert + //assert_eq!(&sample[..], ser_buf.as_slice()); + } + + #[test] + // Tests the decoding of a UdpDiscovery with a Camera Transmission xml + fn test_nego_cam_transmission() { + init(); + + let sample = include_bytes!("samples/udp_negotiate_camt.bin"); + + let msg = BcUdp::deserialize(&sample[..]).unwrap(); + let ser_buf = msg.serialize(vec![]).unwrap(); + let msg2 = BcUdp::deserialize::<&[u8]>(ser_buf.as_ref()).unwrap(); + assert_eq!(msg, msg2); + // Raw samples don't quite match exactly + // because the yaserde for xml puts spaces and new lines in different places + // then the raw data from the camera so we skip this last assert + //assert_eq!(&sample[..], ser_buf.as_slice()); + } + + #[test] + // Tests the decoding of a UdpDiscovery with a Client Transmission xml + fn test_nego_client_transmission() { + init(); + + let sample = include_bytes!("samples/udp_negotiate_clientt.bin"); + + let msg = BcUdp::deserialize(&sample[..]).unwrap(); + let ser_buf = msg.serialize(vec![]).unwrap(); + let msg2 = BcUdp::deserialize::<&[u8]>(ser_buf.as_ref()).unwrap(); + assert_eq!(msg, msg2); + // Raw samples don't quite match exactly + // because the yaserde for xml puts spaces and new lines in different places + // then the raw data from the camera so we skip this last assert + //assert_eq!(&sample[..], ser_buf.as_slice()); + } + + #[test] + // Tests the decoding of a UdpDiscovery with a Camera CFM xml + fn test_nego_cfm() { + init(); + + let sample = include_bytes!("samples/udp_negotiate_camcfm.bin"); + + let msg = BcUdp::deserialize(&sample[..]).unwrap(); + let ser_buf = msg.serialize(vec![]).unwrap(); + let msg2 = BcUdp::deserialize::<&[u8]>(ser_buf.as_ref()).unwrap(); + assert_eq!(msg, msg2); + // Raw samples don't quite match exactly + // because the yaserde for xml puts spaces and new lines in different places + // then the raw data from the camera so we skip this last assert + //assert_eq!(&sample[..], ser_buf.as_slice()); + } + + #[test] + // Tests the decoding of an acknoledge packet + fn test_ack() { + init(); + + let sample = include_bytes!("samples/udp_ack.bin"); + + let msg = BcUdp::deserialize(&sample[..]).unwrap(); + let ser_buf = msg.serialize(vec![]).unwrap(); + let msg2 = BcUdp::deserialize::<&[u8]>(ser_buf.as_ref()).unwrap(); + assert_eq!(msg, msg2); + assert_eq!(&sample[..], ser_buf.as_slice()); + } + + #[test] + // Tests the decoding of an data packet + fn test_data() { + init(); + + let sample = include_bytes!("samples/udp_data.bin"); + + let msg = BcUdp::deserialize(&sample[..]).unwrap(); + let ser_buf = msg.serialize(vec![]).unwrap(); + let msg2 = BcUdp::deserialize::<&[u8]>(ser_buf.as_ref()).unwrap(); + assert_eq!(msg, msg2); + assert_eq!(&sample[..], ser_buf.as_slice()); + } +} diff --git a/crates/core/src/bcudp/xml.rs b/crates/core/src/bcudp/xml.rs new file mode 100644 index 0000000..f99d7ca --- /dev/null +++ b/crates/core/src/bcudp/xml.rs @@ -0,0 +1,138 @@ +// YaSerde currently macro-expands names like __type__value from type_ + +use std::io::{Read, Write}; +// YaSerde is currently naming the traits and the derive macros identically +use yaserde::{ser::Config, YaDeserialize, YaSerialize}; +use yaserde_derive::{YaDeserialize, YaSerialize}; + +/// The top level of the UDP xml is P2P +#[derive(PartialEq, Eq, Debug, YaDeserialize, YaSerialize)] +#[yaserde(rename = "P2P")] +pub struct UdpXml { + /// C2D_S xml + #[yaserde(rename = "C2D_S")] + pub start: Option, + /// C2D_S xml + #[yaserde(rename = "C2D_C")] + pub start_with: Option, + /// D2C_T xml + #[yaserde(rename = "D2C_T")] + pub camera_transmission: Option, + /// C2D_T xml + #[yaserde(rename = "C2D_T")] + pub client_transmission: Option, + /// D2C_CFM xml + #[yaserde(rename = "D2C_CFM")] + pub camera_cfm: Option, + /// C2D_DISC xml + #[yaserde(rename = "C2D_DISC")] + pub disconnect: Option, +} + +impl UdpXml { + pub(crate) fn try_parse(s: impl Read) -> Result { + yaserde::de::from_reader(s) + } + pub(crate) fn serialize(&self, w: W) -> Result { + yaserde::ser::serialize_with_writer(self, w, &Config::default()) + } +} + +/// C2D_S xml +/// +/// The camera will send binary data to port 3000 +/// to whoever it gets this message from +/// +/// It should be broadcasted to port 2015 +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +pub struct DiscoveryStartAny { + /// The destination to reply to + pub to: StartTo, +} + +/// to xml +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +pub struct StartTo { + /// Port to open udp connections with + pub port: u32, +} + +/// C2D_C xml +/// +/// This will start a connection with any camera that has this UID +/// It should be broadcasted to port 2018 +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +pub struct DiscoveryStartWith { + /// UID of the camera the client wants to connect with + pub uid: String, + /// Cli contains the udp port to communicate on + pub cli: StartCli, + /// The cid is the client ID + pub cid: u32, + /// Maximum transmission size, + pub mtu: u32, + /// Debug mode. Purpose unknown + pub debug: bool, + /// Os of the machine known values are `"MAC"` + #[yaserde(rename = "p")] + pub os: String, +} + +/// C2D_C xml +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +pub struct StartCli { + /// Port to start udp communication with + pub port: u32, +} + +/// C2D_DISC xml +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +pub struct Disconnect { + /// The client connection ID + pub cid: u32, + /// The camera connection ID + pub did: u32, +} + +/// D2C_T xml +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +pub struct CameraTransmission { + /// The camera SID + pub sid: u32, + /// Type of connection observed values are `"local"` + pub conn: String, + /// The client connection ID + pub cid: u32, + /// The camera connection ID + pub did: u32, +} + +/// C2D_T xml +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +pub struct ClientTransmission { + /// The camera SID + pub sid: u32, + /// Type of connection observed values are `"local"` + pub conn: String, + /// The client connection ID + pub cid: u32, + /// Maximum size in bytes of a transmission + pub mtu: u32, +} + +/// D2C_CFM xml +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +pub struct CameraCfm { + /// The camera SID + pub sid: u32, + /// Type of connection observed values are `"local"` + pub conn: String, + /// Unknown known values are `0` + pub rsp: u32, + /// The client connection ID + pub cid: u32, + /// The camera connection ID + pub did: u32, + /// The time but only value that has been observed is `0 + pub time_r: u32, +} diff --git a/crates/core/src/bcudp/xml_crypto.rs b/crates/core/src/bcudp/xml_crypto.rs new file mode 100644 index 0000000..147f575 --- /dev/null +++ b/crates/core/src/bcudp/xml_crypto.rs @@ -0,0 +1,34 @@ +const XML_KEY: [u32; 8] = [ + 0x1f2d3c4b, 0x5a6c7f8d, 0x38172e4b, 0x8271635a, 0x863f1a2b, 0xa5c6f7d8, 0x8371e1b4, 0x17f2d3a5, +]; + +pub(crate) fn decrypt(offset: u32, buf: &[u8]) -> Vec { + let key = XML_KEY + .iter() + .map(|i| (i + offset).to_le_bytes()) + .flatten() + .cycle(); + buf.iter().zip(key).map(|(byte, key)| key ^ byte).collect() +} + +pub(crate) fn encrypt(offset: u32, buf: &[u8]) -> Vec { + decrypt(offset, buf) +} + +#[test] +fn test_udp_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(87, &sample[..]); + assert_eq!(decrypted, &should_be[..]); +} + +#[test] +fn test_udp_xml_crypto_roundtrip() { + let zeros: [u8; 256] = [0; 256]; + + let decrypted = encrypt(0, &zeros[..]); + let encrypted = decrypt(0, &decrypted[..]); + assert_eq!(encrypted, &zeros[..]); +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 4b6076a..c2e5a4d 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -30,6 +30,8 @@ pub mod bc; pub mod bc_protocol; /// Contains low level structures and formats for the media substream pub mod bcmedia; +/// Contains low level structures and formats for the udpstream +pub mod bcudp; #[derive(Debug)] /// Certain method just as `start_video` will block forever or return an error diff --git a/dissector/udp.md b/dissector/udp.md new file mode 100644 index 0000000..2e788d2 --- /dev/null +++ b/dissector/udp.md @@ -0,0 +1,283 @@ +# BcUDP + +This document describes the UDP protocol. UDP, unlike TCP, is lossy, there +is no guarantee that all packets sent will be received or that they are received +in the same order. As such the protocol involves sending meta data back and forth +where the camera and client acknowledge packets they have received. + +Additionally the UDP max data size is smaller so packets will be split more +perhaps even several UDP packets per BC message, whereas in TCP the Bc messages were +always in one TCP packet. + +# Packets Types + +There are three types of UDP packets with their own header + +- UDP Discovery: These packets have the magic `3acf872a` and contain encrypted + xml about the connection that will be used +- UDP Ack: These packets have the magic `20cf872a` they are header only and + contain acknowledgement of packets +- UDP Data: These packets contain part of a BC messagse with a special UDP + header that describes the udp message number, to help reassemble + the packets. They have the magic: `10cf872a` + +# UDP Discovery + +These messages are sent as part of the initial connection discovery. +It is a sequence of messages with different xmls. + +If there is no reply is received within 500ms the last message is resent. + +## Header 20 Bytes + +- 4 Bytes magic: `3acf872a` +- 4 Bytes data size: Size in bytes of payload +- 4 Bytes unknown: Always `01000000` for for UDP Discovery +- 4 Bytes Transmission ID: The unique ID of the transmission, every successful + round trip of Discovery it is incremented. + The number is the same for the same transmission + and may be used to identify repeated messages. + It is also used for the encryption. +- 4 Bytes Checksum: The checksum of the payload encrypted payload + +The checksum can be calculated with this rust code: + +```rust +const TABLE: [u32; 1024] = [0x0, 0x0, 0x0, 0x0, 0x96, 0x30, 0x7, 0x77, 0x2C, 0x61, 0xE, 0xEE, 0xBA, 0x51, 0x9, 0x99, 0x19, 0xC4, 0x6D, 0x7, 0x8F, 0xF4, 0x6A, 0x70, 0x35, 0xA5, 0x63, 0xE9, 0xA3, 0x95, 0x64, 0x9E, 0x32, 0x88, 0xDB, 0xE, 0xA4, 0xB8, 0xDC, 0x79, 0x1E, 0xE9, 0xD5, 0xE0, 0x88, 0xD9, 0xD2, 0x97, 0x2B, 0x4C, 0xB6, 0x9, 0xBD, 0x7C, 0xB1, 0x7E, 0x7, 0x2D, 0xB8, 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A3, 0xB4, 0x24, 0x5, 0x36, 0xD0, 0xBA, 0x93, 0x6, 0xD7, 0xCD, 0x29, 0x57, 0xDE, 0x54, 0xBF, 0x67, 0xD9, 0x23, 0x2E, 0x7A, 0x66, 0xB3, 0xB8, 0x4A, 0x61, 0xC4, 0x2, 0x1B, 0x68, 0x5D, 0x94, 0x2B, 0x6F, 0x2A, 0x37, 0xBE, 0xB, 0xB4, 0xA1, 0x8E, 0xC, 0xC3, 0x1B, 0xDF, 0x5, 0x5A, 0x8D, 0xEF, 0x02, 0x2D,]; + +pub(crate) fn calc_crc(payload: &[u8]) -> u32 { + let mut r: u32 = 0; + for &val in payload.iter() { + let offset = (((val as u32 ^ r) & 0xFF) << 2) as usize; + let val: u32 = TABLE[offset + 3] << 24 + | TABLE[offset + 2] << 16 + | TABLE[offset + 1] << 8 + | TABLE[offset]; + r = val ^ (r >> 8); + } + r +} +``` + + +## Payload + +- Payload can be encrypted and decrypted with this rust code + +```rust +const XML_KEY: [u32; 8] = [ + 0x1f2d3c4b, 0x5a6c7f8d, 0x38172e4b, 0x8271635a, 0x863f1a2b, 0xa5c6f7d8, 0x8371e1b4, 0x17f2d3a5, +]; + +pub(crate) fn decrypt(offset: u32, buf: &[u8]) -> Vec { + let key = XML_KEY + .iter() + .map(|i| (i + offset).to_le_bytes()) + .flatten() + .cycle(); + buf.iter().zip(key).map(|(byte, key)| key ^ byte).collect() +} +``` + +## Start Discovery payload + +Client send this packet as a broadcast on 255.255.255.255 on port 2015 +to init a connection + +```xml + + + + 57268 + + + +``` + +--- + +**Camera Replies with Binary** + +Camera replies with binary data to port 3000 + +This data seems to include the +- Camera name +- ip address +- TCP port +- Camera UID + + +**Tcp camera** + +If the camera supports tcp the client will use this binary data to open a +standard tcp bc connection + +**Udp Camera** + +If the camera supports UDP the client will send this xml packet +as a broadcast on 255.255.255.255 on port 2018 + +```xml + + + 95270000YGAKNWKJ + + 24862 + + 849013 + 1350 + 0 +

MAC

+
+
+``` + +**Both** + +A camera can do both of the above. In this case it will try to login +to both udp and tcp. Then the udp will disconnect. + +--- + +## T Payload Camera + +Camera replies with this payload on the port specified in `C2D_C` + +```xml + + + 62097899 + local + 82000 + 80 + + +``` + +- **sid**: ID of the camera +- **conn**: Type of connection only observed `local` value +- **cid**: The connection ID of the client +- **did**: The connection ID of the camera + + +Camera also sends this + +```xml + + + + 3000 + 10000 + 60000 + + 0 + 849013 + 192 + + +``` + + +## T Payload Client + +Client then replies with this. + +```xml + + + 62097899 + local + 82000 + 1350 + + +``` + +- **sid**: ID of the camera +- **conn**: Type of connection only observed `local` value +- **cid**: The connection ID of the client +- **did**: The connection ID of the camera +- **mtu**: The maximum transmission unit of the connection. Which is the + largest packet size in bytes + +**Login** + +The client can now login over UDP + + +## Dissconnect + +After a message ID 02 (logout) the client send this + +```xml + + + 82000 + 80 + + +``` + +- **cid**: The connection ID of the client +- **did**: The connection ID of the camera + +## Other + +Some cameras seem to also send this before login + +```xml + + + 62097899 + local + 0 + 82000 + 80 + 0 + + +``` + +- **sid**: ID of the camera +- **conn**: Type of connection only observed `local` value +- **rsp**: Unknown always 0 +- **cid**: The connection ID of the client +- **did**: The connection ID of the camera +- **time_r**: Should be the time but it is always 0 + +# UDP Ack + +These messages are sent to acknowledge receipt of message. They are header only. + +## Header 28 Bytes + +- 4 Bytes magic: `20cf872a` +- 4 Bytes Connection ID: This is the connection ID negotiated during UDP Discovery +- 4 Bytes unknown: Always `00000000` for for UDP Ack +- 4 Bytes unknown: Always `00000000` for for UDP Ack +- 4 Bytes Last Packet ID: Last received packet id +- 4 Bytes Unknown: Observed values `00000000`, `d6010000`, `d7160000` `09e00000` **NEEDS INFO** +- 4 Bytes Unknown: Observed values `00000000` + +**To Investigate:** + - Why does the unknown byte change. It starts at zero and remains that way for a long + time. Then seems to change and remain at the new value for a long time + +# UDP Data + +UDP data packets contain the BC packets with an extra header. + +Whenever a packet is received a UDP Ack is sent. If the sender of the packet +does not get the Ack within 1000ms it resends the packet + +## Header 20 Bytes + +- 4 Bytes magic: `10cf872a` +- 4 Bytes Connection ID: This is the connection ID negotiated during UDP Discovery +- 4 Bytes unknown: Always `00000000` for for UDP Data +- 4 Bytes Packet ID: The ID of the packet mono-atomically increases for each new packet +- 4 Bytes Payload Size: Size of UDP payload in bytes + +## Payload + +The payload is a standard Bc Packet