Bug fix and preperation for new encryption protocol

This commit is contained in:
QuantumEntangledAndy committed 2021-04-14 17:17:43 +07:00
1 parent 2e04405550
commit 772ba86156
9 files changed
+145 -73

No files matched your search

Generated
+12
View File
@@ -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",
+1
View File
@@ -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"
+23 -14
View File
@@ -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()));
+31 -7
View File
@@ -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<u32>,
}
#[atomic_enum]
#[derive(PartialEq)]
pub enum EncryptionProtocol {
Unencrypted = 0,
VersionOne,
VersionThree,
Unknown,
}
#[derive(Debug)]
pub struct BcContext {
pub(super) in_bin_mode: HashSet<u32>,
pub(super) is_encrypted: Arc<AtomicBool>,
// Arc<AtomicEncryptionProtocol> because it is shared between context
// and connection for deserialisation and serialistion respectivly
pub(super) encryption_protocol: Arc<AtomicEncryptionProtocol>,
}
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<AtomicBool>) {
self.is_encrypted = is_encrypted;
pub fn new_with_encryption_protocol(
encryption_protocol: Arc<AtomicEncryptionProtocol>,
) -> 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)
}
}
+32 -18
View File
@@ -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<W: Write>(&self, buf: W, encrypted: bool) -> Result<W, GenError> {
pub fn serialize<W: Write>(
&self,
buf: W,
encryption_protocol: EncryptionProtocol,
) -> Result<W, GenError> {
// 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<W: Write>(enc_offset: u32, xml: &Extension, encrypted: bool) -> impl SerializeFn<W> {
fn bc_ext<W: Write>(
enc_offset: u32,
xml: &Extension,
encryption_protocol: EncryptionProtocol,
) -> impl SerializeFn<W> {
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<W: Write>(enc_offset: u32, payload: &BcPayloads, encrypted: bool) -> impl SerializeFn<W> {
fn bc_payload<W: Write>(
enc_offset: u32,
payload: &BcPayloads,
encryption_protocol: EncryptionProtocol,
) -> impl SerializeFn<W> {
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<W: Write>(header: &BcHeader) -> impl SerializeFn<W> {
))
}
fn bc_legacy<'a, W: Write>(legacy: &'a LegacyMsg) -> impl SerializeFn<W> + 'a {
fn bc_legacy<W: Write>(legacy: &'_ LegacyMsg) -> impl SerializeFn<W> + '_ {
move |out: WriteContext<W>| {
use LegacyMsg::*;
match legacy {
+22 -6
View File
@@ -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<u8> {
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<u8> {
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]
+3 -10
View File
@@ -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<BcConnection>,
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<Never> {
pub fn start_video(&self, data_outs: &mut GstOutputs, stream_name: &str) -> Result<Never> {
let connection = self
.connection
.as_ref()
+20 -13
View File
@@ -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<Mutex<TcpStream>>,
subscribers: Arc<Mutex<BTreeMap<u32, Sender<Bc>>>>,
rx_thread: Option<JoinHandle<()>>,
is_encrypted: Arc<AtomicBool>,
// Arc<AtomicEncryptionProtocol> because it is shared between context
// and connection for deserialisation and serialistion respectivly
encryption_protocol: Arc<AtomicEncryptionProtocol>,
}
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(())
}
}
+1 -5
View File
@@ -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::<String>(),
paths.join(", ")
);