From 6e325f8b9a262e8dbda11b3cd119668c5f8cea61 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Sun, 1 Aug 2021 08:41:29 +0700 Subject: [PATCH] Add logout model and use it during disconnect --- crates/core/src/bc/model.rs | 2 + crates/core/src/bc_protocol.rs | 31 ++++ crates/core/src/bc_protocol/login.rs | 257 +++++++++++++------------- crates/core/src/bc_protocol/logout.rs | 40 +++- 4 files changed, 202 insertions(+), 128 deletions(-) diff --git a/crates/core/src/bc/model.rs b/crates/core/src/bc/model.rs index cd985bd..977fc92 100644 --- a/crates/core/src/bc/model.rs +++ b/crates/core/src/bc/model.rs @@ -6,6 +6,8 @@ pub(super) const MAGIC_HEADER: u32 = 0xabcdef0; /// Login messages have this ID pub const MSG_ID_LOGIN: u32 = 1; +/// Logout messages have this ID +pub const MSG_ID_LOGOUT: u32 = 2; /// Video and Audio Streams messages have this ID pub const MSG_ID_VIDEO: u32 = 3; /// Version messages have this ID diff --git a/crates/core/src/bc_protocol.rs b/crates/core/src/bc_protocol.rs index 1ea49b4..1982b29 100644 --- a/crates/core/src/bc_protocol.rs +++ b/crates/core/src/bc_protocol.rs @@ -42,6 +42,21 @@ pub struct BcCamera { connection: Option, logged_in: bool, message_num: AtomicU16, + // Certain commands such as logout require the username/pass in plain text.... why....??? + credentials: Option, +} + +// Used for caching the credentials +#[derive(Clone)] +struct Credentials { + username: String, + password: Option, +} + +impl Credentials { + fn new(username: String, password: Option) -> Self { + Self { username, password } + } } impl Drop for BcCamera { @@ -90,6 +105,7 @@ impl BcCamera { message_num: AtomicU16::new(0), channel_id, logged_in: false, + credentials: None, }); } @@ -109,6 +125,21 @@ impl BcCamera { } self.connection = None; } + + // Certains commands like logout need the username and password + // this command will return it as a tuple of (Username, Option) + // This will only work after login + fn get_credentials(&self) -> &Option { + &self.credentials + } + // This is used to store the credentials it is called during login. + fn set_credentials(&mut self, username: String, password: Option) { + self.credentials = Some(Credentials::new(username, password)); + } + // This is used to clear the stored credentials it is called during logout. + fn clear_credentials(&mut self) { + self.credentials = None; + } } /// The Baichuan library has a very peculiar behavior where it always zeros the last byte. I diff --git a/crates/core/src/bc_protocol/login.rs b/crates/core/src/bc_protocol/login.rs index b6ff9dc..f8550fd 100644 --- a/crates/core/src/bc_protocol/login.rs +++ b/crates/core/src/bc_protocol/login.rs @@ -2,140 +2,143 @@ use super::{make_aes_key, md5_string, BcCamera, Error, Result, Truncate, ZeroLas use crate::bc::{model::*, xml::*}; impl BcCamera { - /// Will try to login to the camera. + /// Login to the camera. /// /// This should be called before most other commands pub fn login(&mut self, username: &str, password: Option<&str>) -> Result { - let connection = self - .connection - .as_ref() - .expect("Must be connected to log in"); - let sub_login = connection.subscribe(MSG_ID_LOGIN)?; - - // 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_else(|| EMPTY_LEGACY_PASSWORD.to_owned()); - - let legacy_login = Bc { - meta: BcMeta { - msg_id: MSG_ID_LOGIN, - channel_id: self.channel_id, - msg_num: self.new_message_num(), - stream_type: 0, - response_code: 0xdc03, - class: 0x6514, - }, - body: BcBody::LegacyMsg(LegacyMsg::LoginMsg { - username: md5_username, - password: md5_password, - }), - }; - - sub_login.send(legacy_login)?; - - let legacy_reply = sub_login.rx.recv_timeout(RX_TIMEOUT)?; - - let nonce; - match legacy_reply.body { - BcBody::ModernMsg(ModernMsg { - payload: - Some(BcPayloads::BcXml(BcXml { - encryption: Some(encryption), - .. - })), - .. - }) => { - nonce = encryption.nonce; - } - _ => { - return Err(Error::UnintelligibleReply { - 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::new_from_xml( - BcMeta { - msg_id: MSG_ID_LOGIN, - channel_id: self.channel_id, - msg_num: self.new_message_num(), - stream_type: 0, - response_code: 0, - class: 0x6414, - }, - BcXml { - login_user: Some(LoginUser { - version: xml_ver(), - user_name: md5_username, - password: md5_password, - user_ver: 1, - }), - login_net: Some(LoginNet::default()), - ..Default::default() - }, - ); - - sub_login.send(modern_login)?; - let modern_reply = sub_login.rx.recv_timeout(RX_TIMEOUT)?; - let device_info; - match modern_reply.body { - BcBody::ModernMsg(ModernMsg { - payload: - Some(BcPayloads::BcXml(BcXml { - device_info: Some(info), - .. - })), - .. - }) => { - // Login succeeded! - self.logged_in = true; - device_info = info; + // This { is here due to the connection and set_credentials both requiring a mutable borrow + { + let connection = self + .connection + .as_ref() + .expect("Must be connected to log in"); + let sub_login = connection.subscribe(MSG_ID_LOGIN)?; + + // 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_else(|| EMPTY_LEGACY_PASSWORD.to_owned()); + + let legacy_login = Bc { + meta: BcMeta { + msg_id: MSG_ID_LOGIN, + channel_id: self.channel_id, + msg_num: self.new_message_num(), + stream_type: 0, + response_code: 0xdc03, + class: 0x6514, + }, + body: BcBody::LegacyMsg(LegacyMsg::LoginMsg { + username: md5_username, + password: md5_password, + }), + }; + + sub_login.send(legacy_login)?; + + let legacy_reply = sub_login.rx.recv_timeout(RX_TIMEOUT)?; + + let nonce; + match legacy_reply.body { + BcBody::ModernMsg(ModernMsg { + payload: + Some(BcPayloads::BcXml(BcXml { + encryption: Some(encryption), + .. + })), + .. + }) => { + nonce = encryption.nonce; + } + _ => { + return Err(Error::UnintelligibleReply { + reply: legacy_reply, + why: "Expected an Encryption message back", + }) + } } - BcBody::ModernMsg(ModernMsg { - extension: None, - payload: None, - }) => return Err(Error::AuthFailed), - _ => { - return Err(Error::UnintelligibleReply { - reply: modern_reply, - why: "Expected a DeviceInfo message back from login", - }) + + // 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::new_from_xml( + BcMeta { + msg_id: MSG_ID_LOGIN, + channel_id: self.channel_id, + msg_num: self.new_message_num(), + stream_type: 0, + response_code: 0, + class: 0x6414, + }, + BcXml { + login_user: Some(LoginUser { + version: xml_ver(), + user_name: md5_username, + password: md5_password, + user_ver: 1, + }), + login_net: Some(LoginNet::default()), + ..Default::default() + }, + ); + + sub_login.send(modern_login)?; + let modern_reply = sub_login.rx.recv_timeout(RX_TIMEOUT)?; + + match modern_reply.body { + BcBody::ModernMsg(ModernMsg { + payload: + Some(BcPayloads::BcXml(BcXml { + device_info: Some(info), + .. + })), + .. + }) => { + // Login succeeded! + self.logged_in = true; + device_info = info; + } + BcBody::ModernMsg(ModernMsg { + extension: None, + payload: None, + }) => return Err(Error::AuthFailed), + _ => { + return Err(Error::UnintelligibleReply { + reply: modern_reply, + why: "Expected a DeviceInfo message back from login", + }) + } + } + + if let EncryptionProtocol::Aes(_) = connection.get_encrypted() { + // We setup the data for the AES key now + // as all subsequent communications will use it + let passwd = password.unwrap_or(""); + let full_key = make_aes_key(&nonce, passwd); + connection.set_encrypted(EncryptionProtocol::Aes(Some(full_key))); } } - - if let EncryptionProtocol::Aes(_) = connection.get_encrypted() { - // We setup the data for the AES key now - // as all subsequent communications will use it - let passwd = password.unwrap_or(""); - let full_key = make_aes_key(&nonce, passwd); - connection.set_encrypted(EncryptionProtocol::Aes(Some(full_key))); - } - + self.set_credentials(username.to_string(), password.map(|s| s.to_string())); Ok(device_info) } } diff --git a/crates/core/src/bc_protocol/logout.rs b/crates/core/src/bc_protocol/logout.rs index f963a23..0337ccf 100644 --- a/crates/core/src/bc_protocol/logout.rs +++ b/crates/core/src/bc_protocol/logout.rs @@ -1,11 +1,49 @@ use super::{BcCamera, Result}; +use crate::bc::{model::*, xml::*}; impl BcCamera { /// Logout from the camera pub fn logout(&mut self) -> Result<()> { if self.logged_in { - // TODO: Send message ID 2 + if let Some(credentials) = self.get_credentials() { + let connection = self + .connection + .as_ref() + .expect("Must be connected to log in"); + let sub_logout = connection.subscribe(MSG_ID_LOGOUT)?; + + let username = credentials.username.clone(); + let password = credentials + .password + .as_ref() + .cloned() + .unwrap_or_else(|| "".to_string()); + + let modern_logout = Bc::new_from_xml( + BcMeta { + msg_id: MSG_ID_LOGIN, + channel_id: self.channel_id, + msg_num: self.new_message_num(), + stream_type: 0, + response_code: 0, + class: 0x6414, + }, + BcXml { + login_user: Some(LoginUser { + version: xml_ver(), + user_name: username, + password, + user_ver: 1, + }), + login_net: Some(LoginNet::default()), + ..Default::default() + }, + ); + + sub_logout.send(modern_logout)?; + } } + self.clear_credentials(); self.logged_in = false; Ok(()) }