From 5fde4c680043a7175c2f1f6639df9587d2158425 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Thu, 2 Jul 2020 15:57:18 +0700 Subject: [PATCH 01/33] Add TLS --- Cargo.toml | 3 ++- src/config.rs | 16 ++++++++++++++++ src/gst.rs | 21 ++++++++++++++++++++- src/main.rs | 14 ++++++++++++-- 4 files changed, 50 insertions(+), 4 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 05645c1..602c79d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,10 +13,11 @@ crossbeam = "0.7" env_logger = "*" err-derive = "0.2" glib = "*" +gio = "0.8" gstreamer = "0.15" gstreamer-app = "0.15" gstreamer-rtsp = "0.15" -gstreamer-rtsp-server = "0.15" +gstreamer-rtsp-server = { version = "0.15", features = ["v1_12"]} lazy_static = "1.4" log = { version = "0.4" } indoc = "0.3" diff --git a/src/config.rs b/src/config.rs index 576ea99..37a58aa 100644 --- a/src/config.rs +++ b/src/config.rs @@ -8,6 +8,7 @@ use regex::Regex; lazy_static! { static ref RE_STREAM_FORM: Regex = Regex::new(r"^([hH]26[45]|[ \t]*[!].*)$").unwrap(); static ref RE_STREAM_SRC: Regex = Regex::new(r"^(mainStream|subStream|both)$").unwrap(); + static ref RE_TLS_CLIENT_AUTH: Regex = Regex::new(r"^(none|request|require)$").unwrap(); } #[derive(Debug, Deserialize, Validate, Clone)] @@ -21,6 +22,13 @@ pub struct Config { #[validate(range(min = 0, max = 65535, message = "Invalid port", code = "bind_port"))] #[serde(default = "default_bind_port")] pub bind_port: u16, + + #[serde(default = "default_certificate")] + pub certificate: String, + + #[validate(regex(path = "RE_TLS_CLIENT_AUTH", message = "Incorrect stream format", code = "format"))] + #[serde(default = "default_tls_client_auth")] + pub tls_client_auth: String, } #[derive(Debug, Deserialize, Validate, Clone)] @@ -59,3 +67,11 @@ fn default_format() -> String { fn default_stream() -> String { "both".to_string() } + +fn default_certificate() -> String { + "".to_string() +} + +fn default_tls_client_auth() -> String { + "none".to_string() +} diff --git a/src/gst.rs b/src/gst.rs index 525ccfe..b1cf9ac 100644 --- a/src/gst.rs +++ b/src/gst.rs @@ -7,10 +7,13 @@ use gstreamer::Bin; use gstreamer_app::AppSrc; //use gstreamer_rtsp::RTSPLowerTrans; use gstreamer_rtsp_server::prelude::*; +use gstreamer_rtsp::RTSPAuthMethod; use gstreamer_rtsp_server::{RTSPAuth, RTSPMediaFactory, RTSPServer as GstRTSPServer}; -use log::debug; +use log::{debug, info}; use std::io; use std::io::Write; +use std::fs; +use gio::{TlsCertificate,TlsAuthenticationMode}; type Result = std::result::Result; @@ -96,7 +99,23 @@ impl RtspServer { }); self.server.set_auth(auth.as_ref()); + Ok(()) + } + pub fn set_tls(&self, cert_file: &str, client_auth: TlsAuthenticationMode) -> Result<()> { + info!("Setting up TLS using {}", cert_file); + let auth = match self.server.get_auth() { + Some(x) => x, + None => RTSPAuth::new(), + }; + + let cert = TlsCertificate::new_from_pem(&fs::read_to_string(cert_file).expect("TLS file not found")).expect("Not a valid TLS certificate"); + auth.set_tls_certificate(Some(&cert)); + auth.set_tls_authentication_mode(client_auth); + auth.set_supported_methods(RTSPAuthMethod::None); + + + self.server.set_auth(Some(&auth)); Ok(()) } diff --git a/src/main.rs b/src/main.rs index ec7f9f1..485bf17 100644 --- a/src/main.rs +++ b/src/main.rs @@ -12,6 +12,7 @@ use std::io::Write; use std::time::Duration; use structopt::StructOpt; use validator::Validate; +use gio::TlsAuthenticationMode; mod cmdline; mod config; @@ -76,12 +77,21 @@ fn main() -> Result<(), Error> { let rtsp = &RtspServer::new(); + if ! config.certificate.is_empty() { + let tls_client_auth = match &config.tls_client_auth as &str { + "request" => TlsAuthenticationMode::Requested, + "require" => TlsAuthenticationMode::Required, + "none"|_ => TlsAuthenticationMode::None, + }; + rtsp.set_tls(&config.certificate, tls_client_auth).expect("Failed to set up TLS"); + } + + crossbeam::scope(|s| { for camera in config.cameras { s.spawn(move |_| { // TODO handle these errors - let cam_format :&str = &camera.format; - let stream_format = match cam_format { + let stream_format = match &camera.format as &str { "h264"|"H264" => StreamFormat::H264, "h265"|"H265" => StreamFormat::H265, custom_format @ _ => StreamFormat::Custom(custom_format.to_string()) From a9a0048d7882fcc1295228d85c520d0cc712d84b Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Fri, 3 Jul 2020 07:49:41 +0700 Subject: [PATCH 02/33] Added basic user auth --- Cargo.toml | 2 +- src/config.rs | 14 ++++++++++ src/gst.rs | 71 +++++++++++++++++++++++++++++++++------------------ src/main.rs | 18 ++++++------- 4 files changed, 70 insertions(+), 35 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 602c79d..2d211ec 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,7 +17,7 @@ gio = "0.8" gstreamer = "0.15" gstreamer-app = "0.15" gstreamer-rtsp = "0.15" -gstreamer-rtsp-server = { version = "0.15", features = ["v1_12"]} +gstreamer-rtsp-server = { version = "0.15", features = ["v1_12", "v1_14"]} lazy_static = "1.4" log = { version = "0.4" } indoc = "0.3" diff --git a/src/config.rs b/src/config.rs index 37a58aa..a96550d 100644 --- a/src/config.rs +++ b/src/config.rs @@ -26,6 +26,12 @@ pub struct Config { #[serde(default = "default_certificate")] pub certificate: String, + #[serde(default = "default_username")] + pub username: String, + + #[serde(default = "default_password")] + pub password: String, + #[validate(regex(path = "RE_TLS_CLIENT_AUTH", message = "Incorrect stream format", code = "format"))] #[serde(default = "default_tls_client_auth")] pub tls_client_auth: String, @@ -75,3 +81,11 @@ fn default_certificate() -> String { fn default_tls_client_auth() -> String { "none".to_string() } + +fn default_username() -> String { + "".to_string() +} + +fn default_password() -> String { + "".to_string() +} diff --git a/src/gst.rs b/src/gst.rs index b1cf9ac..d3a4e2c 100644 --- a/src/gst.rs +++ b/src/gst.rs @@ -3,12 +3,12 @@ pub use self::maybe_app_src::MaybeAppSrc; use gstreamer::prelude::Cast; -use gstreamer::Bin; +use gstreamer::{Bin,Structure}; use gstreamer_app::AppSrc; //use gstreamer_rtsp::RTSPLowerTrans; use gstreamer_rtsp_server::prelude::*; use gstreamer_rtsp::RTSPAuthMethod; -use gstreamer_rtsp_server::{RTSPAuth, RTSPMediaFactory, RTSPServer as GstRTSPServer}; +use gstreamer_rtsp_server::{RTSPAuth, RTSPToken, RTSPMediaFactory, RTSP_TOKEN_MEDIA_FACTORY_ROLE, RTSP_PERM_MEDIA_FACTORY_ACCESS, RTSP_PERM_MEDIA_FACTORY_CONSTRUCT, RTSPServer as GstRTSPServer}; use log::{debug, info}; use std::io; use std::io::Write; @@ -48,6 +48,17 @@ impl RtspServer { }; let factory = RTSPMediaFactory::new(); + + factory.add_role_from_structure( + &Structure::new( + "watcher", + &[ + (*RTSP_PERM_MEDIA_FACTORY_ACCESS, &true), + (*RTSP_PERM_MEDIA_FACTORY_CONSTRUCT, &true), + ] + ) + ); + //factory.set_protocols(RTSPLowerTrans::TCP); factory.set_launch(&format!("{}{}{}{}", "( ", @@ -85,40 +96,50 @@ impl RtspServer { Ok(maybe_app_src) } - pub fn set_credentials(&mut self, user_pass: Option<(&str, &str)>) -> Result<()> { - let auth = user_pass.map(|(user, pass)| { - let auth = RTSPAuth::new(); - /* - let perm = RTSPToken::new( - ... - ); - auth.add_basic(RTSPAuth::make_basic(user, pass).as_str(), &perm); - */ - // TODO TLS https://thiblahute.github.io/GStreamer-doc/gst-rtsp-server-1.0/rtsp-server.html?gi-language=c - auth - }); - - self.server.set_auth(auth.as_ref()); - Ok(()) - } - - pub fn set_tls(&self, cert_file: &str, client_auth: TlsAuthenticationMode) -> Result<()> { - info!("Setting up TLS using {}", cert_file); + pub fn set_credentials(&self, user :&str, pass :&str) -> Result<()> { let auth = match self.server.get_auth() { Some(x) => x, None => RTSPAuth::new(), }; - let cert = TlsCertificate::new_from_pem(&fs::read_to_string(cert_file).expect("TLS file not found")).expect("Not a valid TLS certificate"); - auth.set_tls_certificate(Some(&cert)); - auth.set_tls_authentication_mode(client_auth); - auth.set_supported_methods(RTSPAuthMethod::None); + if ! user.is_empty() && ! pass.is_empty() { + info!("Setting credentials for user {}", user); + debug!("Password is {}", pass); + let token = RTSPToken::new(&[(*RTSP_TOKEN_MEDIA_FACTORY_ROLE, &"watcher")]); + let basic = RTSPAuth::make_basic(user, pass); + auth.set_supported_methods(RTSPAuthMethod::Basic); + auth.add_basic(basic.as_str(), &token); + // Now we have basic auth we stop others from watching + let mut token = RTSPToken::new_empty(); + auth.set_default_token(Some(&mut token)); + } else { + let mut token = RTSPToken::new(&[(*RTSP_TOKEN_MEDIA_FACTORY_ROLE, &"watcher")]); + auth.set_default_token(Some(&mut token)); //By default anyone can watch if we don't turn on basic + } self.server.set_auth(Some(&auth)); Ok(()) } + pub fn set_tls(&self, cert_file: &str, client_auth: TlsAuthenticationMode) -> Result<()> { + if ! cert_file.is_empty() { + info!("Setting up TLS using {}", cert_file); + let auth = match self.server.get_auth() { + Some(x) => x, + None => RTSPAuth::new(), + }; + + let cert = TlsCertificate::new_from_pem(&fs::read_to_string(cert_file).expect("TLS file not found")).expect("Not a valid TLS certificate"); + auth.set_tls_certificate(Some(&cert)); + auth.set_tls_authentication_mode(client_auth); + auth.set_supported_methods(RTSPAuthMethod::None); + + self.server.set_auth(Some(&auth)); + } + Ok(()) + } + pub fn run(&self, bind_addr: &str, bind_port: u16) { self.server.set_address(bind_addr); self.server.set_service(&format!("{}", bind_port)); diff --git a/src/main.rs b/src/main.rs index 485bf17..b426dbc 100644 --- a/src/main.rs +++ b/src/main.rs @@ -77,15 +77,15 @@ fn main() -> Result<(), Error> { let rtsp = &RtspServer::new(); - if ! config.certificate.is_empty() { - let tls_client_auth = match &config.tls_client_auth as &str { - "request" => TlsAuthenticationMode::Requested, - "require" => TlsAuthenticationMode::Required, - "none"|_ => TlsAuthenticationMode::None, - }; - rtsp.set_tls(&config.certificate, tls_client_auth).expect("Failed to set up TLS"); - } - + let tls_client_auth = match &config.tls_client_auth as &str { + "request" => TlsAuthenticationMode::Requested, + "require" => TlsAuthenticationMode::Required, + "none"|_ => TlsAuthenticationMode::None, + }; + rtsp.set_tls(&config.certificate, tls_client_auth).expect("Failed to set up TLS"); + + rtsp.set_credentials(&config.username, &config.password).expect("Failed to set up users."); + crossbeam::scope(|s| { for camera in config.cameras { From b5e8cb8ff77f2c5f49474a333be9fafea5a0d487 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Fri, 3 Jul 2020 08:29:05 +0700 Subject: [PATCH 03/33] Updated readme to include TLS and basic auth. --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index b26233c..413a6f5 100644 --- a/README.md +++ b/README.md @@ -70,6 +70,10 @@ By default the HD stream is mounted at `name` and at `name/mainStream` and the S By default Neolink serves on all IP addresses on port 8554. You can modify this by changing the `bind` and the `bind_port` parameter. +Use can enable `rtsps` (TLS) by adding a `certificate = "/path/to/pem"` to the config. This pem should contain by the certificate and the key used for the server. If TLS is enabled all connections must use `rtsps`. Use can also control client side TLS with the config option `tls_client_auth = "none|request|require"`, in this case the client should present a certificate signed by the server's CA, this is disabled by default. + +Use can enable basic authentication by adding the configuration option `username = "someone"` and `password = "somepass"`. Both username and password must be set for this to work. + You can change the Neolink log level by setting the `RUST_LOG` environment variable (not in the configuration file) to one of `error`, `warn`, `info`, `debug`, or `trace`: ``` From 296c281f152889733e3df90c4c408a40050d3685 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Fri, 3 Jul 2020 11:42:56 +0700 Subject: [PATCH 04/33] Added more control over authourised users. --- src/config.rs | 29 +++++++++++++++----------- src/gst.rs | 53 ++++++++++++++++++++++++++---------------------- src/main.rs | 56 +++++++++++++++++++++++++++++++++++++++++---------- 3 files changed, 91 insertions(+), 47 deletions(-) diff --git a/src/config.rs b/src/config.rs index a96550d..2b155b6 100644 --- a/src/config.rs +++ b/src/config.rs @@ -26,15 +26,12 @@ pub struct Config { #[serde(default = "default_certificate")] pub certificate: String, - #[serde(default = "default_username")] - pub username: String, - - #[serde(default = "default_password")] - pub password: String, - #[validate(regex(path = "RE_TLS_CLIENT_AUTH", message = "Incorrect stream format", code = "format"))] #[serde(default = "default_tls_client_auth")] pub tls_client_auth: String, + + #[validate] + pub users: Vec, } #[derive(Debug, Deserialize, Validate, Clone)] @@ -56,6 +53,18 @@ pub struct CameraConfig { #[validate(regex(path = "RE_STREAM_SRC", message = "Incorrect stream source", code = "stream"))] #[serde(default = "default_stream")] pub stream: String, + + #[serde(default = "default_permitted_users")] + pub permitted_users: Vec, +} + +#[derive(Debug, Deserialize, Validate, Clone)] +pub struct UserConfig { + #[serde(alias = "username")] + pub name: String, + + #[serde(alias = "password")] + pub pass: String, } fn default_bind_addr() -> String { @@ -82,10 +91,6 @@ fn default_tls_client_auth() -> String { "none".to_string() } -fn default_username() -> String { - "".to_string() -} - -fn default_password() -> String { - "".to_string() +fn default_permitted_users() -> Vec { + vec!["anyone".to_string()] } diff --git a/src/gst.rs b/src/gst.rs index 763d73f..9bc8893 100644 --- a/src/gst.rs +++ b/src/gst.rs @@ -35,7 +35,7 @@ impl RtspServer { } } - pub fn add_stream(&self, names: &[&str], stream_format: &StreamFormat) -> Result { + pub fn add_stream(&self, names: &[&str], stream_format: &StreamFormat, permitted_users: &Vec) -> Result { let mounts = self .server .get_mount_points() @@ -49,15 +49,17 @@ impl RtspServer { let factory = RTSPMediaFactory::new(); - factory.add_role_from_structure( - &Structure::new( - "watcher", - &[ - (*RTSP_PERM_MEDIA_FACTORY_ACCESS, &true), - (*RTSP_PERM_MEDIA_FACTORY_CONSTRUCT, &true), - ] - ) - ); + for permitted_user in permitted_users { + factory.add_role_from_structure( + &Structure::new( + &permitted_user, + &[ + (*RTSP_PERM_MEDIA_FACTORY_ACCESS, &true), + (*RTSP_PERM_MEDIA_FACTORY_CONSTRUCT, &true), + ] + ) + ); + } //factory.set_protocols(RTSPLowerTrans::TCP); factory.set_launch(&format!("{}{}{}{}", @@ -98,27 +100,30 @@ impl RtspServer { Ok(maybe_app_src) } - pub fn set_credentials(&self, user :&str, pass :&str) -> Result<()> { + pub fn set_credentials(&self, credentials :&Vec<(&String, &String)>) -> Result<()> { let auth = match self.server.get_auth() { Some(x) => x, None => RTSPAuth::new(), }; - if ! user.is_empty() && ! pass.is_empty() { - info!("Setting credentials for user {}", user); - debug!("Password is {}", pass); - let token = RTSPToken::new(&[(*RTSP_TOKEN_MEDIA_FACTORY_ROLE, &"watcher")]); - let basic = RTSPAuth::make_basic(user, pass); - auth.set_supported_methods(RTSPAuthMethod::Basic); - auth.add_basic(basic.as_str(), &token); + auth.set_supported_methods(RTSPAuthMethod::Basic); - // Now we have basic auth we stop others from watching - let mut token = RTSPToken::new_empty(); - auth.set_default_token(Some(&mut token)); - } else { - let mut token = RTSPToken::new(&[(*RTSP_TOKEN_MEDIA_FACTORY_ROLE, &"watcher")]); - auth.set_default_token(Some(&mut token)); //By default anyone can watch if we don't turn on basic + for credentials in credentials { + let (user, pass) = credentials; + if ! user.is_empty() && ! pass.is_empty() { + info!("Setting credentials for user {}", user); + debug!("Password is {}", pass); + let token = RTSPToken::new(&[(*RTSP_TOKEN_MEDIA_FACTORY_ROLE, user)]); + let basic = RTSPAuth::make_basic(user, pass); + auth.add_basic(basic.as_str(), &token); + + // Now we have basic auth we stop others from watching + let mut token = RTSPToken::new_empty(); + auth.set_default_token(Some(&mut token)); + } } + let mut un_authtoken = RTSPToken::new(&[(*RTSP_TOKEN_MEDIA_FACTORY_ROLE, &"unauth")]); + auth.set_default_token(Some(&mut un_authtoken)); self.server.set_auth(Some(&auth)); Ok(()) diff --git a/src/main.rs b/src/main.rs index ab48a79..d859f67 100644 --- a/src/main.rs +++ b/src/main.rs @@ -19,7 +19,7 @@ mod cmdline; mod config; use cmdline::Opt; -use config::{CameraConfig, Config}; +use config::{UserConfig, CameraConfig, Config}; #[derive(Debug, Error)] pub enum Error { @@ -52,15 +52,9 @@ fn main() -> Result<(), Error> { let rtsp = &RtspServer::new(); - let tls_client_auth = match &config.tls_client_auth as &str { - "request" => TlsAuthenticationMode::Requested, - "require" => TlsAuthenticationMode::Required, - "none"|_ => TlsAuthenticationMode::None, - }; - rtsp.set_tls(&config.certificate, tls_client_auth).expect("Failed to set up TLS"); - - rtsp.set_credentials(&config.username, &config.password).expect("Failed to set up users."); + set_up_tls(&config, &rtsp); + set_up_users(&config.users, &rtsp); crossbeam::scope(|s| { for camera in config.cameras { @@ -69,6 +63,7 @@ fn main() -> Result<(), Error> { "h265"|"H265" => StreamFormat::H265, custom_format @ _ => StreamFormat::Custom(custom_format.to_string()) }; + let permitted_user = get_permitted_users(&config.users, &camera.permitted_users); // Let subthreads share the camera object; in principle I think they could share // the object as it sits in the config.cameras block, but I have not figured out the @@ -81,13 +76,13 @@ fn main() -> Result<(), Error> { &arc_cam.name, &*format!("{}/mainStream", arc_cam.name), ]; - let mut output = rtsp.add_stream(paths, &stream_format).unwrap(); + let mut output = rtsp.add_stream(paths, &stream_format, &permitted_user).unwrap(); let main_camera = arc_cam.clone(); s.spawn(move |_| camera_loop(&*main_camera, &mut output)); } if arc_cam.stream == "both" || arc_cam.stream == "subStream" { let paths = &[&*format!("{}/subStream", arc_cam.name)]; - let mut output = rtsp.add_stream(paths, &stream_format).unwrap(); + let mut output = rtsp.add_stream(paths, &stream_format, &permitted_user).unwrap(); let sub_camera = arc_cam.clone(); s.spawn(move |_| camera_loop(&*sub_camera, &mut output)); } @@ -138,6 +133,45 @@ struct CameraErr { err: neolink::Error, } +fn set_up_tls(config: &Config, rtsp: &RtspServer) { + let tls_client_auth = match &config.tls_client_auth as &str { + "request" => TlsAuthenticationMode::Requested, + "require" => TlsAuthenticationMode::Required, + "none"|_ => TlsAuthenticationMode::None, + }; + rtsp.set_tls(&config.certificate, tls_client_auth).expect("Failed to set up TLS"); +} + +fn set_up_users(users: &Vec, rtsp: &RtspServer) { + // Setting up users + let mut credentials = vec![]; + for user in users { + credentials.push((&user.name, &user.pass)); + } + rtsp.set_credentials(&credentials).expect("Failed to set up users."); +} + +fn get_permitted_users(users: &Vec, current_permitted_users: &Vec) -> Vec { + // This is required to handle the special case of "anyone" + // Special set up of "anyone" + // If in the camera config there is the user anyone + // Then we add all users to the cameras config. including unauth + let mut new_permitted_users = vec![]; + if current_permitted_users.contains(&"anyone".to_string()) { + for credentials in users { + let user: &str = &credentials.name; + new_permitted_users.push(user.to_string()); + } + new_permitted_users.push("unauth".to_string()); + } else { + new_permitted_users.append(&mut current_permitted_users.clone()); + } + new_permitted_users.sort(); + new_permitted_users.dedup(); + + new_permitted_users +} + fn camera_main(camera_config: &CameraConfig, output: &mut dyn Write) -> Result { let mut connected = false; (|| { From 02642c263863b1b43dcab80bc46a33a37472c543 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Fri, 3 Jul 2020 11:44:01 +0700 Subject: [PATCH 05/33] Print username only in debug mode --- README.md | 2 +- src/gst.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index a97a122..becce0d 100644 --- a/README.md +++ b/README.md @@ -73,7 +73,7 @@ You may also need to use `h264` format while using the SD stream. By default Neolink serves on all IP addresses on port 8554. You can modify this by changing the `bind` and the `bind_port` parameter. -Use can enable `rtsps` (TLS) by adding a `certificate = "/path/to/pem"` to the config. This pem should contain by the certificate and the key used for the server. If TLS is enabled all connections must use `rtsps`. Use can also control client side TLS with the config option `tls_client_auth = "none|request|require"`, in this case the client should present a certificate signed by the server's CA, this is disabled by default. +Use can enable `rtsps` (TLS) by adding a `certificate = "/path/to/pem"` to the config. This pem should contain by the certificate and the key used for the server. If TLS is enabled all connections must use `rtsps`. You can also control client side TLS with the config option `tls_client_auth = "none|request|require"`, in this case the client should present a certificate signed by the server's CA, this is disabled by default. Use can enable basic authentication by adding the configuration option `username = "someone"` and `password = "somepass"`. Both username and password must be set for this to work. diff --git a/src/gst.rs b/src/gst.rs index 763d73f..8f7576a 100644 --- a/src/gst.rs +++ b/src/gst.rs @@ -105,7 +105,7 @@ impl RtspServer { }; if ! user.is_empty() && ! pass.is_empty() { - info!("Setting credentials for user {}", user); + debug!("Setting credentials for user {}", user); debug!("Password is {}", pass); let token = RTSPToken::new(&[(*RTSP_TOKEN_MEDIA_FACTORY_ROLE, &"watcher")]); let basic = RTSPAuth::make_basic(user, pass); From 3a71c7e65164a61ae4a05bbc70e9f12efed17a24 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Fri, 3 Jul 2020 11:46:52 +0700 Subject: [PATCH 06/33] Use .unwrap_or_else with getting the auth from gst --- src/gst.rs | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/src/gst.rs b/src/gst.rs index 8f7576a..abefd7d 100644 --- a/src/gst.rs +++ b/src/gst.rs @@ -99,10 +99,7 @@ impl RtspServer { } pub fn set_credentials(&self, user :&str, pass :&str) -> Result<()> { - let auth = match self.server.get_auth() { - Some(x) => x, - None => RTSPAuth::new(), - }; + let auth = self.server.get_auth().unwrap_or_else(RTSPAuth::new()); if ! user.is_empty() && ! pass.is_empty() { debug!("Setting credentials for user {}", user); @@ -127,10 +124,7 @@ impl RtspServer { pub fn set_tls(&self, cert_file: &str, client_auth: TlsAuthenticationMode) -> Result<()> { if ! cert_file.is_empty() { info!("Setting up TLS using {}", cert_file); - let auth = match self.server.get_auth() { - Some(x) => x, - None => RTSPAuth::new(), - }; + let auth = self.server.get_auth().unwrap_or_else(RTSPAuth::new()); let cert = TlsCertificate::new_from_pem(&fs::read_to_string(cert_file).expect("TLS file not found")).expect("Not a valid TLS certificate"); auth.set_tls_certificate(Some(&cert)); From 7eed4a037ac3a238e1f1fcb19876037d498f0529 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Fri, 3 Jul 2020 11:48:33 +0700 Subject: [PATCH 07/33] Print using TLS only on debug level --- src/gst.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/gst.rs b/src/gst.rs index abefd7d..02bd375 100644 --- a/src/gst.rs +++ b/src/gst.rs @@ -9,7 +9,7 @@ use gstreamer_app::AppSrc; use gstreamer_rtsp_server::prelude::*; use gstreamer_rtsp::RTSPAuthMethod; use gstreamer_rtsp_server::{RTSPAuth, RTSPToken, RTSPMediaFactory, RTSP_TOKEN_MEDIA_FACTORY_ROLE, RTSP_PERM_MEDIA_FACTORY_ACCESS, RTSP_PERM_MEDIA_FACTORY_CONSTRUCT, RTSPServer as GstRTSPServer}; -use log::{debug, info}; +use log::debug; use std::io; use std::io::Write; use std::fs; @@ -123,7 +123,7 @@ impl RtspServer { pub fn set_tls(&self, cert_file: &str, client_auth: TlsAuthenticationMode) -> Result<()> { if ! cert_file.is_empty() { - info!("Setting up TLS using {}", cert_file); + debug!("Setting up TLS using {}", cert_file); let auth = self.server.get_auth().unwrap_or_else(RTSPAuth::new()); let cert = TlsCertificate::new_from_pem(&fs::read_to_string(cert_file).expect("TLS file not found")).expect("Not a valid TLS certificate"); From 418f8a0fa81f08f8435fab7b2b7d42222629b883 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Fri, 3 Jul 2020 11:49:23 +0700 Subject: [PATCH 08/33] Use new from file when loading the pem --- src/gst.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/gst.rs b/src/gst.rs index 02bd375..d8cd28f 100644 --- a/src/gst.rs +++ b/src/gst.rs @@ -126,7 +126,7 @@ impl RtspServer { debug!("Setting up TLS using {}", cert_file); let auth = self.server.get_auth().unwrap_or_else(RTSPAuth::new()); - let cert = TlsCertificate::new_from_pem(&fs::read_to_string(cert_file).expect("TLS file not found")).expect("Not a valid TLS certificate"); + let cert = TlsCertificate::new_from_file(cert_file).expect("Not a valid TLS certificate or not found."); auth.set_tls_certificate(Some(&cert)); auth.set_tls_authentication_mode(client_auth); auth.set_supported_methods(RTSPAuthMethod::None); From 0317137616a81c6a3da450662956782e3b66bf41 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Fri, 3 Jul 2020 11:52:55 +0700 Subject: [PATCH 09/33] Use unreachable for the client tls --- src/main.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index ab48a79..8242617 100644 --- a/src/main.rs +++ b/src/main.rs @@ -55,7 +55,8 @@ fn main() -> Result<(), Error> { let tls_client_auth = match &config.tls_client_auth as &str { "request" => TlsAuthenticationMode::Requested, "require" => TlsAuthenticationMode::Required, - "none"|_ => TlsAuthenticationMode::None, + "none" => TlsAuthenticationMode::None, + _ => unreachable!(), }; rtsp.set_tls(&config.certificate, tls_client_auth).expect("Failed to set up TLS"); From 1b68d73399c487edbadb36c437beed78bed4edaf Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Fri, 3 Jul 2020 12:21:54 +0700 Subject: [PATCH 10/33] Using Options for basic auth --- src/config.rs | 12 ++++++------ src/gst.rs | 36 +++++++++++++++++++----------------- src/main.rs | 8 +++++++- 3 files changed, 32 insertions(+), 24 deletions(-) diff --git a/src/config.rs b/src/config.rs index a96550d..199d91d 100644 --- a/src/config.rs +++ b/src/config.rs @@ -27,10 +27,10 @@ pub struct Config { pub certificate: String, #[serde(default = "default_username")] - pub username: String, + pub username: Option, #[serde(default = "default_password")] - pub password: String, + pub password: Option, #[validate(regex(path = "RE_TLS_CLIENT_AUTH", message = "Incorrect stream format", code = "format"))] #[serde(default = "default_tls_client_auth")] @@ -82,10 +82,10 @@ fn default_tls_client_auth() -> String { "none".to_string() } -fn default_username() -> String { - "".to_string() +fn default_username() -> Option { + None } -fn default_password() -> String { - "".to_string() +fn default_password() -> Option { + None } diff --git a/src/gst.rs b/src/gst.rs index d8cd28f..0c20234 100644 --- a/src/gst.rs +++ b/src/gst.rs @@ -12,7 +12,6 @@ use gstreamer_rtsp_server::{RTSPAuth, RTSPToken, RTSPMediaFactory, RTSP_TOKEN_ME use log::debug; use std::io; use std::io::Write; -use std::fs; use gio::{TlsCertificate,TlsAuthenticationMode}; type Result = std::result::Result; @@ -98,23 +97,26 @@ impl RtspServer { Ok(maybe_app_src) } - pub fn set_credentials(&self, user :&str, pass :&str) -> Result<()> { - let auth = self.server.get_auth().unwrap_or_else(RTSPAuth::new()); + pub fn set_credentials(&self, user_pass: Option<(&str, &str)>) -> Result<()> { + let auth = self.server.get_auth().unwrap_or_else(|| RTSPAuth::new()); - if ! user.is_empty() && ! pass.is_empty() { - debug!("Setting credentials for user {}", user); - debug!("Password is {}", pass); - let token = RTSPToken::new(&[(*RTSP_TOKEN_MEDIA_FACTORY_ROLE, &"watcher")]); - let basic = RTSPAuth::make_basic(user, pass); - auth.set_supported_methods(RTSPAuthMethod::Basic); - auth.add_basic(basic.as_str(), &token); + match user_pass { + Some((user, pass)) => { + debug!("Setting credentials for user {}", user); + debug!("Password is {}", pass); + let token = RTSPToken::new(&[(*RTSP_TOKEN_MEDIA_FACTORY_ROLE, &"watcher")]); + let basic = RTSPAuth::make_basic(user, pass); + auth.set_supported_methods(RTSPAuthMethod::Basic); + auth.add_basic(basic.as_str(), &token); - // Now we have basic auth we stop others from watching - let mut token = RTSPToken::new_empty(); - auth.set_default_token(Some(&mut token)); - } else { - let mut token = RTSPToken::new(&[(*RTSP_TOKEN_MEDIA_FACTORY_ROLE, &"watcher")]); - auth.set_default_token(Some(&mut token)); //By default anyone can watch if we don't turn on basic + // Now we have basic auth we stop others from watching + let mut token = RTSPToken::new_empty(); + auth.set_default_token(Some(&mut token)); + }, + None => { + let mut token = RTSPToken::new(&[(*RTSP_TOKEN_MEDIA_FACTORY_ROLE, &"watcher")]); + auth.set_default_token(Some(&mut token)); //By default anyone can watch if we don't turn on basic + } } self.server.set_auth(Some(&auth)); @@ -124,7 +126,7 @@ impl RtspServer { pub fn set_tls(&self, cert_file: &str, client_auth: TlsAuthenticationMode) -> Result<()> { if ! cert_file.is_empty() { debug!("Setting up TLS using {}", cert_file); - let auth = self.server.get_auth().unwrap_or_else(RTSPAuth::new()); + let auth = self.server.get_auth().unwrap_or_else(|| RTSPAuth::new()); let cert = TlsCertificate::new_from_file(cert_file).expect("Not a valid TLS certificate or not found."); auth.set_tls_certificate(Some(&cert)); diff --git a/src/main.rs b/src/main.rs index 8242617..a6f447f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -60,7 +60,13 @@ fn main() -> Result<(), Error> { }; rtsp.set_tls(&config.certificate, tls_client_auth).expect("Failed to set up TLS"); - rtsp.set_credentials(&config.username, &config.password).expect("Failed to set up users."); + let name = &config.username; + let pass = &config.password; + let user_pass = match (name, pass) { + (Some(name), Some(pass)) => Some((&name as &str, &pass as &str)), + _ => None, + }; + rtsp.set_credentials(user_pass).expect("Failed to set up users."); crossbeam::scope(|s| { From 5ff211747ee607a433ff6dc55f7798f835f7b743 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Fri, 3 Jul 2020 12:38:09 +0700 Subject: [PATCH 11/33] Using option when setting up TLS --- src/config.rs | 6 +++--- src/gst.rs | 16 +++++++--------- src/main.rs | 5 ++++- 3 files changed, 14 insertions(+), 13 deletions(-) diff --git a/src/config.rs b/src/config.rs index 199d91d..f7eb36d 100644 --- a/src/config.rs +++ b/src/config.rs @@ -24,7 +24,7 @@ pub struct Config { pub bind_port: u16, #[serde(default = "default_certificate")] - pub certificate: String, + pub certificate: Option, #[serde(default = "default_username")] pub username: Option, @@ -74,8 +74,8 @@ fn default_stream() -> String { "both".to_string() } -fn default_certificate() -> String { - "".to_string() +fn default_certificate() -> Option { + None } fn default_tls_client_auth() -> String { diff --git a/src/gst.rs b/src/gst.rs index 0c20234..c3edc91 100644 --- a/src/gst.rs +++ b/src/gst.rs @@ -124,17 +124,15 @@ impl RtspServer { } pub fn set_tls(&self, cert_file: &str, client_auth: TlsAuthenticationMode) -> Result<()> { - if ! cert_file.is_empty() { - debug!("Setting up TLS using {}", cert_file); - let auth = self.server.get_auth().unwrap_or_else(|| RTSPAuth::new()); + debug!("Setting up TLS using {}", cert_file); + let auth = self.server.get_auth().unwrap_or_else(|| RTSPAuth::new()); - let cert = TlsCertificate::new_from_file(cert_file).expect("Not a valid TLS certificate or not found."); - auth.set_tls_certificate(Some(&cert)); - auth.set_tls_authentication_mode(client_auth); - auth.set_supported_methods(RTSPAuthMethod::None); + let cert = TlsCertificate::new_from_file(&cert_file).expect("Not a valid TLS certificate or not found."); + auth.set_tls_certificate(Some(&cert)); + auth.set_tls_authentication_mode(client_auth); + auth.set_supported_methods(RTSPAuthMethod::None); - self.server.set_auth(Some(&auth)); - } + self.server.set_auth(Some(&auth)); Ok(()) } diff --git a/src/main.rs b/src/main.rs index a6f447f..5e9a945 100644 --- a/src/main.rs +++ b/src/main.rs @@ -58,7 +58,10 @@ fn main() -> Result<(), Error> { "none" => TlsAuthenticationMode::None, _ => unreachable!(), }; - rtsp.set_tls(&config.certificate, tls_client_auth).expect("Failed to set up TLS"); + + if let Some(cert_path) = &config.certificate { + rtsp.set_tls(&cert_path, tls_client_auth).expect("Failed to set up TLS"); + } let name = &config.username; let pass = &config.password; From 9a6d8572b4abaf5b779300271578ed7d048be740 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Fri, 3 Jul 2020 12:58:13 +0700 Subject: [PATCH 12/33] Changed handelling of getting user path --- src/gst.rs | 29 +++++++++++++---------------- 1 file changed, 13 insertions(+), 16 deletions(-) diff --git a/src/gst.rs b/src/gst.rs index c3edc91..1ab6573 100644 --- a/src/gst.rs +++ b/src/gst.rs @@ -100,23 +100,20 @@ impl RtspServer { pub fn set_credentials(&self, user_pass: Option<(&str, &str)>) -> Result<()> { let auth = self.server.get_auth().unwrap_or_else(|| RTSPAuth::new()); - match user_pass { - Some((user, pass)) => { - debug!("Setting credentials for user {}", user); - debug!("Password is {}", pass); - let token = RTSPToken::new(&[(*RTSP_TOKEN_MEDIA_FACTORY_ROLE, &"watcher")]); - let basic = RTSPAuth::make_basic(user, pass); - auth.set_supported_methods(RTSPAuthMethod::Basic); - auth.add_basic(basic.as_str(), &token); + if let Some((user, pass)) = user_pass { + debug!("Setting credentials for user {}", user); + debug!("Password is {}", pass); + let token = RTSPToken::new(&[(*RTSP_TOKEN_MEDIA_FACTORY_ROLE, &"watcher")]); + let basic = RTSPAuth::make_basic(user, pass); + auth.set_supported_methods(RTSPAuthMethod::Basic); + auth.add_basic(basic.as_str(), &token); - // Now we have basic auth we stop others from watching - let mut token = RTSPToken::new_empty(); - auth.set_default_token(Some(&mut token)); - }, - None => { - let mut token = RTSPToken::new(&[(*RTSP_TOKEN_MEDIA_FACTORY_ROLE, &"watcher")]); - auth.set_default_token(Some(&mut token)); //By default anyone can watch if we don't turn on basic - } + // Now we have basic auth we stop others from watching + let mut token = RTSPToken::new_empty(); + auth.set_default_token(Some(&mut token)); + } else { + let mut token = RTSPToken::new(&[(*RTSP_TOKEN_MEDIA_FACTORY_ROLE, &"watcher")]); + auth.set_default_token(Some(&mut token)); //By default anyone can watch if we don't turn on basic } self.server.set_auth(Some(&auth)); From fc802c873ad4d4abda59fec83aad034d826908b5 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Fri, 3 Jul 2020 13:25:32 +0700 Subject: [PATCH 13/33] Seperate reading and parsing cert files for better error handlling --- src/gst.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/gst.rs b/src/gst.rs index 1ab6573..b8bb540 100644 --- a/src/gst.rs +++ b/src/gst.rs @@ -12,6 +12,7 @@ use gstreamer_rtsp_server::{RTSPAuth, RTSPToken, RTSPMediaFactory, RTSP_TOKEN_ME use log::debug; use std::io; use std::io::Write; +use std::fs; use gio::{TlsCertificate,TlsAuthenticationMode}; type Result = std::result::Result; @@ -124,7 +125,9 @@ impl RtspServer { debug!("Setting up TLS using {}", cert_file); let auth = self.server.get_auth().unwrap_or_else(|| RTSPAuth::new()); - let cert = TlsCertificate::new_from_file(&cert_file).expect("Not a valid TLS certificate or not found."); + // We seperate reading the file and changing to a PEM so that we get different error messages. + let cert_contents = fs::read_to_string(cert_file).expect("TLS file not found"); + let cert = TlsCertificate::new_from_pem(&cert_contents).expect("Not a valid TLS certificate"); auth.set_tls_certificate(Some(&cert)); auth.set_tls_authentication_mode(client_auth); auth.set_supported_methods(RTSPAuthMethod::None); From 80e416d01d7a3feb022adffe9fdeb90516c6f678 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Fri, 3 Jul 2020 13:49:43 +0700 Subject: [PATCH 14/33] Merging changes from PR --- README.md | 2 +- src/config.rs | 12 +++++++----- src/gst.rs | 41 +++++++++++++++-------------------------- src/main.rs | 20 +++++++++++++++----- 4 files changed, 38 insertions(+), 37 deletions(-) diff --git a/README.md b/README.md index a97a122..becce0d 100644 --- a/README.md +++ b/README.md @@ -73,7 +73,7 @@ You may also need to use `h264` format while using the SD stream. By default Neolink serves on all IP addresses on port 8554. You can modify this by changing the `bind` and the `bind_port` parameter. -Use can enable `rtsps` (TLS) by adding a `certificate = "/path/to/pem"` to the config. This pem should contain by the certificate and the key used for the server. If TLS is enabled all connections must use `rtsps`. Use can also control client side TLS with the config option `tls_client_auth = "none|request|require"`, in this case the client should present a certificate signed by the server's CA, this is disabled by default. +Use can enable `rtsps` (TLS) by adding a `certificate = "/path/to/pem"` to the config. This pem should contain by the certificate and the key used for the server. If TLS is enabled all connections must use `rtsps`. You can also control client side TLS with the config option `tls_client_auth = "none|request|require"`, in this case the client should present a certificate signed by the server's CA, this is disabled by default. Use can enable basic authentication by adding the configuration option `username = "someone"` and `password = "somepass"`. Both username and password must be set for this to work. diff --git a/src/config.rs b/src/config.rs index 2b155b6..e7ccfba 100644 --- a/src/config.rs +++ b/src/config.rs @@ -24,7 +24,7 @@ pub struct Config { pub bind_port: u16, #[serde(default = "default_certificate")] - pub certificate: String, + pub certificate: Option, #[validate(regex(path = "RE_TLS_CLIENT_AUTH", message = "Incorrect stream format", code = "format"))] #[serde(default = "default_tls_client_auth")] @@ -60,11 +60,13 @@ pub struct CameraConfig { #[derive(Debug, Deserialize, Validate, Clone)] pub struct UserConfig { + #[validate(required)] #[serde(alias = "username")] - pub name: String, + pub name: Option, + #[validate(required)] #[serde(alias = "password")] - pub pass: String, + pub pass: Option, } fn default_bind_addr() -> String { @@ -83,8 +85,8 @@ fn default_stream() -> String { "both".to_string() } -fn default_certificate() -> String { - "".to_string() +fn default_certificate() -> Option { + None } fn default_tls_client_auth() -> String { diff --git a/src/gst.rs b/src/gst.rs index 9bc8893..0c1b57b 100644 --- a/src/gst.rs +++ b/src/gst.rs @@ -9,7 +9,7 @@ use gstreamer_app::AppSrc; use gstreamer_rtsp_server::prelude::*; use gstreamer_rtsp::RTSPAuthMethod; use gstreamer_rtsp_server::{RTSPAuth, RTSPToken, RTSPMediaFactory, RTSP_TOKEN_MEDIA_FACTORY_ROLE, RTSP_PERM_MEDIA_FACTORY_ACCESS, RTSP_PERM_MEDIA_FACTORY_CONSTRUCT, RTSPServer as GstRTSPServer}; -use log::{debug, info}; +use log::debug; use std::io; use std::io::Write; use std::fs; @@ -100,26 +100,18 @@ impl RtspServer { Ok(maybe_app_src) } - pub fn set_credentials(&self, credentials :&Vec<(&String, &String)>) -> Result<()> { - let auth = match self.server.get_auth() { - Some(x) => x, - None => RTSPAuth::new(), - }; + pub fn set_credentials(&self, credentials :&Vec>) -> Result<()> { + let auth = self.server.get_auth().unwrap_or_else(|| RTSPAuth::new()); auth.set_supported_methods(RTSPAuthMethod::Basic); - for credentials in credentials { - let (user, pass) = credentials; - if ! user.is_empty() && ! pass.is_empty() { - info!("Setting credentials for user {}", user); + for credential in credentials { + if let Some((user, pass)) = credential { + debug!("Setting credentials for user {}", user); debug!("Password is {}", pass); let token = RTSPToken::new(&[(*RTSP_TOKEN_MEDIA_FACTORY_ROLE, user)]); let basic = RTSPAuth::make_basic(user, pass); auth.add_basic(basic.as_str(), &token); - - // Now we have basic auth we stop others from watching - let mut token = RTSPToken::new_empty(); - auth.set_default_token(Some(&mut token)); } } let mut un_authtoken = RTSPToken::new(&[(*RTSP_TOKEN_MEDIA_FACTORY_ROLE, &"unauth")]); @@ -130,20 +122,17 @@ impl RtspServer { } pub fn set_tls(&self, cert_file: &str, client_auth: TlsAuthenticationMode) -> Result<()> { - if ! cert_file.is_empty() { - info!("Setting up TLS using {}", cert_file); - let auth = match self.server.get_auth() { - Some(x) => x, - None => RTSPAuth::new(), - }; + debug!("Setting up TLS using {}", cert_file); + let auth = self.server.get_auth().unwrap_or_else(|| RTSPAuth::new()); - let cert = TlsCertificate::new_from_pem(&fs::read_to_string(cert_file).expect("TLS file not found")).expect("Not a valid TLS certificate"); - auth.set_tls_certificate(Some(&cert)); - auth.set_tls_authentication_mode(client_auth); - auth.set_supported_methods(RTSPAuthMethod::None); + // We seperate reading the file and changing to a PEM so that we get different error messages. + let cert_contents = fs::read_to_string(cert_file).expect("TLS file not found"); + let cert = TlsCertificate::new_from_pem(&cert_contents).expect("Not a valid TLS certificate"); + auth.set_tls_certificate(Some(&cert)); + auth.set_tls_authentication_mode(client_auth); + auth.set_supported_methods(RTSPAuthMethod::None); - self.server.set_auth(Some(&auth)); - } + self.server.set_auth(Some(&auth)); Ok(()) } diff --git a/src/main.rs b/src/main.rs index d859f67..1922fc5 100644 --- a/src/main.rs +++ b/src/main.rs @@ -137,16 +137,25 @@ fn set_up_tls(config: &Config, rtsp: &RtspServer) { let tls_client_auth = match &config.tls_client_auth as &str { "request" => TlsAuthenticationMode::Requested, "require" => TlsAuthenticationMode::Required, - "none"|_ => TlsAuthenticationMode::None, + "none" => TlsAuthenticationMode::None, + _ => unreachable!(), }; - rtsp.set_tls(&config.certificate, tls_client_auth).expect("Failed to set up TLS"); + if let Some(cert_path) = &config.certificate { + rtsp.set_tls(&cert_path, tls_client_auth).expect("Failed to set up TLS"); + } } fn set_up_users(users: &Vec, rtsp: &RtspServer) { // Setting up users let mut credentials = vec![]; for user in users { - credentials.push((&user.name, &user.pass)); + let name = &user.name; + let pass = &user.pass; + let user_pass = match (name, pass) { + (Some(name), Some(pass)) => Some((&name as &str, &pass as &str)), + _ => None, + }; + credentials.push(user_pass); } rtsp.set_credentials(&credentials).expect("Failed to set up users."); } @@ -159,8 +168,9 @@ fn get_permitted_users(users: &Vec, current_permitted_users: &Vec Date: Fri, 3 Jul 2020 14:23:09 +0700 Subject: [PATCH 15/33] Readme and comment updates --- README.md | 11 ++++++++++- src/main.rs | 5 +++-- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index becce0d..393427f 100644 --- a/README.md +++ b/README.md @@ -75,7 +75,16 @@ You can modify this by changing the `bind` and the `bind_port` parameter. Use can enable `rtsps` (TLS) by adding a `certificate = "/path/to/pem"` to the config. This pem should contain by the certificate and the key used for the server. If TLS is enabled all connections must use `rtsps`. You can also control client side TLS with the config option `tls_client_auth = "none|request|require"`, in this case the client should present a certificate signed by the server's CA, this is disabled by default. -Use can enable basic authentication by adding the configuration option `username = "someone"` and `password = "somepass"`. Both username and password must be set for this to work. +Use can enable basic authentication by adding users to the configuration file as: +``` +[[users]] +name: someone +pass: somepass +``` +you also need to add the allowed users into each camera by adding the following to `[[cameras]]`. +``` +permitted_users = ["someone", "someoneelse"] +``` You can change the Neolink log level by setting the `RUST_LOG` environment variable (not in the configuration file) to one of `error`, `warn`, `info`, `debug`, or `trace`: diff --git a/src/main.rs b/src/main.rs index 1922fc5..4761abe 100644 --- a/src/main.rs +++ b/src/main.rs @@ -162,8 +162,8 @@ fn set_up_users(users: &Vec, rtsp: &RtspServer) { fn get_permitted_users(users: &Vec, current_permitted_users: &Vec) -> Vec { // This is required to handle the special case of "anyone" - // Special set up of "anyone" - // If in the camera config there is the user anyone + // ===Special set up of "anyone"=== + // If in the camera config there is the user "anyone" // Then we add all users to the cameras config. including unauth let mut new_permitted_users = vec![]; if current_permitted_users.contains(&"anyone".to_string()) { @@ -176,6 +176,7 @@ fn get_permitted_users(users: &Vec, current_permitted_users: &Vec Date: Fri, 3 Jul 2020 14:57:34 +0700 Subject: [PATCH 16/33] Add default no users --- src/config.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/config.rs b/src/config.rs index e7ccfba..fc9d03e 100644 --- a/src/config.rs +++ b/src/config.rs @@ -31,6 +31,7 @@ pub struct Config { pub tls_client_auth: String, #[validate] + #[serde(default = "default_users")] pub users: Vec, } @@ -96,3 +97,7 @@ fn default_tls_client_auth() -> String { fn default_permitted_users() -> Vec { vec!["anyone".to_string()] } + +fn default_users() -> Vec { + vec![] +} From 1a5ce73b6d0597fe7c7532206831cf191011583a Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Tue, 7 Jul 2020 22:02:12 +0700 Subject: [PATCH 17/33] Ensure anonymous has access to check the URL if not play it --- src/gst.rs | 56 +++++++++++++++++++++++++++++++++++++++-------------- src/main.rs | 11 ++++++++++- 2 files changed, 52 insertions(+), 15 deletions(-) diff --git a/src/gst.rs b/src/gst.rs index 0c1b57b..37d9028 100644 --- a/src/gst.rs +++ b/src/gst.rs @@ -3,7 +3,7 @@ pub use self::maybe_app_src::MaybeAppSrc; use gstreamer::prelude::Cast; -use gstreamer::{Bin,Structure}; +use gstreamer::{Bin, Structure}; use gstreamer_app::AppSrc; //use gstreamer_rtsp::RTSPLowerTrans; use gstreamer_rtsp_server::prelude::*; @@ -50,15 +50,19 @@ impl RtspServer { let factory = RTSPMediaFactory::new(); for permitted_user in permitted_users { - factory.add_role_from_structure( - &Structure::new( - &permitted_user, - &[ - (*RTSP_PERM_MEDIA_FACTORY_ACCESS, &true), - (*RTSP_PERM_MEDIA_FACTORY_CONSTRUCT, &true), - ] - ) - ); + debug!("Permitting {} to access {}", permitted_user, names.join(", ")); + self.add_watcher_role(&factory, &permitted_user) + } + // During auth, first it binds anonymously. At this point it checks + // RTSP_PERM_MEDIA_FACTORY_ACCESS to see if anyone can connect + // This is done before the auth token is loaded, possibliy an upstream bug there + // After checking RTSP_PERM_MEDIA_FACTORY_ACCESS anonymously + // It loads the auth token of the user and checks that users + // RTSP_PERM_MEDIA_FACTORY_CONSTRUCT allowing them to play + // As a result of this we must ensure that if anonymous is not granted watcher + // access that anon has at least RTSP_PERM_MEDIA_FACTORY_ACCESS + if ! permitted_users.contains(&"anonymous".to_string()) { + self.add_check_role(&factory, "anonymous"); } //factory.set_protocols(RTSPLowerTrans::TCP); @@ -100,11 +104,36 @@ impl RtspServer { Ok(maybe_app_src) } - pub fn set_credentials(&self, credentials :&Vec>) -> Result<()> { - let auth = self.server.get_auth().unwrap_or_else(|| RTSPAuth::new()); + pub fn add_watcher_role(&self, factory: &RTSPMediaFactory, role: &str) { + factory.add_role_from_structure( + &Structure::new( + &role, + &[ + (*RTSP_PERM_MEDIA_FACTORY_ACCESS, &true), + (*RTSP_PERM_MEDIA_FACTORY_CONSTRUCT, &true), + ] + ) + ); + } + pub fn add_check_role(&self, factory: &RTSPMediaFactory, role: &str) { + factory.add_role_from_structure( + &Structure::new( + &role, + &[ + (*RTSP_PERM_MEDIA_FACTORY_ACCESS, &true), + ] + ) + ); + } + + pub fn set_credentials(&self, credentials: &Vec>) -> Result<()> { + let auth = self.server.get_auth().unwrap_or_else(|| RTSPAuth::new()); auth.set_supported_methods(RTSPAuthMethod::Basic); + let mut un_authtoken = RTSPToken::new(&[(*RTSP_TOKEN_MEDIA_FACTORY_ROLE, &"anonymous")]); + auth.set_default_token(Some(&mut un_authtoken)); + for credential in credentials { if let Some((user, pass)) = credential { debug!("Setting credentials for user {}", user); @@ -114,8 +143,6 @@ impl RtspServer { auth.add_basic(basic.as_str(), &token); } } - let mut un_authtoken = RTSPToken::new(&[(*RTSP_TOKEN_MEDIA_FACTORY_ROLE, &"unauth")]); - auth.set_default_token(Some(&mut un_authtoken)); self.server.set_auth(Some(&auth)); Ok(()) @@ -130,6 +157,7 @@ impl RtspServer { let cert = TlsCertificate::new_from_pem(&cert_contents).expect("Not a valid TLS certificate"); auth.set_tls_certificate(Some(&cert)); auth.set_tls_authentication_mode(client_auth); + // We set to none here, when set up credentials is called it will change it to the appropiate value auth.set_supported_methods(RTSPAuthMethod::None); self.server.set_auth(Some(&auth)); diff --git a/src/main.rs b/src/main.rs index 4761abe..171f5d2 100644 --- a/src/main.rs +++ b/src/main.rs @@ -153,6 +153,15 @@ fn set_up_users(users: &Vec, rtsp: &RtspServer) { let pass = &user.pass; let user_pass = match (name, pass) { (Some(name), Some(pass)) => Some((&name as &str, &pass as &str)), + (Some(name), None) => { + warn!("One of the users has no password, skipping this user"); + debug!("The skipped user was {}", name); + None + } + (None, Some(_pass)) => { + warn!("One of the users has a password but no name, skipping this user"); + None + } _ => None, }; credentials.push(user_pass); @@ -172,7 +181,7 @@ fn get_permitted_users(users: &Vec, current_permitted_users: &Vec Date: Wed, 8 Jul 2020 07:15:19 +0700 Subject: [PATCH 18/33] Adding more info messages, and reserving special user names --- src/main.rs | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/src/main.rs b/src/main.rs index 171f5d2..ebdb0fb 100644 --- a/src/main.rs +++ b/src/main.rs @@ -148,20 +148,29 @@ fn set_up_tls(config: &Config, rtsp: &RtspServer) { fn set_up_users(users: &Vec, rtsp: &RtspServer) { // Setting up users let mut credentials = vec![]; + let reserved_names = vec!(String::from("anyone"), String::from("anonymous")); for user in users { + if let Some(name) = &user.name { + if reserved_names.contains(name) { + warn!("{} is a reserved username, skipping this user", name); + continue; + } + } let name = &user.name; let pass = &user.pass; let user_pass = match (name, pass) { - (Some(name), Some(pass)) => Some((&name as &str, &pass as &str)), + (Some(name), Some(pass)) => { + Some((&name as &str, &pass as &str)) + } (Some(name), None) => { warn!("One of the users has no password, skipping this user"); debug!("The skipped user was {}", name); None - } + }, (None, Some(_pass)) => { warn!("One of the users has a password but no name, skipping this user"); None - } + }, _ => None, }; credentials.push(user_pass); From ad1b34239cb55db703be9340d01a6138aa29a8df Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Fri, 10 Jul 2020 17:36:36 +0700 Subject: [PATCH 19/33] But fix and update to the warning given during user/password checking --- src/gst.rs | 4 ++-- src/main.rs | 9 ++------- 2 files changed, 4 insertions(+), 9 deletions(-) diff --git a/src/gst.rs b/src/gst.rs index 35d5c83..529f90f 100644 --- a/src/gst.rs +++ b/src/gst.rs @@ -50,7 +50,7 @@ impl RtspServer { let factory = RTSPMediaFactory::new(); for permitted_user in permitted_users { - debug!("Permitting {} to access {}", permitted_user, names.join(", ")); + debug!("Permitting {} to access {}", permitted_user, paths.join(", ")); self.add_watcher_role(&factory, &permitted_user) } // During auth, first it binds anonymously. At this point it checks @@ -60,7 +60,7 @@ impl RtspServer { // It loads the auth token of the user and checks that users // RTSP_PERM_MEDIA_FACTORY_CONSTRUCT allowing them to play // As a result of this we must ensure that if anonymous is not granted watcher - // access that anon has at least RTSP_PERM_MEDIA_FACTORY_ACCESS + // access that anon has at least RTSP_PERM_MEDIA_FACTORY_ACCESS if ! permitted_users.contains(&"anonymous".to_string()) { self.add_check_role(&factory, "anonymous"); } diff --git a/src/main.rs b/src/main.rs index c2e45a8..3875364 100644 --- a/src/main.rs +++ b/src/main.rs @@ -165,14 +165,9 @@ fn set_up_users(users: &Vec, rtsp: &RtspServer) { let user_pass = match (name, pass) { (Some(name), Some(pass)) => { Some((&name as &str, &pass as &str)) - } - (Some(name), None) => { - warn!("One of the users has no password, skipping this user"); - debug!("The skipped user was {}", name); - None }, - (None, Some(_pass)) => { - warn!("One of the users has a password but no name, skipping this user"); + (Some(_), None) | (None, Some(_)) => { + warn!("Username and password must be supplied together - ignoring [[users]] entry"); None }, _ => None, From 4723435a457fc8d2e8c1c6ed8325b001c8142b9e Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Sat, 11 Jul 2020 09:11:11 +0700 Subject: [PATCH 20/33] Clean up of redundent code in TLS and Basic auth --- src/gst.rs | 76 +++++++++++++++++++++++++++--------------------------- 1 file changed, 38 insertions(+), 38 deletions(-) diff --git a/src/gst.rs b/src/gst.rs index 529f90f..8a497a8 100644 --- a/src/gst.rs +++ b/src/gst.rs @@ -49,21 +49,8 @@ impl RtspServer { let factory = RTSPMediaFactory::new(); - for permitted_user in permitted_users { - debug!("Permitting {} to access {}", permitted_user, paths.join(", ")); - self.add_watcher_role(&factory, &permitted_user) - } - // During auth, first it binds anonymously. At this point it checks - // RTSP_PERM_MEDIA_FACTORY_ACCESS to see if anyone can connect - // This is done before the auth token is loaded, possibliy an upstream bug there - // After checking RTSP_PERM_MEDIA_FACTORY_ACCESS anonymously - // It loads the auth token of the user and checks that users - // RTSP_PERM_MEDIA_FACTORY_CONSTRUCT allowing them to play - // As a result of this we must ensure that if anonymous is not granted watcher - // access that anon has at least RTSP_PERM_MEDIA_FACTORY_ACCESS - if ! permitted_users.contains(&"anonymous".to_string()) { - self.add_check_role(&factory, "anonymous"); - } + debug!("Permitting {} to access {}", permitted_users.join(", "), paths.join(", ")); + self.add_permitted_roles(&factory, permitted_users); //factory.set_protocols(RTSPLowerTrans::TCP); factory.set_launch(&format!("{}{}{}{}", @@ -104,27 +91,42 @@ impl RtspServer { Ok(maybe_app_src) } - pub fn add_watcher_role(&self, factory: &RTSPMediaFactory, role: &str) { - factory.add_role_from_structure( - &Structure::new( - &role, - &[ - (*RTSP_PERM_MEDIA_FACTORY_ACCESS, &true), - (*RTSP_PERM_MEDIA_FACTORY_CONSTRUCT, &true), - ] - ) - ); - } - - pub fn add_check_role(&self, factory: &RTSPMediaFactory, role: &str) { - factory.add_role_from_structure( - &Structure::new( - &role, - &[ - (*RTSP_PERM_MEDIA_FACTORY_ACCESS, &true), - ] - ) - ); + pub fn add_permitted_roles(&self, factory: &RTSPMediaFactory, permitted_roles: &Vec) { + for permitted_role in permitted_roles { + factory.add_role_from_structure( + &Structure::new( + permitted_role.as_str(), + &[ + (*RTSP_PERM_MEDIA_FACTORY_ACCESS, &true), + (*RTSP_PERM_MEDIA_FACTORY_CONSTRUCT, &true), + ] + ) + ); + } + // During auth, first it binds anonymously. At this point it checks + // RTSP_PERM_MEDIA_FACTORY_ACCESS to see if anyone can connect + // This is done before the auth token is loaded, possibliy an upstream bug there + // After checking RTSP_PERM_MEDIA_FACTORY_ACCESS anonymously + // It loads the auth token of the user and checks that users + // RTSP_PERM_MEDIA_FACTORY_CONSTRUCT allowing them to play + // As a result of this we must ensure that if anonymous is not granted RTSP_PERM_MEDIA_FACTORY_ACCESS + // As a part of permitted users then we must allow it to access + // at least RTSP_PERM_MEDIA_FACTORY_ACCESS but not RTSP_PERM_MEDIA_FACTORY_CONSTRUCT + // Watching Actually happens during RTSP_PERM_MEDIA_FACTORY_CONSTRUCT + // So this should be OK to do. + // FYI: If no RTSP_PERM_MEDIA_FACTORY_ACCESS then server returns 404 not found + // If yes RTSP_PERM_MEDIA_FACTORY_ACCESS but no RTSP_PERM_MEDIA_FACTORY_CONSTRUCT + // server returns 401 not authourised + if ! permitted_roles.contains(&"anonymous".to_string()) { + factory.add_role_from_structure( + &Structure::new( + "anonymous", + &[ + (*RTSP_PERM_MEDIA_FACTORY_ACCESS, &true), + ] + ) + ); + } } pub fn set_credentials(&self, credentials: &Vec>) -> Result<()> { @@ -157,8 +159,6 @@ impl RtspServer { let cert = TlsCertificate::new_from_pem(&cert_contents).expect("Not a valid TLS certificate"); auth.set_tls_certificate(Some(&cert)); auth.set_tls_authentication_mode(client_auth); - // We set to none here, when set up credentials is called it will change it to the appropiate value - auth.set_supported_methods(RTSPAuthMethod::None); self.server.set_auth(Some(&auth)); Ok(()) From 0fa62698a7f95306b7a7366748147cccc400cb7e Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Sun, 12 Jul 2020 18:49:51 +0700 Subject: [PATCH 21/33] Updates to the readme --- README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 9f2975a..4846c75 100644 --- a/README.md +++ b/README.md @@ -93,9 +93,11 @@ You may also need to use `h264` format while using the SD stream. By default Neolink serves on all IP addresses on port 8554. You can modify this by changing the `bind` and the `bind_port` parameter. -Use can enable `rtsps` (TLS) by adding a `certificate = "/path/to/pem"` to the config. This pem should contain by the certificate and the key used for the server. If TLS is enabled all connections must use `rtsps`. You can also control client side TLS with the config option `tls_client_auth = "none|request|require"`, in this case the client should present a certificate signed by the server's CA, this is disabled by default. +You can enable `rtsps` (TLS) by adding a `certificate = "/path/to/pem"` to the top section of the config file. This PEM should contain by the certificate and the key used for the server. If TLS is enabled all connections must use `rtsps`. You can also control client side TLS with the config option `tls_client_auth = "none|request|require"`; in this case the client should present a certificate signed by the server's CA. -Use can enable basic authentication by adding users to the configuration file as: +TLS is disabled by default. + +You can password-protect the Neolink server by adding `[[users]]`` sections to the configuration file: ``` [[users]] name: someone From 65748bd1179d27e27fc3d77af4e3b4337de96b9a Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Mon, 13 Jul 2020 09:17:50 +0700 Subject: [PATCH 22/33] Using a slice for the permitted users --- src/gst.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/gst.rs b/src/gst.rs index 8a497a8..1e79c77 100644 --- a/src/gst.rs +++ b/src/gst.rs @@ -35,7 +35,7 @@ impl RtspServer { } } - pub fn add_stream(&self, paths: &[&str], stream_format: &StreamFormat, permitted_users: &Vec) -> Result { + pub fn add_stream(&self, paths: &[&str], stream_format: &StreamFormat, permitted_users: &[String]) -> Result { let mounts = self .server .get_mount_points() @@ -91,7 +91,7 @@ impl RtspServer { Ok(maybe_app_src) } - pub fn add_permitted_roles(&self, factory: &RTSPMediaFactory, permitted_roles: &Vec) { + pub fn add_permitted_roles(&self, factory: &RTSPMediaFactory, permitted_roles: &[String]) { for permitted_role in permitted_roles { factory.add_role_from_structure( &Structure::new( From 6811f15aba1548408f97c31a53c5276785cfb951 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Mon, 13 Jul 2020 09:18:11 +0700 Subject: [PATCH 23/33] Using hashmap to do the deduplicating --- src/main.rs | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/src/main.rs b/src/main.rs index 3875364..c26c4b0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -8,6 +8,7 @@ use std::fs; use std::io::Write; use std::sync::Arc; use std::time::Duration; +use std::collections::HashSet; use structopt::StructOpt; use validator::Validate; use gio::TlsAuthenticationMode; @@ -182,22 +183,23 @@ fn get_permitted_users(users: &Vec, current_permitted_users: &Vec Date: Mon, 13 Jul 2020 09:20:09 +0700 Subject: [PATCH 24/33] Using anonymous for default permitted users --- src/config.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/config.rs b/src/config.rs index 1da14a6..ba1626d 100644 --- a/src/config.rs +++ b/src/config.rs @@ -105,7 +105,7 @@ fn default_tls_client_auth() -> String { } fn default_permitted_users() -> Vec { - vec!["anyone".to_string()] + vec!["anonymous".to_string()] } fn default_users() -> Vec { From 143390d6f4af442491873a4110d16fb8eebe535b Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Mon, 13 Jul 2020 10:11:58 +0700 Subject: [PATCH 25/33] using valdator to check for reserved names --- src/config.rs | 12 ++++++++++-- src/main.rs | 7 ------- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/src/config.rs b/src/config.rs index ba1626d..80bea06 100644 --- a/src/config.rs +++ b/src/config.rs @@ -4,7 +4,7 @@ use serde::Deserialize; use std::clone::Clone; use std::net::SocketAddr; use std::time::Duration; -use validator::Validate; +use validator::{Validate, ValidationError}; use validator_derive::Validate; lazy_static! { @@ -71,7 +71,7 @@ pub struct CameraConfig { #[derive(Debug, Deserialize, Validate, Clone)] pub struct UserConfig { - #[validate(required)] + #[validate(required, custom = "validate_username")] #[serde(alias = "username")] pub name: Option, @@ -111,3 +111,11 @@ fn default_permitted_users() -> Vec { fn default_users() -> Vec { vec![] } + +fn validate_username(name: &str) -> Result<(), ValidationError> { + let reserved_names = vec!("anyone", "anonymous"); + if reserved_names.contains(&name) { + return Err(ValidationError::new("This is a reserved username")); + } + Ok(()) +} diff --git a/src/main.rs b/src/main.rs index c26c4b0..3f5151b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -153,14 +153,7 @@ fn set_up_tls(config: &Config, rtsp: &RtspServer) { fn set_up_users(users: &Vec, rtsp: &RtspServer) { // Setting up users let mut credentials = vec![]; - let reserved_names = vec!(String::from("anyone"), String::from("anonymous")); for user in users { - if let Some(name) = &user.name { - if reserved_names.contains(name) { - warn!("{} is a reserved username, skipping this user", name); - continue; - } - } let name = &user.name; let pass = &user.pass; let user_pass = match (name, pass) { From 0d39cbaeff8e70ba41e8abc634e26a6641590774 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Mon, 13 Jul 2020 11:51:29 +0700 Subject: [PATCH 26/33] Updates to the readme --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 4846c75..44f6aae 100644 --- a/README.md +++ b/README.md @@ -108,6 +108,10 @@ you also need to add the allowed users into each camera by adding the following permitted_users = ["someone", "someoneelse"] ``` +Anywhere a username is accepted it can take any username or one of the following special values. +- `anyone` means any user with a valid user/pass +- `anonymous` means no user/pass required + You can change the Neolink log level by setting the `RUST_LOG` environment variable (not in the configuration file) to one of `error`, `warn`, `info`, `debug`, or `trace`: ``` From c1151acecb4acc134689edc9c94cca6e27a0110a Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Mon, 13 Jul 2020 12:02:13 +0700 Subject: [PATCH 27/33] More readme updates to explain the default permitted_users --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 44f6aae..a349953 100644 --- a/README.md +++ b/README.md @@ -112,6 +112,8 @@ Anywhere a username is accepted it can take any username or one of the following - `anyone` means any user with a valid user/pass - `anonymous` means no user/pass required +The default `permitted_users` list is `[ "anonymous" ]` meaning no authentication required. If you want to use authenitcation then after adding your users through `[[users]]` please ensure you update the `permittted_users` for each camera. + You can change the Neolink log level by setting the `RUST_LOG` environment variable (not in the configuration file) to one of `error`, `warn`, `info`, `debug`, or `trace`: ``` From 60810fc0f75a65a6e009ef327cd1b79dddea47e4 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Mon, 13 Jul 2020 12:12:17 +0700 Subject: [PATCH 28/33] Rustfmt cleanup --- src/config.rs | 10 ++++++--- src/gst.rs | 58 +++++++++++++++++++++++++++++---------------------- src/main.rs | 33 +++++++++++++++++------------ 3 files changed, 60 insertions(+), 41 deletions(-) diff --git a/src/config.rs b/src/config.rs index 80bea06..d1381a5 100644 --- a/src/config.rs +++ b/src/config.rs @@ -28,7 +28,11 @@ pub struct Config { #[serde(default = "default_certificate")] pub certificate: Option, - #[validate(regex(path = "RE_TLS_CLIENT_AUTH", message = "Incorrect stream format", code = "format"))] + #[validate(regex( + path = "RE_TLS_CLIENT_AUTH", + message = "Incorrect stream format", + code = "format" + ))] #[serde(default = "default_tls_client_auth")] pub tls_client_auth: String, @@ -112,8 +116,8 @@ fn default_users() -> Vec { vec![] } -fn validate_username(name: &str) -> Result<(), ValidationError> { - let reserved_names = vec!("anyone", "anonymous"); +fn validate_username(name: &str) -> Result<(), ValidationError> { + let reserved_names = vec!["anyone", "anonymous"]; if reserved_names.contains(&name) { return Err(ValidationError::new("This is a reserved username")); } diff --git a/src/gst.rs b/src/gst.rs index 1e79c77..6e7a3e0 100644 --- a/src/gst.rs +++ b/src/gst.rs @@ -6,14 +6,18 @@ use gstreamer::prelude::Cast; use gstreamer::{Bin, Structure}; use gstreamer_app::AppSrc; //use gstreamer_rtsp::RTSPLowerTrans; -use gstreamer_rtsp_server::prelude::*; +use gio::{TlsAuthenticationMode, TlsCertificate}; use gstreamer_rtsp::RTSPAuthMethod; -use gstreamer_rtsp_server::{RTSPAuth, RTSPToken, RTSPMediaFactory, RTSP_TOKEN_MEDIA_FACTORY_ROLE, RTSP_PERM_MEDIA_FACTORY_ACCESS, RTSP_PERM_MEDIA_FACTORY_CONSTRUCT, RTSPServer as GstRTSPServer}; +use gstreamer_rtsp_server::prelude::*; +use gstreamer_rtsp_server::{ + RTSPAuth, RTSPMediaFactory, RTSPServer as GstRTSPServer, RTSPToken, + RTSP_PERM_MEDIA_FACTORY_ACCESS, RTSP_PERM_MEDIA_FACTORY_CONSTRUCT, + RTSP_TOKEN_MEDIA_FACTORY_ROLE, +}; use log::debug; +use std::fs; use std::io; use std::io::Write; -use std::fs; -use gio::{TlsCertificate,TlsAuthenticationMode}; type Result = std::result::Result; @@ -35,7 +39,12 @@ impl RtspServer { } } - pub fn add_stream(&self, paths: &[&str], stream_format: &StreamFormat, permitted_users: &[String]) -> Result { + pub fn add_stream( + &self, + paths: &[&str], + stream_format: &StreamFormat, + permitted_users: &[String], + ) -> Result { let mounts = self .server .get_mount_points() @@ -49,7 +58,11 @@ impl RtspServer { let factory = RTSPMediaFactory::new(); - debug!("Permitting {} to access {}", permitted_users.join(", "), paths.join(", ")); + debug!( + "Permitting {} to access {}", + permitted_users.join(", "), + paths.join(", ") + ); self.add_permitted_roles(&factory, permitted_users); //factory.set_protocols(RTSPLowerTrans::TCP); @@ -93,15 +106,13 @@ impl RtspServer { pub fn add_permitted_roles(&self, factory: &RTSPMediaFactory, permitted_roles: &[String]) { for permitted_role in permitted_roles { - factory.add_role_from_structure( - &Structure::new( - permitted_role.as_str(), - &[ - (*RTSP_PERM_MEDIA_FACTORY_ACCESS, &true), - (*RTSP_PERM_MEDIA_FACTORY_CONSTRUCT, &true), - ] - ) - ); + factory.add_role_from_structure(&Structure::new( + permitted_role.as_str(), + &[ + (*RTSP_PERM_MEDIA_FACTORY_ACCESS, &true), + (*RTSP_PERM_MEDIA_FACTORY_CONSTRUCT, &true), + ], + )); } // During auth, first it binds anonymously. At this point it checks // RTSP_PERM_MEDIA_FACTORY_ACCESS to see if anyone can connect @@ -117,15 +128,11 @@ impl RtspServer { // FYI: If no RTSP_PERM_MEDIA_FACTORY_ACCESS then server returns 404 not found // If yes RTSP_PERM_MEDIA_FACTORY_ACCESS but no RTSP_PERM_MEDIA_FACTORY_CONSTRUCT // server returns 401 not authourised - if ! permitted_roles.contains(&"anonymous".to_string()) { - factory.add_role_from_structure( - &Structure::new( - "anonymous", - &[ - (*RTSP_PERM_MEDIA_FACTORY_ACCESS, &true), - ] - ) - ); + if !permitted_roles.contains(&"anonymous".to_string()) { + factory.add_role_from_structure(&Structure::new( + "anonymous", + &[(*RTSP_PERM_MEDIA_FACTORY_ACCESS, &true)], + )); } } @@ -156,7 +163,8 @@ impl RtspServer { // We seperate reading the file and changing to a PEM so that we get different error messages. let cert_contents = fs::read_to_string(cert_file).expect("TLS file not found"); - let cert = TlsCertificate::new_from_pem(&cert_contents).expect("Not a valid TLS certificate"); + let cert = + TlsCertificate::new_from_pem(&cert_contents).expect("Not a valid TLS certificate"); auth.set_tls_certificate(Some(&cert)); auth.set_tls_authentication_mode(client_auth); diff --git a/src/main.rs b/src/main.rs index 3f5151b..feff234 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,23 +1,23 @@ use env_logger::Env; use err_derive::Error; +use gio::TlsAuthenticationMode; use log::*; use neolink::bc_protocol::BcCamera; use neolink::gst::{MaybeAppSrc, RtspServer, StreamFormat}; use neolink::Never; +use std::collections::HashSet; use std::fs; use std::io::Write; use std::sync::Arc; use std::time::Duration; -use std::collections::HashSet; use structopt::StructOpt; use validator::Validate; -use gio::TlsAuthenticationMode; mod cmdline; mod config; use cmdline::Opt; -use config::{UserConfig, CameraConfig, Config}; +use config::{CameraConfig, Config, UserConfig}; #[derive(Debug, Error)] pub enum Error { @@ -77,13 +77,17 @@ fn main() -> Result<(), Error> { &*format!("/{}", arc_cam.name), &*format!("/{}/mainStream", arc_cam.name), ]; - let mut output = rtsp.add_stream(paths, &stream_format, &permitted_user).unwrap(); + let mut output = rtsp + .add_stream(paths, &stream_format, &permitted_user) + .unwrap(); let main_camera = arc_cam.clone(); s.spawn(move |_| camera_loop(&*main_camera, "mainStream", &mut output)); } if ["both", "subStream"].iter().any(|&e| e == arc_cam.stream) { let paths = &[&*format!("/{}/subStream", arc_cam.name)]; - let mut output = rtsp.add_stream(paths, &substream_format, &permitted_user).unwrap(); + let mut output = rtsp + .add_stream(paths, &substream_format, &permitted_user) + .unwrap(); let sub_camera = arc_cam.clone(); s.spawn(move |_| camera_loop(&*sub_camera, "subStream", &mut output)); } @@ -146,7 +150,8 @@ fn set_up_tls(config: &Config, rtsp: &RtspServer) { _ => unreachable!(), }; if let Some(cert_path) = &config.certificate { - rtsp.set_tls(&cert_path, tls_client_auth).expect("Failed to set up TLS"); + rtsp.set_tls(&cert_path, tls_client_auth) + .expect("Failed to set up TLS"); } } @@ -156,22 +161,24 @@ fn set_up_users(users: &Vec, rtsp: &RtspServer) { for user in users { let name = &user.name; let pass = &user.pass; - let user_pass = match (name, pass) { - (Some(name), Some(pass)) => { - Some((&name as &str, &pass as &str)) - }, + let user_pass = match (name, pass) { + (Some(name), Some(pass)) => Some((&name as &str, &pass as &str)), (Some(_), None) | (None, Some(_)) => { warn!("Username and password must be supplied together - ignoring [[users]] entry"); None - }, + } _ => None, }; credentials.push(user_pass); } - rtsp.set_credentials(&credentials).expect("Failed to set up users."); + rtsp.set_credentials(&credentials) + .expect("Failed to set up users."); } -fn get_permitted_users(users: &Vec, current_permitted_users: &Vec) -> Vec { +fn get_permitted_users( + users: &Vec, + current_permitted_users: &Vec, +) -> Vec { // This is required to handle the special case of "anyone" // ===Special set up of "anyone"=== // If in the camera config there is the user "anyone" From b86f5abf6cdacda0735c36bc481cb4a0d10be51c Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Mon, 13 Jul 2020 14:33:31 +0700 Subject: [PATCH 29/33] Chaning the default of permitted_users to depend on `[[users]]` --- README.md | 4 +++- src/config.rs | 6 +++--- src/main.rs | 16 +++++++++++++++- 3 files changed, 21 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index a349953..d204e47 100644 --- a/README.md +++ b/README.md @@ -112,7 +112,9 @@ Anywhere a username is accepted it can take any username or one of the following - `anyone` means any user with a valid user/pass - `anonymous` means no user/pass required -The default `permitted_users` list is `[ "anonymous" ]` meaning no authentication required. If you want to use authenitcation then after adding your users through `[[users]]` please ensure you update the `permittted_users` for each camera. +The default `permitted_users` list is: +- `[ "anonymous"]` if no `[[users]]` were given in the config meaning no authentication required to connect. +- `[ "anyone" ]` if `[[users]]` were provided meaning any authourised users can connect. You can change the Neolink log level by setting the `RUST_LOG` environment variable (not in the configuration file) to one of `error`, `warn`, `info`, `debug`, or `trace`: diff --git a/src/config.rs b/src/config.rs index d1381a5..086d5db 100644 --- a/src/config.rs +++ b/src/config.rs @@ -70,7 +70,7 @@ pub struct CameraConfig { pub stream: String, #[serde(default = "default_permitted_users")] - pub permitted_users: Vec, + pub permitted_users: Option>, } #[derive(Debug, Deserialize, Validate, Clone)] @@ -108,8 +108,8 @@ fn default_tls_client_auth() -> String { "none".to_string() } -fn default_permitted_users() -> Vec { - vec!["anonymous".to_string()] +fn default_permitted_users() -> Option> { + None } fn default_users() -> Vec { diff --git a/src/main.rs b/src/main.rs index feff234..d2f6898 100644 --- a/src/main.rs +++ b/src/main.rs @@ -177,8 +177,22 @@ fn set_up_users(users: &Vec, rtsp: &RtspServer) { fn get_permitted_users( users: &Vec, - current_permitted_users: &Vec, + permitted_users: &Option>, ) -> Vec { + let current_permitted_users = match permitted_users { + Some(permitted_users) => permitted_users.clone().to_owned(), + None => { + // If None then the users didn't specify permitted_users + // In this case we do either + // - Any authourised user if [[users]] was specified + // - Any connecting user if [[users]] was not added + if users.len() > 0 { + vec!("anyone".to_string()) + } else { + vec!("anonymous".to_string()) + } + } + }; // This is required to handle the special case of "anyone" // ===Special set up of "anyone"=== // If in the camera config there is the user "anyone" From 4e16ae912d8b52c453dff2b95cc2d76d0f8f541e Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Mon, 13 Jul 2020 15:31:25 +0700 Subject: [PATCH 30/33] Added more info in the sample_config --- sample_config.toml | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/sample_config.toml b/sample_config.toml index a67d47e..b224841 100644 --- a/sample_config.toml +++ b/sample_config.toml @@ -1,13 +1,43 @@ +# A bind value of 0.0.0.0 means any network this computer can access +# You can chage this to a specfic network e.g. "192.168.1.101" here +# Or to no networks e.g. this computer only "127.0.0.1" bind = "0.0.0.0" +# Default port is 8554 but you can change it by uncommenting the following +# bind_port = 8554 + +# Uncomment the following and supply a path to a valid PEM +# to activate TLS encryption. +# The PEM should contain the certificate and the private key +# If TLS is activated you must connect with "rtsps://" and not "rtsp://" +# certificate = "/path/to/pem/with/cert/and/key" + +# You can password protect the rtsp server mount points by adding users +# like the following me and someone. If you do not add [[users]] +# then anyone can connect without a password or username +# To access such a stream try using a url such as "rtsp://me:mepass@192.168.1.101/driveway" +[[users]] +name = "me" +pass = "mepass" + +[[users]] +name = "someone" +pass = "someonepass" + [[cameras]] name = "driveway" username = "admin" password = "12345678" address = "192.168.1.187:9000" +# By default any of the users can connect (or anyone at all if no users are specfied) +# You can uncomment the following to permit only specfic users +# permitted_users = [ "me" ] [[cameras]] name = "storage shed" username = "admin" password = "987654321" address = "192.168.1.245:9000" +# By default the camera is assumed to be in H.265 format +# Some camera's e.g. E1 use H.264. You can use the following to change this +# format = "h264" From 419c9561d2030f1e62bf5c62026d5aa94da773c1 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Tue, 14 Jul 2020 09:57:55 +0700 Subject: [PATCH 31/33] Using hashmap for permitted users throughout --- Cargo.toml | 1 + src/gst.rs | 9 ++++++--- src/main.rs | 8 ++------ 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 429a4bb..6610062 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,6 +21,7 @@ gstreamer-rtsp-server = { version = "0.15", features = ["v1_12", "v1_14"]} lazy_static = "1.4" log = { version = "0.4" } indoc = "0.3" +itertools = "0.9" md5 = "0.7" nom = "5.1" regex = "1" diff --git a/src/gst.rs b/src/gst.rs index 6e7a3e0..9e60e35 100644 --- a/src/gst.rs +++ b/src/gst.rs @@ -15,9 +15,11 @@ use gstreamer_rtsp_server::{ RTSP_TOKEN_MEDIA_FACTORY_ROLE, }; use log::debug; +use std::collections::HashSet; use std::fs; use std::io; use std::io::Write; +use itertools::Itertools; type Result = std::result::Result; @@ -43,7 +45,7 @@ impl RtspServer { &self, paths: &[&str], stream_format: &StreamFormat, - permitted_users: &[String], + permitted_users: &HashSet, ) -> Result { let mounts = self .server @@ -60,7 +62,8 @@ impl RtspServer { debug!( "Permitting {} to access {}", - permitted_users.join(", "), + // This is hashmap or (iter) equivalent of join, it requres itertools + permitted_users.iter().cloned().intersperse(", ".to_string()).collect::(), paths.join(", ") ); self.add_permitted_roles(&factory, permitted_users); @@ -104,7 +107,7 @@ impl RtspServer { Ok(maybe_app_src) } - pub fn add_permitted_roles(&self, factory: &RTSPMediaFactory, permitted_roles: &[String]) { + pub fn add_permitted_roles(&self, factory: &RTSPMediaFactory, permitted_roles: &HashSet) { for permitted_role in permitted_roles { factory.add_role_from_structure(&Structure::new( permitted_role.as_str(), diff --git a/src/main.rs b/src/main.rs index d2f6898..3ea49bf 100644 --- a/src/main.rs +++ b/src/main.rs @@ -178,7 +178,7 @@ fn set_up_users(users: &Vec, rtsp: &RtspServer) { fn get_permitted_users( users: &Vec, permitted_users: &Option>, -) -> Vec { +) -> HashSet { let current_permitted_users = match permitted_users { Some(permitted_users) => permitted_users.clone().to_owned(), None => { @@ -209,11 +209,7 @@ fn get_permitted_users( new_permitted_users.insert(user.to_string()); } } - let mut result = vec![]; - for user in new_permitted_users { - result.push(user); - } - result + new_permitted_users } fn camera_main( From 5d30e1a8b110c8f955c2ae682275a375cb97e79a Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Tue, 14 Jul 2020 09:59:55 +0700 Subject: [PATCH 32/33] No printing of secrets even at debug level --- src/gst.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/gst.rs b/src/gst.rs index 9e60e35..128b2e8 100644 --- a/src/gst.rs +++ b/src/gst.rs @@ -149,7 +149,6 @@ impl RtspServer { for credential in credentials { if let Some((user, pass)) = credential { debug!("Setting credentials for user {}", user); - debug!("Password is {}", pass); let token = RTSPToken::new(&[(*RTSP_TOKEN_MEDIA_FACTORY_ROLE, user)]); let basic = RTSPAuth::make_basic(user, pass); auth.add_basic(basic.as_str(), &token); From 5bd4c5aff49aa4ba0ea4a34fa101b5f14c0101c3 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Tue, 14 Jul 2020 10:00:53 +0700 Subject: [PATCH 33/33] Correct messages of validate of the client tls in the config --- src/config.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/config.rs b/src/config.rs index 086d5db..ab0dab4 100644 --- a/src/config.rs +++ b/src/config.rs @@ -30,8 +30,8 @@ pub struct Config { #[validate(regex( path = "RE_TLS_CLIENT_AUTH", - message = "Incorrect stream format", - code = "format" + message = "Incorrect tls auth", + code = "tls_client_auth" ))] #[serde(default = "default_tls_client_auth")] pub tls_client_auth: String,