From 296c281f152889733e3df90c4c408a40050d3685 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Fri, 3 Jul 2020 11:42:56 +0700 Subject: [PATCH 1/3] 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 80e416d01d7a3feb022adffe9fdeb90516c6f678 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Fri, 3 Jul 2020 13:49:43 +0700 Subject: [PATCH 2/3] 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 3/3] 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