diff --git a/dissector/baichuan.lua b/dissector/baichuan.lua index a03565e..c9e0337 100644 --- a/dissector/baichuan.lua +++ b/dissector/baichuan.lua @@ -10,6 +10,7 @@ message_len = ProtoField.int32("baichuan.msg_len", "messageLen", base.DEC) xml_enc_offset = ProtoField.int32("baichuan.xml_encryption_offset", "xmlEncryptionOffset", base.DEC) xml_enc_used = ProtoField.bool("baichuan.xml_encryption_used", "encrypted", base.NONE) message_class = ProtoField.int32("baichuan.msg_class", "messageClass", base.DEC) +f_bin_offset = ProtoField.int32("baichuan.bin_offset", "binOffset", base.DEC) username = ProtoField.string("baichuan.username", "username", base.ASCII) password = ProtoField.string("baichuan.password", "password", base.ASCII) @@ -20,8 +21,9 @@ bc_protocol.fields = { xml_enc_offset, xml_enc_used, message_class, + f_bin_offset, username, - password + password, } message_types = { @@ -49,12 +51,6 @@ function xml_encrypt(ba, offset) e:set_size(ba:len()) for i=0,ba:len() - 1 do e:set_index(i, bit32.bxor(bit32.band(offset, 0xFF), bit32.bxor(ba:get_index(i), key:byte(((i + offset) % 8) + 1)))) - - -- Heuristic: XML always starts with '<', so save the work if this doesn't - -- appear to be XML - if i == 0 and e:get_index(i) ~= string.byte('<') then - return nil - end end return e end @@ -86,6 +82,7 @@ function bc_protocol.dissector(buffer, pinfo, tree) local encrypted = (msg_cls == 0x6414 or buffer(16, 1):le_uint() ~= 0) local class = message_classes[buffer(18, 2):le_uint()] local header_len = header_lengths[buffer(18, 2):le_uint()] + if buffer:len() ~= msg_len + header_len then -- Case 1, need more bytes, -- from https://wiki.wireshark.org/Lua/Dissectors#TCP_reassembly @@ -94,6 +91,13 @@ function bc_protocol.dissector(buffer, pinfo, tree) return buffer:len() end + -- bin_offset is either nil (no binary data) or nonzero + local bin_offset = nil + if header_len == 24 then + bin_offset = buffer(20, 4):le_uint() + if bin_offset == 0 then bin_offset = nil end + end + local bc_subtree = tree:add(bc_protocol, buffer(), "Baichuan IP Camera Protocol, " .. msg_type_str .. " message") local header = bc_subtree:add(bc_protocol, buffer(0, header_len), @@ -108,6 +112,7 @@ function bc_protocol.dissector(buffer, pinfo, tree) header:add_le(xml_enc_used, buffer(16, 1)) header:add_le(message_class, buffer(18, 2)) :append_text(" (" .. class .. ")") + header:add_le(f_bin_offset, buffer(20, 4)) if msg_len == 0 then return @@ -122,26 +127,24 @@ function bc_protocol.dissector(buffer, pinfo, tree) body:add_le(password, buffer(header_len + 32, 32)) end else - local body_tvb = buffer(header_len, nil):tvb() + local body_tvb = buffer(header_len, bin_offset):tvb() + body:add(body_tvb(), "Encrypted XML") - -- Always attempt to undo the xmlEncryption, since it may be useful for - -- some messages that haven't been reversed yet (especially ones where the - -- request is XML and the reply is binary). if encrypted then - local ba = buffer(header_len, buffer:len() - header_len):bytes() + local ba = buffer(header_len, bin_offset):bytes() local decrypted = xml_encrypt(ba, enc_offset) - if decrypted ~= nil then - body_tvb = decrypted:tvb("Decrypted Body") - - -- Create a tree item that, when clicked, automatically shows the tab we just created - body:add(body_tvb(), "Decrypted Body") - end + body_tvb = decrypted:tvb("Decrypted XML") + -- Create a tree item that, when clicked, automatically shows the tab we just created + body:add(body_tvb(), "Decrypted XML") end + Dissector.get("xml"):call(body_tvb, pinfo, body) - if msg_type == 0x03 then -- video - Dissector.get("h265"):call(body_tvb, pinfo, tree) - else -- I presume everything else is XML control messages - Dissector.get("xml"):call(body_tvb, pinfo, body) + if bin_offset ~= nil then + local binary_tvb = buffer(header_len + bin_offset, nil):tvb() + body:add(binary_tvb(), "Binary Payload") + if msg_type == 0x03 then -- video + Dissector.get("h265"):call(binary_tvb, pinfo, tree) + end end end end diff --git a/src/bc/de.rs b/src/bc/de.rs new file mode 100644 index 0000000..2e57080 --- /dev/null +++ b/src/bc/de.rs @@ -0,0 +1,112 @@ +use nom::{IResult, error::ParseError}; +use nom::{bytes::complete::take, number::complete::*, combinator::*, sequence::*}; +use super::model::*; +use super::xml::Body; +use super::xml_crypto; + +fn bc_msg(buf: &[u8]) -> IResult<&[u8], Bc> { + let (buf, header) = bc_header(buf)?; + let (buf, msg) = bc_modern_msg(&header, buf)?; + + let bc = Bc { + header, + body: BcBody::ModernMsg(msg), + }; + + Ok((buf, bc)) +} + +fn bc_modern_msg<'a, 'b, E: ParseError<&'b [u8]>>(header: &'a BcHeader, buf: &'b [u8]) -> IResult<&'b [u8], ModernMsg, E> { + let end_of_xml = header.bin_offset.unwrap_or(buf.len() as u32); + + let (mut buf, body_buf) = take(end_of_xml)(buf)?; + + let decrypted; + let processed_body_buf = if !header.is_encrypted() { buf } else { + decrypted = xml_crypto::crypt(header.enc_offset, body_buf); + &decrypted + }; + + // Apply the function, but throw away the reference to decrypted in the Ok and Err case + // This error-error-error thing is the same idiom Nom uses internally. + use nom::{Err, error::{make_error, ErrorKind}}; + let body = Body::try_parse(processed_body_buf) + .map_err(|_| Err::Error(make_error(buf, ErrorKind::MapRes)))?; + + // Extract remainder of message as binary, if it exists + let mut binary = None; + if let Some(bin_offset) = header.bin_offset { + let (buf_after, payload) = map(take(header.body_len - bin_offset), |x: &[u8]| x.to_vec())(buf)?; + binary = Some(payload); + buf = buf_after; + } + + let msg = ModernMsg { + xml: Some(body), + binary, + }; + + Ok((buf, msg)) +} + +fn bc_header<'a, E: ParseError<&'a [u8]>>(buf: &'a [u8]) -> IResult<&[u8], BcHeader, E> { + let (buf, _magic) = verify(le_u32, |x| *x == MAGIC_HEADER)(buf)?; + let (buf, msg_id) = le_u32(buf)?; + let (buf, body_len) = le_u32(buf)?; + let (buf, enc_offset) = le_u32(buf)?; + let (buf, (response_code, _ignored, class)) = tuple((le_u8, le_u8, le_u16))(buf)?; + + // All modern messages are encrypted. In addition, it seems that the camera firmware checks + // this field to see if some other messages should be encrypted. This is still somewhat fuzzy. + // A copy of the source code for the camera would be very useful. + let encrypted = response_code != 0; + + // See BcHeader::is_modern() for a description of which packets have the bin offset + let has_bin_offset = class == 0x6414 || class == 0x0000; + let (buf, bin_offset) = cond(has_bin_offset, le_u32)(buf)?; + + Ok((buf, BcHeader { + msg_id, + body_len, + enc_offset, + encrypted, + class, + bin_offset, + })) +} + +#[test] +fn test_bc_modern_login() { + let sample = include_bytes!("samples/model_sample_modern_login.bin"); + + let (_, msg) = bc_msg(&sample[..]).unwrap(); + assert_eq!(msg.header.msg_id, 1); + assert_eq!(msg.header.body_len, 145); + assert_eq!(msg.header.enc_offset, 0x1000000); + assert_eq!(msg.header.encrypted, true); + assert_eq!(msg.header.class, 0x6614); + match msg.body { + BcBody::ModernMsg(ModernMsg{ xml: Some(xml), binary: None }) => { + assert_eq!(xml.encryption.unwrap().nonce, "9E6D1FCB9E69846D") + } + _ => assert!(false), + } +} + +#[test] +fn test_bc_with_binary() { + let sample = include_bytes!("samples/model_sample_modern_login.bin"); + + let (_, msg) = bc_msg(&sample[..]).unwrap(); + assert_eq!(msg.header.msg_id, 1); + assert_eq!(msg.header.body_len, 145); + assert_eq!(msg.header.enc_offset, 0x1000000); + assert_eq!(msg.header.encrypted, true); + assert_eq!(msg.header.class, 0x6614); + match msg.body { + BcBody::ModernMsg(ModernMsg{ xml: Some(xml), binary: None }) => { + assert_eq!(xml.encryption.unwrap().nonce, "9E6D1FCB9E69846D") + } + _ => assert!(false), + } +} diff --git a/src/bc/mod.rs b/src/bc/mod.rs index ea377d9..e6208ed 100644 --- a/src/bc/mod.rs +++ b/src/bc/mod.rs @@ -1,5 +1,6 @@ +mod de; mod model; -mod bc_xml; +mod xml; mod xml_crypto; pub use model::Bc; diff --git a/src/bc/model.rs b/src/bc/model.rs index fb5bdc8..25becb3 100644 --- a/src/bc/model.rs +++ b/src/bc/model.rs @@ -1,16 +1,13 @@ -use nom::{IResult, error::ParseError}; -use nom::{bytes::complete::take, number::complete::*, combinator::*, sequence::*}; -use super::bc_xml::Body; -use super::xml_crypto; +use super::xml::Body; -const MAGIC_HEADER: u32 = 0xabcdef0; +pub(super) const MAGIC_HEADER: u32 = 0xabcdef0; const MSG_ID_LOGIN: u32 = 1; const MSG_ID_VIDEO: u32 = 3; pub struct Bc { - header: BcHeader, - body: BcBody, + pub(super) header: BcHeader, + pub body: BcBody, } pub enum BcBody { @@ -19,8 +16,8 @@ pub enum BcBody { } pub struct ModernMsg { - xml: Option, - binary: Option>, + pub xml: Option, + pub binary: Option>, } pub enum LegacyMsg { @@ -30,13 +27,13 @@ pub enum LegacyMsg { } } -struct BcHeader { - body_len: u32, - msg_id: u32, - enc_offset: u32, - encrypted: bool, - class: u16, - bin_offset: Option, +pub(super) struct BcHeader { + pub(super) body_len: u32, + pub(super) msg_id: u32, + pub(super) enc_offset: u32, + pub(super) encrypted: bool, + pub(super) class: u16, + pub(super) bin_offset: Option, } impl BcHeader { @@ -59,87 +56,3 @@ impl BcHeader { } } -fn bc_msg(buf: &[u8]) -> IResult<&[u8], Bc> { - let (buf, header) = bc_header(buf)?; - let (buf, msg) = bc_modern_msg(&header, buf)?; - - let bc = Bc { - header, - body: BcBody::ModernMsg(msg), - }; - - Ok((buf, bc)) -} - -fn bc_modern_msg<'a, 'b, E: ParseError<&'b [u8]>>(header: &'a BcHeader, buf: &'b [u8]) -> IResult<&'b [u8], ModernMsg, E> { - let end_of_xml = header.bin_offset.unwrap_or(buf.len() as u32); - - let (mut buf, body_buf) = take(end_of_xml)(buf)?; - - let decrypted; - let processed_body_buf = if !header.is_encrypted() { buf } else { - decrypted = xml_crypto::crypt(header.enc_offset, body_buf); - &decrypted - }; - - // Apply the function, but throw away the reference to decrypted in the Ok and Err case - // This error-error-error thing is the same idiom Nom uses internally. - use nom::{Err, error::{make_error, ErrorKind}}; - let body = Body::try_parse(processed_body_buf) - .map_err(|_| Err::Error(make_error(buf, ErrorKind::MapRes)))?; - - // Extract remainder of message as binary, if it exists - let mut binary = None; - if let Some(bin_offset) = header.bin_offset { - let (buf_after, payload) = map(take(header.body_len - bin_offset), |x: &[u8]| x.to_vec())(buf)?; - binary = Some(payload); - buf = buf_after; - } - - let msg = ModernMsg { - xml: Some(body), - binary, - }; - - Ok((buf, msg)) -} - -fn bc_header(buf: &[u8]) -> IResult<&[u8], BcHeader> { - let (buf, _magic) = verify(le_u32, |x| *x == MAGIC_HEADER)(buf)?; - let (buf, msg_id) = le_u32(buf)?; - let (buf, body_len) = le_u32(buf)?; - let (buf, enc_offset) = le_u32(buf)?; - let (buf, (encrypted, _ignored, class)) = tuple((le_u8, le_u8, le_u16))(buf)?; - let encrypted = encrypted != 0; - - // See BcHeader::is_modern() for a description of which packets have the bin offset - let has_bin_offset = class == 0x6414 || class == 0x0000; - let (buf, bin_offset) = cond(has_bin_offset, le_u32)(buf)?; - - Ok((buf, BcHeader { - msg_id, - body_len, - enc_offset, - encrypted, - class, - bin_offset, - })) -} - -#[test] -fn test_bc_modern_login() { - let sample = include_bytes!("samples/model_sample_modern_login.bin"); - - let (_, msg) = bc_msg(&sample[..]).unwrap(); - assert_eq!(msg.header.msg_id, 1); - assert_eq!(msg.header.body_len, 145); - assert_eq!(msg.header.enc_offset, 0x1000000); - assert_eq!(msg.header.encrypted, true); - assert_eq!(msg.header.class, 0x6614); - match msg.body { - BcBody::ModernMsg(ModernMsg{ xml: Some(xml), binary: None }) => { - assert_eq!(xml.encryption.unwrap().nonce, "9E6D1FCB9E69846D") - } - _ => assert!(false), - } -} diff --git a/src/bc/bc_xml.rs b/src/bc/xml.rs similarity index 100% rename from src/bc/bc_xml.rs rename to src/bc/xml.rs