From f207fc1a9411455048f8db4b069190d316e710f9 Mon Sep 17 00:00:00 2001 From: George Hilliard Date: Sat, 18 Apr 2020 21:31:49 -0500 Subject: [PATCH] Implement initial login flow --- Cargo.toml | 3 + dissector/baichuan.lua | 2 +- src/bc/de.rs | 74 ++++++++++++--- src/bc/mod.rs | 10 +- src/bc/model.rs | 2 + src/bc/ser.rs | 19 ++-- src/bc/xml.rs | 17 ++++ src/bc_protocol.rs | 205 +++++++++++++++++++++++++++++++++++++++++ src/main.rs | 21 ++++- 9 files changed, 323 insertions(+), 30 deletions(-) create mode 100644 src/bc_protocol.rs diff --git a/Cargo.toml b/Cargo.toml index 5108f95..7a46ed2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,7 +8,10 @@ edition = "2018" [dependencies] cookie-factory = "0.3.1" +err-derive = "0.2.4" +log = "0.4.8" indoc = "0.3.5" +md5 = "0.7.0" nom = "5.1.1" yaserde = "0.3.15" yaserde_derive = "0.3.15" diff --git a/dissector/baichuan.lua b/dissector/baichuan.lua index 200e169..554e052 100644 --- a/dissector/baichuan.lua +++ b/dissector/baichuan.lua @@ -130,7 +130,7 @@ function bc_protocol.dissector(buffer, pinfo, tree) end else local body_tvb = buffer(header_len, bin_offset):tvb() - body:add(body_tvb(), "Encrypted XML") + body:add(body_tvb(), "XML Payload") if encrypted then local ba = buffer(header_len, bin_offset):bytes() diff --git a/src/bc/de.rs b/src/bc/de.rs index db8ee76..ed48192 100644 --- a/src/bc/de.rs +++ b/src/bc/de.rs @@ -1,13 +1,58 @@ -use nom::{IResult, error::ParseError}; -use nom::{bytes::complete::take, number::complete::*, combinator::*, sequence::*}; +use err_derive::Error; +use nom::IResult; +use nom::{bytes::streaming::take, number::streaming::*, combinator::*, sequence::*}; +use std::io::Read; use super::model::*; use super::xml::Body; use super::xml_crypto; +#[derive(Debug, Error)] +pub enum Error { + #[error(display="Parsing error")] + NomError(&'static str), + #[error(display="I/O error")] + IoError(#[error(source)] std::io::Error), +} + +type NomErrorTuple<'a> = (&'a [u8], nom::error::ErrorKind); + +impl<'a> From>> for Error { + fn from(k: nom::Err>) -> Self { + let reason = match k { + nom::Err::Error(_) => "Nom Error", + nom::Err::Failure(_) => "Nom Failure", + _ => "Unknown Nom error", + }; + Error::NomError(reason) + } +} + impl Bc { - pub fn deserialize(buf: &[u8]) -> Result { + pub fn deserialize(r: R) -> Result { // Throw away the nom-specific return types - bc_msg(buf).map(|(_, bc)| bc).map_err(|_| ()) // TODO better error + read_from_reader(bc_msg, r) + } +} + +fn read_from_reader(parser: P, mut rdr: R) -> Result + where R: Read, + E: for<'a> From>> + From, + P: Fn(&[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 => 1, // read one byte + nom::Needed::Size(len) => len, + } + }, + Err(e) => return Err(e.into()), + }; + + (&mut rdr).take(to_read as u64).read_to_end(&mut input)?; } } @@ -57,7 +102,7 @@ fn bc_legacy_login_msg<'a, 'b>(buf: &'b [u8]) fn bc_modern_msg<'a, 'b>(header: &'a BcHeader, buf: &'b [u8]) -> IResult<&'b [u8], ModernMsg> { - let end_of_xml = header.bin_offset.unwrap_or(buf.len() as u32); + let end_of_xml = header.bin_offset.unwrap_or(header.body_len); let (mut buf, body_buf) = take(end_of_xml)(buf)?; @@ -67,20 +112,23 @@ fn bc_modern_msg<'a, 'b>(header: &'a BcHeader, buf: &'b [u8]) &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)?; + let (buf_after, payload) = map(take(header.body_len - bin_offset), + |x: &[u8]| x.to_vec())(buf)?; binary = Some(payload); buf = buf_after; } + // Now we'll take the buffer that Nom gave a ref to and parse it. Do this last, so we don't + // parse over and over if we get Incompletes on the binary part. Apply the XML parse 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)))?; + let msg = ModernMsg { xml: Some(body), binary, @@ -148,7 +196,7 @@ fn test_bc_legacy_login() { username, password }) => { assert_eq!(username, "21232F297A57A5A743894A0E4A801FC\0"); - assert_eq!(password, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"); + assert_eq!(password, EMPTY_LEGACY_PASSWORD); } _ => assert!(false), } diff --git a/src/bc/mod.rs b/src/bc/mod.rs index 39ceb08..6122498 100644 --- a/src/bc/mod.rs +++ b/src/bc/mod.rs @@ -1,7 +1,5 @@ -mod de; -mod model; -mod ser; -mod xml; +pub mod de; +pub mod model; +pub mod ser; +pub mod xml; mod xml_crypto; - -pub use model::Bc; diff --git a/src/bc/model.rs b/src/bc/model.rs index aca624e..b579893 100644 --- a/src/bc/model.rs +++ b/src/bc/model.rs @@ -5,6 +5,8 @@ pub(super) const MAGIC_HEADER: u32 = 0xabcdef0; pub const MSG_ID_LOGIN: u32 = 1; pub const MSG_ID_VIDEO: u32 = 3; +pub const EMPTY_LEGACY_PASSWORD: &str = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"; + #[derive(Debug, PartialEq, Eq)] pub struct Bc { pub meta: BcMeta, diff --git a/src/bc/ser.rs b/src/bc/ser.rs index bda1dfb..21a6549 100644 --- a/src/bc/ser.rs +++ b/src/bc/ser.rs @@ -58,14 +58,19 @@ fn bc_xml(enc_offset: u32, xml: &Body) -> impl SerializeFn } fn bc_header(header: &BcHeader) -> impl SerializeFn { + // TODO this is actually a u16 "response code" in modern messages + let (signaled_encryption, spare) = if header.class == 0x0000 { + (0x00, 0x00) + } else { + (header.encrypted as u8, 0xdc) + }; tuple(( le_u32(MAGIC_HEADER), le_u32(header.msg_id), le_u32(header.body_len), le_u32(header.enc_offset), - le_u8(header.encrypted as u8), - //le_u8(header.response_code), - le_u8(0xdc), // skipped byte + le_u8(signaled_encryption), + le_u8(spare), // skipped byte le_u16(header.class), opt(header.bin_offset, le_u32), )) @@ -130,10 +135,10 @@ fn do_nothing() -> impl SerializeFn { fn test_legacy_login_roundtrip() { // I don't want to make up a sample message; just load it let sample = include_bytes!("samples/model_sample_legacy_login.bin"); - let msg = Bc::deserialize(&sample[..]).unwrap(); + let msg = Bc::deserialize::<&[u8]>(&sample[..]).unwrap(); let ser_buf = msg.serialize(vec!()).unwrap(); - let msg2 = Bc::deserialize(ser_buf.as_ref()).unwrap(); + let msg2 = Bc::deserialize::<&[u8]>(ser_buf.as_ref()).unwrap(); assert_eq!(msg, msg2); assert_eq!(&sample[..], ser_buf.as_slice()); } @@ -143,9 +148,9 @@ fn test_modern_login_roundtrip() { // I don't want to make up a sample message; just load it let sample = include_bytes!("samples/model_sample_modern_login.bin"); - let msg = Bc::deserialize(&sample[..]).unwrap(); + let msg = Bc::deserialize::<&[u8]>(&sample[..]).unwrap(); let ser_buf = msg.serialize(vec!()).unwrap(); - let msg2 = Bc::deserialize(ser_buf.as_ref()).unwrap(); + let msg2 = Bc::deserialize::<&[u8]>(ser_buf.as_ref()).unwrap(); assert_eq!(msg, msg2); } diff --git a/src/bc/xml.rs b/src/bc/xml.rs index a851912..c94c5c7 100644 --- a/src/bc/xml.rs +++ b/src/bc/xml.rs @@ -21,6 +21,8 @@ pub struct Body { pub login_user: Option, #[yaserde(rename="LoginNet")] pub login_net: Option, + #[yaserde(rename="DeviceInfo")] + pub device_info: Option, } impl Body { @@ -72,6 +74,21 @@ impl Default for LoginNet { } } +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +pub struct DeviceInfo { + #[yaserde(rename="Resolution")] + pub resolution: Resolution, +} + +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +pub struct Resolution { + #[yaserde(rename="resolutionName")] + pub name: String, + pub width: u32, + pub height: u32, +} + + pub fn xml_ver() -> String { "1.1".to_string() } diff --git a/src/bc_protocol.rs b/src/bc_protocol.rs new file mode 100644 index 0000000..17c8ce1 --- /dev/null +++ b/src/bc_protocol.rs @@ -0,0 +1,205 @@ +use err_derive::Error; +use log::*; +use md5; +use std::net::{IpAddr, SocketAddr, ToSocketAddrs, TcpStream}; +use super::bc::{model::*, xml::*}; + +pub struct BcCamera { + address: SocketAddr, + + connection: Option, + logged_in: bool, +} + +#[derive(Debug, Error)] +pub enum Error { + #[error(display="Communication error")] + CommunicationError(#[error(source)] std::io::Error), + #[error(display="Deserialization error")] + DeserializationError(#[error(source)] super::bc::de::Error), + #[error(display="Serialization error")] + SerializationError(#[error(source)] super::bc::ser::Error), + #[error(display="Communication error")] + UnintelligibleReply { + request: Bc, + reply: Bc, + why: &'static str, + }, + #[error(display="Credential error")] + AuthFailed, + #[error(display="Other error")] + OtherError(&'static str), +} + +type Result = std::result::Result; + +impl Drop for BcCamera { + fn drop(&mut self) { + self.disconnect(); + } +} + +impl BcCamera { + pub fn new_with_ip(ip_addr: IpAddr) -> Result { + Self::new_with_addr((ip_addr, 9000)) + } + + pub fn new_with_addr(hostname: T) -> Result { + let address = hostname.to_socket_addrs()?.next() + .ok_or(Error::OtherError("Address resolution failed"))?; + + Ok(Self { + address, + connection: None, + logged_in: false, + }) + } + + pub fn connect(&mut self) -> Result<()> { + self.connection = Some(TcpStream::connect(self.address)?); + Ok(()) + } + + pub fn disconnect(&mut self) { + if let Err(err) = self.logout() { + warn!("Could not log out, ignoring: {}", err); + } + self.connection = None; + } + + pub fn login(&mut self, username: &str, password: Option<&str>) -> Result { + use Md5Trunc::*; + + let connection = self.connection.as_ref().expect("Must be connected to log in"); + + // Login flow is: Send legacy login message, expect back a modern message with Encryption + // details. Then, re-send the login as a modern login message. Expect back a device info + // congratulating us on logging in. + + // In the legacy scheme, username/password are MD5'd if they are encrypted (which they need + // to be to "upgrade" to the modern login flow), then the hex of the MD5 is sent. + // Note: I suspect there may be a buffer overflow opportunity in the firmware since in the + // Baichuan library, these strings are capped at 32 bytes with a null terminator. This + // could also be a mistake in the library, the effect being it only compares 31 chars, not 32. + let md5_username = md5_string(username, ZeroLast); + let md5_password = password.map(|p| md5_string(p, ZeroLast)).unwrap_or(EMPTY_LEGACY_PASSWORD.to_owned()); + + let legacy_login = Bc { + meta: BcMeta { + msg_id: MSG_ID_LOGIN, + client_idx: 0, + encrypted: true, + class: 0x6514, + }, + body: BcBody::LegacyMsg(LegacyMsg::LoginMsg { + username: md5_username, + password: md5_password, + }) + }; + + legacy_login.serialize(connection)?; + + let legacy_reply = Bc::deserialize(connection)?; + let nonce; + match legacy_reply.body { + BcBody::ModernMsg(ModernMsg { + xml: Some(Body { encryption: Some(encryption), .. }), .. + }) => { + nonce = encryption.nonce; + } + _ => return Err(Error::UnintelligibleReply { + request: legacy_login, + reply: legacy_reply, + why: "Expected an Encryption message back" + }) + } + + // In the modern login flow, the username/password are concat'd with the server's nonce + // string, then MD5'd, then the hex of this MD5 is sent as the password. This nonce + // prevents replay attacks if the server were to require modern flow, but not rainbow table + // attacks (since the plain user/password MD5s have already been sent). The upshot is that + // you should use a very strong random password that is not found in a rainbow table and + // not feasibly crackable with John the Ripper. + + let modern_password = password.unwrap_or(""); + let concat_username = format!("{}{}", username, nonce); + let concat_password = format!("{}{}", modern_password, nonce); + let md5_username = md5_string(&concat_username, Truncate); + let md5_password = md5_string(&concat_password, Truncate); + + let modern_login = Bc { + meta: BcMeta { + msg_id: MSG_ID_LOGIN, + client_idx: 0, // TODO + encrypted: true, + class: 0x6414, + }, + body: BcBody::ModernMsg(ModernMsg { + xml: Some(Body { + login_user: Some(LoginUser { + version: xml_ver(), + user_name: md5_username, + password: md5_password, + user_ver: 1, + }), + login_net: Some(LoginNet::default()), + ..Default::default() + }), + binary: None, + }), + }; + + modern_login.serialize(connection)?; + + let modern_reply = Bc::deserialize(connection)?; + let device_info; + match modern_reply.body { + BcBody::ModernMsg(ModernMsg { + xml: Some(Body { device_info: Some(info), .. }), .. + }) => { + // Login succeeded! + self.logged_in = true; + device_info = info; + } + BcBody::ModernMsg(ModernMsg { + xml: None, binary: None, + }) => { + return Err(Error::AuthFailed) + } + _ => return Err(Error::UnintelligibleReply { + request: modern_login, + reply: modern_reply, + why: "Expected a DeviceInfo message back from login" + }) + } + + Ok(device_info) + } + + pub fn logout(&mut self) -> Result<()> { + if self.logged_in { + // TODO + } + self.logged_in = false; + Ok(()) + } +} + +#[derive(PartialEq, Eq)] +enum Md5Trunc { + ZeroLast, + Truncate +} + +fn md5_string(input: &str, trunc: Md5Trunc) -> String { + let mut md5 = format!("{:X}\0", md5::compute(input)); + md5.replace_range(31.., if trunc == Md5Trunc::Truncate { "" } else { "\0" }); + md5 +} + +#[test] +fn test_md5_string() { + use Md5Trunc::*; + assert_eq!(md5_string("admin", Truncate), "21232F297A57A5A743894A0E4A801FC"); + assert_eq!(md5_string("admin", ZeroLast), "21232F297A57A5A743894A0E4A801FC\0"); +} diff --git a/src/main.rs b/src/main.rs index a0d333e..6b6ddaa 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,7 +1,22 @@ #![allow(dead_code)] // while I'm still fleshing this out -mod bc; +use err_derive::Error; +use std::env::args; -fn main() { - println!("Hello, world!"); +mod bc; +mod bc_protocol; + +use bc_protocol::BcCamera; + +#[derive(Debug, Error)] +pub enum Error { + #[error(display="Communication error")] + ProtocolError(#[error(source)] bc_protocol::Error), +} + +fn main() -> Result<(), Error> { + let mut camera = BcCamera::new_with_addr(args().nth(1).unwrap())?; + camera.connect()?; + camera.login("admin", Some("12345678"))?; + Ok(()) }