diff --git a/Cargo.toml b/Cargo.toml index fc29f13..6610062 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,13 +13,15 @@ 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", "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/README.md b/README.md index 5246bc7..c583af5 100644 --- a/README.md +++ b/README.md @@ -98,6 +98,29 @@ By default Neolink serves on all IP addresses on port 8554. You can modify this by changing the `bind` and the `bind_port` parameter. You only need one `bind`/`bind_port` setting at the top of the config file. +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. + +TLS is disabled by default. + +You can password-protect the Neolink server by adding `[[users]]`` sections to the configuration file: +``` +[[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"] +``` + +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 + +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/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" diff --git a/src/config.rs b/src/config.rs index 5ee198b..ab0dab4 100644 --- a/src/config.rs +++ b/src/config.rs @@ -4,12 +4,13 @@ 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! { 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)] @@ -23,6 +24,21 @@ 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: Option, + + #[validate(regex( + path = "RE_TLS_CLIENT_AUTH", + message = "Incorrect tls auth", + code = "tls_client_auth" + ))] + #[serde(default = "default_tls_client_auth")] + pub tls_client_auth: String, + + #[validate] + #[serde(default = "default_users")] + pub users: Vec, } #[derive(Debug, Deserialize, Validate, Clone)] @@ -52,6 +68,20 @@ pub struct CameraConfig { ))] #[serde(default = "default_stream")] pub stream: String, + + #[serde(default = "default_permitted_users")] + pub permitted_users: Option>, +} + +#[derive(Debug, Deserialize, Validate, Clone)] +pub struct UserConfig { + #[validate(required, custom = "validate_username")] + #[serde(alias = "username")] + pub name: Option, + + #[validate(required)] + #[serde(alias = "password")] + pub pass: Option, } fn default_bind_addr() -> String { @@ -69,3 +99,27 @@ fn default_format() -> String { fn default_stream() -> String { "both".to_string() } + +fn default_certificate() -> Option { + None +} + +fn default_tls_client_auth() -> String { + "none".to_string() +} + +fn default_permitted_users() -> Option> { + None +} + +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/gst.rs b/src/gst.rs index 31afce7..128b2e8 100644 --- a/src/gst.rs +++ b/src/gst.rs @@ -3,14 +3,23 @@ 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 gio::{TlsAuthenticationMode, TlsCertificate}; +use gstreamer_rtsp::RTSPAuthMethod; use gstreamer_rtsp_server::prelude::*; -use gstreamer_rtsp_server::{RTSPAuth, RTSPMediaFactory, RTSPServer as GstRTSPServer}; +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::collections::HashSet; +use std::fs; use std::io; use std::io::Write; +use itertools::Itertools; type Result = std::result::Result; @@ -32,7 +41,12 @@ impl RtspServer { } } - pub fn add_stream(&self, paths: &[&str], stream_format: &StreamFormat) -> Result { + pub fn add_stream( + &self, + paths: &[&str], + stream_format: &StreamFormat, + permitted_users: &HashSet, + ) -> Result { let mounts = self .server .get_mount_points() @@ -45,6 +59,15 @@ impl RtspServer { }; let factory = RTSPMediaFactory::new(); + + debug!( + "Permitting {} to access {}", + // 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); + //factory.set_protocols(RTSPLowerTrans::TCP); factory.set_launch(&format!("{}{}{}{}", "( ", @@ -84,21 +107,70 @@ 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 - }); + 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(), + &[ + (*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)], + )); + } + } - self.server.set_auth(auth.as_ref()); + 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); + let token = RTSPToken::new(&[(*RTSP_TOKEN_MEDIA_FACTORY_ROLE, user)]); + let basic = RTSPAuth::make_basic(user, pass); + auth.add_basic(basic.as_str(), &token); + } + } + + self.server.set_auth(Some(&auth)); + Ok(()) + } + + pub fn set_tls(&self, cert_file: &str, client_auth: TlsAuthenticationMode) -> Result<()> { + debug!("Setting up TLS using {}", cert_file); + let auth = self.server.get_auth().unwrap_or_else(|| RTSPAuth::new()); + + // 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); + + self.server.set_auth(Some(&auth)); Ok(()) } diff --git a/src/main.rs b/src/main.rs index f0620ab..3ea49bf 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,9 +1,11 @@ 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; @@ -15,7 +17,7 @@ mod cmdline; mod config; use cmdline::Opt; -use config::{CameraConfig, Config}; +use config::{CameraConfig, Config, UserConfig}; #[derive(Debug, Error)] pub enum Error { @@ -45,6 +47,10 @@ fn main() -> Result<(), Error> { let rtsp = &RtspServer::new(); + set_up_tls(&config, &rtsp); + + set_up_users(&config.users, &rtsp); + crossbeam::scope(|s| { for camera in config.cameras { let stream_format = match &*camera.format { @@ -58,6 +64,7 @@ fn main() -> Result<(), Error> { "h264" | "H264" | "h265" | "H265" => StreamFormat::H264, 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 @@ -70,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).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).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)); } @@ -131,6 +142,76 @@ 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, + _ => unreachable!(), + }; + 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 { + 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(_), 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."); +} + +fn get_permitted_users( + users: &Vec, + permitted_users: &Option>, +) -> HashSet { + 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" + // Then we add all users to the cameras config. including unauth + let mut new_permitted_users = HashSet::new(); + if current_permitted_users.contains(&"anyone".to_string()) { + for credentials in users { + if let Some(user) = &credentials.name { + new_permitted_users.insert(user.to_string()); + } + } + } else { + for user in current_permitted_users { + new_permitted_users.insert(user.to_string()); + } + } + new_permitted_users +} + fn camera_main( camera_config: &CameraConfig, stream_name: &str,