From c12a97642fb5fa049ddecd6afa7602c96f3fb9c3 Mon Sep 17 00:00:00 2001 From: Steve Gilvarry Date: Sun, 15 Nov 2026 23:18:23 +1100 Subject: [PATCH 1/2] fix(security): stop secrets and server paths reaching clients and logs - zmcontrol.pl's stderr went back to whoever sent a PTZ command. A control module's errors quote the camera URL, password included. - `GET /storage` showed view-only System users the S3 secret key in `Storage.Url`. - A recording that could not be probed returned its full path on the server. - A reqwest error names the URL it was sent to; `HttpClientError` now returns a generic message, as database errors do. - `auth_middleware` logged the whole URI at debug, query-string token included. - The login handler logged the username before validating it, so a line break in it forged log lines. Same for the server control action. - `DatabaseConfig`, `TurnConfig` and `SentryConfig` printed their password or DSN through `Debug`. Nothing prints them today. Co-Authored-By: Claude Fable 5.2 --- src/configure/db.rs | 29 +++++++++++++++- src/configure/sentry.rs | 12 ++++++- src/configure/streaming.rs | 23 ++++++++++++- src/dto/response/storage.rs | 37 ++++++++++++++++++++ src/error/mod.rs | 21 ++++++++++++ src/handlers/auth.rs | 8 +++-- src/handlers/events_playback.rs | 28 +++++++++++++-- src/handlers/server.rs | 4 ++- src/handlers/storage.rs | 23 +++++++++++-- src/ptz/bridge.rs | 61 ++++++++++++++++++++++++++------- src/util/middleware.rs | 9 ++++- 11 files changed, 230 insertions(+), 25 deletions(-) diff --git a/src/configure/db.rs b/src/configure/db.rs index eb330f4c..99a63b2d 100644 --- a/src/configure/db.rs +++ b/src/configure/db.rs @@ -18,7 +18,7 @@ use super::zmconf::ZmConfig; /// /// When using placeholder values in TOML (like "username", "password"), /// the actual values will be loaded from ZoneMinder's zm.conf if available. -#[derive(Debug, Deserialize, Clone)] +#[derive(Deserialize, Clone)] pub struct DatabaseConfig { #[serde(default = "default_username")] pub username: String, @@ -57,6 +57,28 @@ pub struct DatabaseConfig { pub sqlx_logging: bool, } +// Manual Debug: the config is `{:?}`-printable all the way up from +// `AppConfig`, and the password must not come out with it. +impl std::fmt::Debug for DatabaseConfig { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("DatabaseConfig") + .field("username", &self.username) + .field("password", &"[REDACTED]") + .field("port", &self.port) + .field("host", &self.host) + .field("socket", &self.socket) + .field("max_connections", &self.max_connections) + .field("min_connections", &self.min_connections) + .field("connect_timeout_secs", &self.connect_timeout_secs) + .field("acquire_timeout_secs", &self.acquire_timeout_secs) + .field("idle_timeout_secs", &self.idle_timeout_secs) + .field("max_lifetime_secs", &self.max_lifetime_secs) + .field("database_name", &self.database_name) + .field("sqlx_logging", &self.sqlx_logging) + .finish() + } +} + fn default_username() -> String { "zmuser".to_string() } @@ -307,6 +329,11 @@ mod tests { config.get_url(), "mysql://testuser:testpass@dbhost:3307/testdb?timezone=SYSTEM" ); + + // Printing the config, as a log line or a panic would, hides it. + let printed = format!("{config:?}"); + assert!(!printed.contains("testpass"), "{printed}"); + assert!(printed.contains("testuser")); } #[test] diff --git a/src/configure/sentry.rs b/src/configure/sentry.rs index d8ec9571..4bded281 100644 --- a/src/configure/sentry.rs +++ b/src/configure/sentry.rs @@ -1,7 +1,7 @@ use sentry::ClientInitGuard; use serde::Deserialize; -#[derive(Debug, Deserialize, Clone)] +#[derive(Deserialize, Clone)] pub struct SentryConfig { #[serde(default)] pub enabled: bool, @@ -9,6 +9,16 @@ pub struct SentryConfig { dsn: String, } +// Manual Debug: a DSN holds the project's ingest key. +impl std::fmt::Debug for SentryConfig { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("SentryConfig") + .field("enabled", &self.enabled) + .field("dsn", &"[REDACTED]") + .finish() + } +} + /// Initialize Sentry error reporting if enabled and DSN is configured. /// Returns None if Sentry is disabled or DSN is empty. pub fn init(config: &SentryConfig) -> Option { diff --git a/src/configure/streaming.rs b/src/configure/streaming.rs index 910cfa5b..2f868ff5 100644 --- a/src/configure/streaming.rs +++ b/src/configure/streaming.rs @@ -133,7 +133,7 @@ impl Default for WebRtcConfig { } } -#[derive(Debug, Clone, Deserialize)] +#[derive(Clone, Deserialize)] #[serde(default)] pub struct TurnConfig { pub enabled: bool, @@ -142,6 +142,18 @@ pub struct TurnConfig { pub password: String, } +// Manual Debug: the TURN password must not come out with the config. +impl std::fmt::Debug for TurnConfig { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("TurnConfig") + .field("enabled", &self.enabled) + .field("server", &self.server) + .field("username", &self.username) + .field("password", &"[REDACTED]") + .finish() + } +} + impl Default for TurnConfig { fn default() -> Self { Self { @@ -242,6 +254,15 @@ impl Default for RtspConfig { mod tests { use super::*; + #[test] + fn the_turn_password_is_not_printed_with_the_config() { + let turn = TurnConfig { + password: "hunter2".to_string(), + ..TurnConfig::default() + }; + assert!(!format!("{turn:?}").contains("hunter2")); + } + #[test] fn test_streaming_config_default() { let config = StreamingConfig::default(); diff --git a/src/dto/response/storage.rs b/src/dto/response/storage.rs index 572d892f..4315691c 100644 --- a/src/dto/response/storage.rs +++ b/src/dto/response/storage.rs @@ -30,6 +30,17 @@ pub struct StorageFilesystem { } impl StorageResponse { + /// For a caller who may view storage but not edit it: the URL without + /// its password. An S3 area's is its secret key + /// (`s3fs://KEY:SECRET@host/bucket`). + pub fn without_secrets(mut self) -> Self { + self.url = self + .url + .as_deref() + .map(crate::dto::response::monitor::hide_url_password); + self + } + /// Fill `filesystem` from the storage path (a `statvfs`). pub fn with_filesystem(mut self) -> Self { self.filesystem = crate::daemon::stats::filesystem_usage(std::path::Path::new(&self.path)) @@ -86,3 +97,29 @@ impl From> for PaginatedStorageResponse { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_viewer_does_not_get_the_s3_secret_key() { + let shown = StorageResponse { + id: 2, + name: "cloud".into(), + path: "/mnt/s3".into(), + r#type: "s3fs".into(), + scheme: "Medium".into(), + server_id: None, + url: Some("s3fs://AKIAEXAMPLE:wJalrXUtnFEMI@s3.example.com/bucket".into()), + disk_space: None, + do_delete: 1, + enabled: 1, + filesystem: None, + } + .without_secrets(); + let url = shown.url.unwrap(); + assert!(!url.contains("wJalrXUtnFEMI"), "{url}"); + assert!(url.contains("AKIAEXAMPLE") && url.contains("s3.example.com/bucket")); + } +} diff --git a/src/error/mod.rs b/src/error/mod.rs index 5de40084..f2af5e69 100644 --- a/src/error/mod.rs +++ b/src/error/mod.rs @@ -201,6 +201,13 @@ impl AppError { None => "A database error occurred".to_string(), }; } + // A reqwest error names the URL it was sent to, which can hold a + // camera's or a provider's credentials and maps out what this server + // can reach. Same treatment as a database error. + if let HttpClientError(err) = &self { + tracing::error!("outbound HTTP request failed: {err}"); + message = "A request to another service failed".to_string(); + } let (kind, code, details, status_code) = match self { InvalidPayloadError(_err) => ( "INVALID_PAYLOAD_ERROR".to_string(), @@ -616,6 +623,20 @@ mod tests { assert!(!body.error_message.contains("column")); } + /// A failed outbound request must not hand its URL to the client. + #[tokio::test] + async fn http_client_error_message_is_generic() { + // Port 1 on loopback refuses at once. + let err = reqwest::Client::new() + .get("http://admin:hunter2@127.0.0.1:1/onvif?key=s3cret") + .send() + .await + .expect_err("nothing listens on port 1"); + let (status, body) = AppError::HttpClientError(err).response(); + assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR); + assert_eq!(body.error_message, "A request to another service failed"); + } + /// GH #55: the message parser behind the "data too long" → 400 mapping. /// /// The driver's text is the only place the column name appears, so this diff --git a/src/handlers/auth.rs b/src/handlers/auth.rs index e74767d8..d46ffe8f 100644 --- a/src/handlers/auth.rs +++ b/src/handlers/auth.rs @@ -44,14 +44,16 @@ fn tokens(resp: TokenResponse) -> Tokens { pub async fn login( State(state): State, Json(req): Json, -) -> AppResult> { - info!("Login attempt for user: {}.", req.username); +) -> AppResult { + // Validate before logging: the name is the client's text until then, and + // a newline in it would forge log lines. req.validate()?; + info!("Login attempt for user: {}.", req.username); let username = req.username.clone(); match service::auth::login(&state, req).await { Ok(resp) => { info!("Successfully logged in user: {username}."); - Ok(Json(resp)) + Ok(tokens(resp)) } Err(e) => { warn!("Unsuccessfully login user error: {e:?}."); diff --git a/src/handlers/events_playback.rs b/src/handlers/events_playback.rs index bfacbad8..46a5a3f8 100644 --- a/src/handlers/events_playback.rs +++ b/src/handlers/events_playback.rs @@ -478,10 +478,19 @@ async fn event_vod_assets( let video_path = get_event_video_path(state, id, scope).await?; let info = crate::streaming::probe::probe_event_media(id, video_path.clone()) .await - .map_err(AppError::InternalServerError)?; + .map_err(|e| unreadable_recording(id, &e))?; crate::streaming::hls::vod::get_or_build(id, video_path, info) .await - .map_err(AppError::InternalServerError) + .map_err(|e| unreadable_recording(id, &e)) +} + +/// The error for a recording that couldn't be read. `detail` names the file +/// with its full path on the server, which shows the storage layout to +/// anyone who may view events. It goes to the log; the client is told only +/// which event. +fn unreadable_recording(event_id: u64, detail: &str) -> AppError { + tracing::warn!("event {event_id}: {detail}"); + AppError::InternalServerError(format!("event {event_id}'s recording could not be read")) } /// Get the fMP4 initialization segment for an event's HLS-VOD stream. @@ -745,7 +754,7 @@ pub async fn get_event_info( let info = crate::streaming::probe::probe_event_media(path.id, video_path) .await - .map_err(AppError::InternalServerError)?; + .map_err(|e| unreadable_recording(path.id, &e))?; let playable_direct = info.playable_direct(); Ok(Json(EventVideoInfo { @@ -933,6 +942,19 @@ mod tests { // parse_range_header // ------------------------------------------------------------------ + #[test] + fn an_unreadable_recording_does_not_name_its_path() { + let detail = + "open \"/var/cache/zoneminder/events/3/2026-11-15/41/41-video.mp4\": Invalid data"; + let (_, body) = unreadable_recording(41, detail).response(); + assert!( + !body.error_message.contains("/var/cache"), + "{}", + body.error_message + ); + assert!(body.error_message.contains("41")); + } + #[test] fn parse_range_header_normal_closed_range() { assert_eq!( diff --git a/src/handlers/server.rs b/src/handlers/server.rs index 6f14aa80..3a4eff90 100644 --- a/src/handlers/server.rs +++ b/src/handlers/server.rs @@ -88,7 +88,9 @@ pub async fn change_state( State(state): State, Path(action): Path, ) -> AppResult> { - info!("Handling request to change ZoneMinder state: {}", action); + // `{:?}`: the action is the caller's text, and a line break in it would + // forge a log line. + info!("Handling request to change ZoneMinder state: {:?}", action); let message = match action.to_lowercase().as_str() { "restart" => { diff --git a/src/handlers/storage.rs b/src/handlers/storage.rs index 8aafea48..3ab3c32b 100644 --- a/src/handlers/storage.rs +++ b/src/handlers/storage.rs @@ -11,6 +11,12 @@ use axum::{ use garde::Validate; use serde::Deserialize; +/// Whether the caller may edit storage, and so already knows its secrets. +fn may_edit(claims: &crate::util::claim::UserClaims) -> bool { + use crate::util::authz::{Feature, Level}; + claims.perms.level(Feature::System) >= Level::Edit +} + /// List storage definitions used by ZoneMinder for event/video storage. /// /// - Requires a valid JWT. @@ -27,9 +33,17 @@ use serde::Deserialize; )] pub async fn list_storage( State(state): State, + axum::Extension(claims): axum::Extension, Query(params): Query, ) -> AppResult> { - let result = crate::service::storage::list_paginated(&state, ¶ms).await?; + let mut result = crate::service::storage::list_paginated(&state, ¶ms).await?; + if !may_edit(&claims) { + result.items = result + .items + .into_iter() + .map(StorageResponse::without_secrets) + .collect(); + } Ok(Json(PaginatedStorageResponse::from(result))) } @@ -47,9 +61,14 @@ pub async fn list_storage( pub async fn get_storage( Path(id): Path, State(state): State, + axum::Extension(claims): axum::Extension, ) -> AppResult> { let item = crate::service::storage::get_by_id(&state, id).await?; - Ok(Json(item)) + Ok(Json(if may_edit(&claims) { + item + } else { + item.without_secrets() + })) } /// Create a new storage entry. diff --git a/src/ptz/bridge.rs b/src/ptz/bridge.rs index e54729f9..5b379daf 100644 --- a/src/ptz/bridge.rs +++ b/src/ptz/bridge.rs @@ -461,18 +461,7 @@ impl PerlControlProxy { "zmcontrol.pl failed" ); - // Parse common error conditions - let error_msg = if stderr.contains("Authentication") { - return Err(PtzError::AuthenticationFailed(stderr.to_string())); - } else if stderr.contains("not supported") { - return Err(PtzError::CommandNotSupported(stderr.to_string())); - } else if stderr.contains("Connection") || stderr.contains("timeout") { - return Err(PtzError::CameraOffline(stderr.to_string())); - } else { - format!("Exit code {}: {}", exit_code, stderr) - }; - - return Err(PtzError::PerlBridgeError(error_msg)); + return Err(classify_failure(exit_code, &stderr)); } if !stderr.is_empty() { @@ -489,6 +478,25 @@ impl PerlControlProxy { } } +/// The error for a failed zmcontrol.pl run, from what it wrote to stderr. +/// +/// The text itself stays in the log. It goes back to whoever sent the PTZ +/// command, who needs only Control access, and a control module's errors +/// quote the camera's address, which holds its user name and password. +fn classify_failure(exit_code: i32, stderr: &str) -> PtzError { + if stderr.contains("Authentication") { + PtzError::AuthenticationFailed("the camera refused the stored credentials".to_string()) + } else if stderr.contains("not supported") { + PtzError::CommandNotSupported("the camera's control does not support it".to_string()) + } else if stderr.contains("Connection") || stderr.contains("timeout") { + PtzError::CameraOffline("the camera did not answer".to_string()) + } else { + PtzError::PerlBridgeError(format!( + "zmcontrol.pl exited with code {exit_code}; see the server log" + )) + } +} + #[async_trait] impl PtzControl for PerlControlProxy { fn capabilities(&self) -> &PtzCapabilities { @@ -616,6 +624,35 @@ impl PtzControlFactory for PerlControlFactory { mod tests { use super::*; + /// A control module's error names the camera URL, password and all. The + /// caller, who may hold only Control access, must not be sent it. + #[test] + fn a_failed_command_does_not_return_what_zmcontrol_printed() { + let leaks = [ + "Authentication failed for http://admin:hunter2@10.0.0.9/cgi-bin/ptz", + "Connection refused: http://admin:hunter2@10.0.0.9/cgi-bin/ptz", + "move not supported by http://admin:hunter2@10.0.0.9", + "Can't locate object via http://admin:hunter2@10.0.0.9 at line 3", + ]; + for stderr in leaks { + let shown = classify_failure(1, stderr).to_string(); + assert!(!shown.contains("hunter2"), "{shown}"); + assert!(!shown.contains("10.0.0.9"), "{shown}"); + } + assert!(matches!( + classify_failure(1, leaks[0]), + PtzError::AuthenticationFailed(_) + )); + assert!(matches!( + classify_failure(1, leaks[1]), + PtzError::CameraOffline(_) + )); + assert!(matches!( + classify_failure(2, leaks[3]), + PtzError::PerlBridgeError(_) + )); + } + fn test_config() -> PtzConnectionConfig { PtzConnectionConfig { monitor_id: 1, diff --git a/src/util/middleware.rs b/src/util/middleware.rs index d4c0555b..8b7c7c0b 100644 --- a/src/util/middleware.rs +++ b/src/util/middleware.rs @@ -9,11 +9,18 @@ use tracing::{debug, warn}; use crate::{server::state::AppState, util::claim::UserClaims}; /// Middleware to verify JWT token for protected routes +/// +/// It does not check token revocation. Use it only inside a router that +/// [`authz::protect`](crate::util::authz::protect) or a monitor gate wraps, +/// which do; a route with a login and no feature gate takes +/// [`authenticated_middleware`]. `tests/token_revocation.rs` walks every +/// documented route with a revoked token. pub async fn auth_middleware( request: Request, next: Next, ) -> Result { - debug!("Authenticating request: {}", request.uri()); + // Path only: a query string can carry a token, which must not reach logs. + debug!("Authenticating request: {}", request.uri().path()); // Extract the authorization header let auth_header = request From 648706fdba14a1221e29e6d498e4212bd07e08b7 Mon Sep 17 00:00:00 2001 From: Steve Gilvarry Date: Sun, 15 Nov 2026 23:20:25 +1100 Subject: [PATCH 2/2] fix(security): bound network and resource use, and pin outbound targets Unauthenticated: - No listener limited how long a client could take to send request headers, so stalled connections were held open (Slowloris). All listeners now drop them after 30 seconds; a test with a control shows the difference. The plain HTTP listener moves from `axum::serve` to `axum_server`, which is what lets the timeout be set. - A request body that stalls ends after 30 idle seconds. - The rate limiter never dropped per-client entries, and counted every address in an IPv6 /64 separately. - RTSP: one address could hold every connection slot; now 16. - ONVIF discovery: a host could answer a probe with unlimited devices; now 256. Outbound: - The ONVIF client refuses this server and cloud metadata addresses, no longer follows redirects in the event listener, caps response size, and connects to the addresses it checked (DNS rebinding). - A capture path may not point at a cloud metadata service. - The client for the search models and telemetry had no timeout. Limits for logged-in users: - Frame decodes and synopsis stills: one per core. VOD packaging: two. Exports: four. On-demand worker commands: two per monitor. - WebRTC: 64 ICE candidates per session, SDP up to 64 KiB, WebSocket messages up to 256 KiB. - Generated videos: 7680 a side. Page numbers: clamped so the offset cannot overflow. The synopsis still cache and the probe cache are bounded. - The request log span records the path, not the query string, which can carry `?token=` or `?st=`. Co-Authored-By: Claude Fable 5.2 --- Cargo.lock | 1 + Cargo.toml | 3 + src/dto/pagination.rs | 21 ++++- src/dto/request/monitor.rs | 10 +++ src/handlers/event_export.rs | 23 +++++- src/handlers/live.rs | 19 +++++ src/onvif/discovery.rs | 38 +++++++++ src/onvif/error.rs | 5 ++ src/onvif/transport.rs | 108 ++++++++++++++++++++++-- src/ptz/protocols/onvif.rs | 2 + src/routes/mod.rs | 146 ++++++++++++++++++++++++++++++++- src/server/mod.rs | 144 +++++++++++++++++++++++++++----- src/server/state.rs | 68 +++++++++++++-- src/service/discovery.rs | 1 + src/service/media_jobs.rs | 47 +++++++++++ src/service/synopsis/mod.rs | 76 ++++++++++++++++- src/service/zmnext/ondemand.rs | 66 +++++++++++++++ src/streaming/hls/vod.rs | 39 ++++++++- src/streaming/live/webrtc.rs | 64 +++++++++++++++ src/streaming/live/whep.rs | 2 + src/streaming/probe.rs | 26 +++++- src/streaming/rtsp/mod.rs | 72 ++++++++++++++++ src/streaming/snapshot.rs | 44 ++++++++++ src/util/net_guard.rs | 115 ++++++++++++++++++++++++++ src/util/rate_limit.rs | 33 +++++++- 25 files changed, 1127 insertions(+), 46 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f8739b78..de7f577a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7938,6 +7938,7 @@ dependencies = [ "futures-util", "garde", "hmac 0.13.0", + "hyper-util", "iana-time-zone", "image", "insta", diff --git a/Cargo.toml b/Cargo.toml index c59e9ec5..f62ee449 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -59,6 +59,8 @@ async-trait = "0.1" axum = { version = "0.8", features = ["ws"] } axum-extra = { version = "0.12", features = ["typed-header"] } axum-server = { version = "0.8", features = ["tls-rustls"] } +# For the HTTP/1 header read timeout: hyper enforces it only with a timer. +hyper-util = { version = "0.1", features = ["tokio"] } rustls = { version = "0.23", default-features = false, features = ["ring", "std"] } rustls-pki-types = { version = "1", features = ["std"] } tokio-rustls = { version = "0.26", default-features = false, features = ["ring", "tls12", "logging"] } @@ -127,6 +129,7 @@ tower-http = { version = "0.7", features = [ "compression-gzip", "compression-br", "set-header", + "timeout", ] } tower_governor = "0.8" diff --git a/src/dto/pagination.rs b/src/dto/pagination.rs index 5c6e6018..d7ad692a 100644 --- a/src/dto/pagination.rs +++ b/src/dto/pagination.rs @@ -10,6 +10,12 @@ pub const DEFAULT_PAGE_SIZE: u64 = 25; /// Maximum page size allowed pub const MAX_PAGE_SIZE: u64 = 1000; +/// The highest page number honoured. A row offset is `page * page_size`, here +/// and inside the ORM's paginator; with a page near `u64::MAX` that multiply +/// overflows, which panics a debug build and wraps to an arbitrary offset in +/// a release one. No table has this many pages. +pub const MAX_PAGE: u64 = u32::MAX as u64; + /// Common pagination query parameters for list endpoints #[derive(Debug, Clone, Default, Deserialize, Serialize, ToSchema, Validate)] pub struct PaginationParams { @@ -27,7 +33,7 @@ pub struct PaginationParams { impl PaginationParams { /// Get the page number (1-indexed), defaulting to 1 pub fn page(&self) -> u64 { - self.page.unwrap_or(1).max(1) + self.page.unwrap_or(1).clamp(1, MAX_PAGE) } /// Get the page size, defaulting to DEFAULT_PAGE_SIZE @@ -91,6 +97,19 @@ impl PaginatedResponse { mod tests { use super::*; + /// `?page=18446744073709551615` must not overflow the offset. + #[test] + fn a_huge_page_number_does_not_overflow_the_offset() { + let params = PaginationParams { + page: Some(u64::MAX), + page_size: Some(MAX_PAGE_SIZE), + }; + assert_eq!(params.page(), MAX_PAGE); + assert_eq!(params.offset(), (MAX_PAGE - 1) * MAX_PAGE_SIZE); + // What the ORM's paginator computes from the page it is given. + assert!(params.page().checked_mul(params.page_size()).is_some()); + } + #[test] fn test_pagination_params_defaults() { let params = PaginationParams::default(); diff --git a/src/dto/request/monitor.rs b/src/dto/request/monitor.rs index 66cdd601..4a6e3945 100644 --- a/src/dto/request/monitor.rs +++ b/src/dto/request/monitor.rs @@ -92,6 +92,14 @@ pub fn is_safe_capture_path(value: &str, ctx: &()) -> garde::Result { if v.is_empty() || v.starts_with('/') { return Ok(()); } + // zmc fetches whatever this names, as the server. A camera on the same + // host is normal, so loopback stays allowed; a cloud metadata service is + // never a camera, and it answers with the instance's credentials. + if crate::util::net_guard::names_metadata_service(v) { + return Err(garde::Error::new( + "must not point at a cloud metadata service", + )); + } match v.split_once("://") { Some((scheme, _)) if CAPTURE_SCHEMES.contains(&scheme.to_ascii_lowercase().as_str()) => { Ok(()) @@ -1361,6 +1369,8 @@ mod validator_tests { #[test] fn storage_path_must_be_shell_literal() { + assert!(is_safe_capture_path("rtsp://127.0.0.1:8554/cam", &()).is_ok()); + assert!(is_safe_capture_path("http://169.254.169.254/latest/meta-data/", &()).is_err()); assert!(is_safe_storage_path("", &()).is_ok()); assert!(is_safe_storage_path("/var/cache/zoneminder/events", &()).is_ok()); assert!(is_safe_storage_path("/mnt/nas-1/zm_events.2", &()).is_ok()); diff --git a/src/handlers/event_export.rs b/src/handlers/event_export.rs index 2055795a..d8583d7b 100644 --- a/src/handlers/event_export.rs +++ b/src/handlers/event_export.rs @@ -20,6 +20,17 @@ use crate::service::monitor_acl::MonitorScope; /// (`frames.json`), `images`, `video` and `misc` (the event directory's other /// files). Every id is checked first: one that doesn't exist or isn't /// visible to the caller is a 404 and nothing is sent. +/// The most exports written at once. One reads up to 500 events' recordings +/// off the disks the cameras are recording to, and it takes only View access +/// to start one, so without a limit a viewer could start enough to stall +/// recording. +const MAX_CONCURRENT_EXPORTS: usize = 4; + +static EXPORT_SLOTS: once_cell::sync::Lazy> = + once_cell::sync::Lazy::new(|| { + std::sync::Arc::new(tokio::sync::Semaphore::new(MAX_CONCURRENT_EXPORTS)) + }); + #[utoipa::path( post, path = "/api/v3/events/export", @@ -39,9 +50,19 @@ pub async fn export_events( Json(req): Json, ) -> AppResult { req.validate().map_err(AppError::InvalidInputError)?; + // Taken before any work, held until the archive is written. + let slot = EXPORT_SLOTS.clone().try_acquire_owned().map_err(|_| { + AppError::ServiceUnavailableError(format!( + "{MAX_CONCURRENT_EXPORTS} exports are already running; try again when one finishes" + )) + })?; let exports = svc::prepare(&state, &scope, &req.ids).await?; let (writer, reader) = tokio::io::duplex(64 * 1024); - tokio::spawn(svc::write(state.clone(), exports, req.parts(), writer)); + let (state_for_write, parts) = (state.clone(), req.parts()); + tokio::spawn(async move { + let _slot = slot; + svc::write(state_for_write, exports, parts, writer).await; + }); let name = format!( "attachment; filename=\"zm-events-{}.zip\"", diff --git a/src/handlers/live.rs b/src/handlers/live.rs index d8d96fb8..f06acea9 100644 --- a/src/handlers/live.rs +++ b/src/handlers/live.rs @@ -752,6 +752,12 @@ pub async fn webrtc_websocket_handler( // hardcoded Google STUN defaults (REVIEW_FIXES_PLAN §2.2). let webrtc_config = WebRtcLiveConfig::from_webrtc_config(&state.config.streaming.webrtc); + // Signalling is an SDP answer and ICE candidates, a few kilobytes each. + // The default limit is 64 MiB a message, which a viewer could make the + // server buffer. + let ws = ws + .max_message_size(MAX_SIGNALING_BYTES) + .max_frame_size(MAX_SIGNALING_BYTES); Ok(ws.on_upgrade(move |socket| async move { let _slot = slot; handle_webrtc_websocket(state, router, monitor_id, viewer, webrtc_config, socket).await @@ -780,6 +786,9 @@ async fn inject_startup_keyframe( .await } +/// The largest signalling message a WebSocket client may send. +const MAX_SIGNALING_BYTES: usize = 256 * 1024; + /// The user a WebSocket session streams to, rechecked while it runs. #[derive(Debug, Clone, Copy)] struct Viewer { @@ -971,6 +980,16 @@ async fn handle_webrtc_websocket( match signaling_msg { WebRtcSignalingMessage::Answer { session_id: sid, sdp } if sid == session_id => { + if let Err(reason) = crate::streaming::live::webrtc::check_remote_sdp(&sdp) { + warn!("WebRTC session {}: refusing the answer: {}", session_id, reason); + let error_msg = WebRtcSignalingMessage::Error { + message: format!("Invalid SDP answer: {reason}"), + }; + if let Ok(json) = serde_json::to_string(&error_msg) { + let _ = ws_sender.send(Message::Text(json.into())).await; + } + break; + } let answer = match webrtc::peer_connection::RTCSessionDescription::answer(sdp) { Ok(a) => a, Err(e) => { diff --git a/src/onvif/discovery.rs b/src/onvif/discovery.rs index ce70db22..19b62d8b 100644 --- a/src/onvif/discovery.rs +++ b/src/onvif/discovery.rs @@ -86,6 +86,12 @@ impl ProbeMatch { } } +/// The most devices one probe returns. Replies are unauthenticated UDP, so +/// any host on the network can answer, as often and with as many devices as +/// it likes. Without a limit a flood of made-up devices grows the result, +/// and the cost of de-duplicating it, for the whole collection window. +const MAX_MATCHES: usize = 256; + /// WS-Discovery probe client. /// /// Stateless apart from configuration; one client can issue many probes. @@ -210,6 +216,9 @@ impl DiscoveryClient { if !dup { found.push(m); } + if found.len() >= MAX_MATCHES { + return Ok(found); + } } } @@ -626,6 +635,35 @@ mod tests { let _ = parse_probe_matches(""); } + /// A host that answers a probe with a flood of made-up devices gets a + /// bounded list back, and the probe ends early. + #[tokio::test] + async fn a_flood_of_replies_stops_at_the_limit() { + let camera = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap(); + let client = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap(); + let client_addr = client.local_addr().unwrap(); + + let flood = tokio::spawn(async move { + for n in 0..(MAX_MATCHES + 100) { + let reply = NORMAL.replace( + "urn:uuid:abcdef01-1234-5678-9abc-def012345678", + &format!("urn:uuid:flood-{n}"), + ); + camera.send_to(reply.as_bytes(), client_addr).await.unwrap(); + if n % 32 == 0 { + tokio::task::yield_now().await; + } + } + }); + + let dc = DiscoveryClient::new(Duration::from_secs(20)); + let started = Instant::now(); + let found = dc.collect(&client).await.unwrap(); + flood.abort(); + assert_eq!(found.len(), MAX_MATCHES); + assert!(started.elapsed() < Duration::from_secs(15)); + } + /// End-to-end socket smoke test: bind a local responder, point a client at /// the loopback, and confirm the send/collect plumbing parses a reply. /// Uses an explicit unicast send (not the multicast group) so it runs in diff --git a/src/onvif/error.rs b/src/onvif/error.rs index 85c5b1e6..9878822b 100644 --- a/src/onvif/error.rs +++ b/src/onvif/error.rs @@ -33,6 +33,11 @@ pub enum OnvifError { /// WS-Discovery failure (socket bind, multicast send/receive). #[error("discovery error: {0}")] Discovery(String), + + /// The service address reaches this server or a cloud metadata service, + /// so no request was sent. + #[error("refused: {0}")] + Refused(String), } /// Convenience result alias for ONVIF operations. diff --git a/src/onvif/transport.rs b/src/onvif/transport.rs index e58664b3..84881570 100644 --- a/src/onvif/transport.rs +++ b/src/onvif/transport.rs @@ -45,6 +45,8 @@ impl OnvifTransport { // action from the wsa:Action header rather than the Content-Type param. // Emitted for every call (harmless for Device/Media/PTZ, mandatory for // Events). MessageID is a fresh urn:uuid per request. + let pinned = ensure_target_allowed(service_url).await?; + let client = pinned.as_ref().unwrap_or(&self.client); let message_id = format!("urn:uuid:{}", uuid::Uuid::new_v4()); let wsa = wsa_headers(service_url, soap_action, &message_id); let security = match creds { @@ -59,8 +61,7 @@ impl OnvifTransport { // SOAP 1.2 carries the action in the Content-Type parameter. let content_type = format!("application/soap+xml; charset=utf-8; action=\"{soap_action}\""); - let resp = self - .client + let resp = client .post(service_url) .header(reqwest::header::CONTENT_TYPE, content_type) .timeout(timeout) @@ -76,13 +77,7 @@ impl OnvifTransport { })?; let status = resp.status(); - let text = resp.text().await.map_err(|e| { - if e.is_timeout() { - OnvifError::Timeout - } else { - OnvifError::Http(e) - } - })?; + let text = read_capped(resp).await?; // A SOAP Fault may arrive with a non-2xx status (commonly 400/500) or, // for some devices, a 200. Parse the body either way before deciding. @@ -110,6 +105,62 @@ impl OnvifTransport { } } +/// Refuse a service address that reaches this server or a cloud metadata +/// service. `service_url` is a stored `ONVIF_URL` (anyone with Monitors Edit +/// sets it) or an address a device returned, and the request carries the +/// camera's credentials. +/// Refuse a target that is this server or a metadata service. For a host +/// name, returns a client that connects only to the addresses the check saw: +/// the shared client would look the name up again, and a name that answers +/// with a camera's address first and `127.0.0.1` second (DNS rebinding) would +/// get past the check. +async fn ensure_target_allowed(service_url: &str) -> OnvifResult> { + use crate::util::net_guard::{check_and_resolve, own_addresses, Checked}; + match check_and_resolve(service_url, &own_addresses()).await { + Err(ip) => Err(OnvifError::Refused(format!( + "{service_url} reaches {ip}, which is this server or a cloud metadata address" + ))), + Ok(Checked::Literal) => Ok(None), + Ok(Checked::Name(name, addrs)) if addrs.is_empty() => { + Err(OnvifError::Refused(format!("{name} does not resolve"))) + } + Ok(Checked::Name(name, addrs)) => reqwest::Client::builder() + .no_proxy() + .redirect(reqwest::redirect::Policy::none()) + .resolve_to_addrs(&name, &addrs) + .build() + .map(Some) + .map_err(OnvifError::Http), + } +} + +/// The most a device's response may hold. ONVIF replies are a few kilobytes; +/// the largest (GetProfiles, a full PullMessages batch) stay well under this. +const MAX_RESPONSE_BYTES: usize = 4 * 1024 * 1024; + +/// The response body as text, refused once it passes [`MAX_RESPONSE_BYTES`] +/// so a device can't make the server buffer an endless reply. +async fn read_capped(mut resp: reqwest::Response) -> OnvifResult { + let mut body = Vec::new(); + loop { + let chunk = resp.chunk().await.map_err(|e| { + if e.is_timeout() { + OnvifError::Timeout + } else { + OnvifError::Http(e) + } + })?; + let Some(chunk) = chunk else { break }; + if body.len() + chunk.len() > MAX_RESPONSE_BYTES { + return Err(OnvifError::Parse(format!( + "response is larger than {MAX_RESPONSE_BYTES} bytes" + ))); + } + body.extend_from_slice(&chunk); + } + Ok(String::from_utf8_lossy(&body).into_owned()) +} + /// SOAP 1.2 envelope namespace. const SOAP_ENV_NS: &str = "http://www.w3.org/2003/05/soap-envelope"; /// WS-Addressing 1.0 namespace. @@ -310,6 +361,45 @@ fn truncate(s: &str, max: usize) -> &str { mod tests { use super::*; + /// The address may be a stored `ONVIF_URL` or one a device handed back + /// (a subscription reference, a media XAddr), so the transport itself + /// refuses this server and cloud metadata. The listener would accept a + /// connection if the request were sent. + #[tokio::test] + async fn refuses_this_server_and_metadata_before_connecting() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let transport = OnvifTransport::new(reqwest::Client::new()); + for url in [ + format!("http://127.0.0.1:{port}/onvif/event_service"), + format!("http://localhost:{port}/onvif/event_service"), + format!("http://[::ffff:127.0.0.1]:{port}/Subscription?Idx=1"), + "http://169.254.169.254/latest/meta-data/".to_string(), + ] { + let err = transport + .call(&url, "urn:x", "", None, Duration::from_secs(2)) + .await + .unwrap_err(); + assert!(matches!(err, OnvifError::Refused(_)), "{url}: {err:?}"); + } + let accepted = tokio::time::timeout(Duration::from_millis(200), listener.accept()).await; + assert!(accepted.is_err(), "a request reached the listener"); + } + + fn response_of(len: usize) -> reqwest::Response { + reqwest::Response::from(axum::http::Response::new(vec![b'a'; len])) + } + + #[tokio::test] + async fn a_response_past_the_size_cap_is_an_error() { + let ok = read_capped(response_of(MAX_RESPONSE_BYTES)).await.unwrap(); + assert_eq!(ok.len(), MAX_RESPONSE_BYTES); + let err = read_capped(response_of(MAX_RESPONSE_BYTES + 1)) + .await + .unwrap_err(); + assert!(matches!(err, OnvifError::Parse(_)), "{err:?}"); + } + #[test] fn envelope_without_header_omits_header_element() { let xml = envelope("", ""); diff --git a/src/ptz/protocols/onvif.rs b/src/ptz/protocols/onvif.rs index 11766648..cdac1878 100644 --- a/src/ptz/protocols/onvif.rs +++ b/src/ptz/protocols/onvif.rs @@ -329,6 +329,8 @@ fn map_onvif_error(err: OnvifError) -> PtzError { OnvifError::Discovery(msg) => { PtzError::ProtocolError(format!("ONVIF discovery error: {msg}")) } + // As the manager answers for a refused `ControlAddress`. + OnvifError::Refused(msg) => PtzError::InvalidParameter(msg), } } diff --git a/src/routes/mod.rs b/src/routes/mod.rs index 39d17683..67912180 100644 --- a/src/routes/mod.rs +++ b/src/routes/mod.rs @@ -277,6 +277,71 @@ fn parse_origin_rules(raw: &str) -> Vec { .collect() } +/// How long a request body may go without sending anything. The header +/// timeout (`server::bounded`) ends a request that never sends its head; this +/// ends one that sends the head and then stalls on the body, which the login +/// route would otherwise wait on for ever, from anyone. +const BODY_IDLE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30); + +/// How often a rate limiter's idle entries are dropped. +const LIMITER_SWEEP: std::time::Duration = std::time::Duration::from_secs(60); + +/// Drop a limiter's entries for clients that have not called lately. +/// +/// The limiter keeps one entry per client address and never removes any on +/// its own. The login limiter is on by default and answers before any +/// authentication, so without this anyone who can send from many addresses +/// (an IPv6 /64 is enough) grows the map until the server runs out of memory. +macro_rules! forget_idle_clients { + ($conf:expr) => {{ + let limiter = std::sync::Arc::downgrade($conf.limiter()); + run_every(LIMITER_SWEEP, move || match limiter.upgrade() { + Some(limiter) => { + limiter.retain_recent(); + true + } + // The router that owned it is gone. + None => false, + }); + }}; +} + +/// Call `f` every `period` until it returns false. Does nothing outside a +/// Tokio runtime (a router built in a plain unit test). +fn run_every(period: std::time::Duration, mut f: impl FnMut() -> bool + Send + 'static) { + let Ok(runtime) = tokio::runtime::Handle::try_current() else { + return; + }; + runtime.spawn(async move { + let mut tick = tokio::time::interval(period); + tick.tick().await; + loop { + tick.tick().await; + if !f() { + break; + } + } + }); +} + +/// What a request's log span says of its URI: the path, without the query. +/// Media URLs carry credentials there (`?token=`, `?st=`), +/// and the default span records the whole URI on every line logged while the +/// request runs, where anyone reading a debug log could lift them. +fn logged_uri(uri: &axum::http::Uri) -> &str { + uri.path() +} + +/// `TraceLayer`'s default span, with [`logged_uri`] for the URI. +fn request_span(request: &axum::http::Request) -> tracing::Span { + tracing::debug_span!( + "request", + method = %request.method(), + uri = %logged_uri(request.uri()), + version = ?request.version(), + ) +} + /// Apply the cross-cutting middleware stack to the fully-merged router. /// /// Outermost → innermost: tracing, security headers, body-size limit, @@ -320,6 +385,7 @@ fn apply_common_middleware( burst, mw.trust_proxy_headers, ); + forget_idle_clients!(conf); Some(crate::util::rate_limit::ExemptLayer::new( GovernorLayer::new(conf) .error_handler(crate::util::rate_limit::too_many_requests), @@ -344,7 +410,7 @@ fn apply_common_middleware( }); let stack = ServiceBuilder::new() - .layer(TraceLayer::new_for_http()) + .layer(TraceLayer::new_for_http().make_span_with(request_span)) .layer(SetResponseHeaderLayer::if_not_present( header::X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff"), @@ -359,6 +425,9 @@ fn apply_common_middleware( )) .option_layer(hsts_layer) .layer(DefaultBodyLimit::max(mw.body_limit_bytes)) + .layer(tower_http::timeout::RequestBodyTimeoutLayer::new( + BODY_IDLE_TIMEOUT, + )) .option_layer(rate_limit_layer) .layer(cors); @@ -414,6 +483,7 @@ pub fn create_router_app(state: AppState) -> Router { mw.auth_rate_limit_burst, mw.trust_proxy_headers, ); + forget_idle_clients!(conf); routes.layer( GovernorLayer::new(conf) .error_handler(crate::util::rate_limit::too_many_requests), @@ -871,6 +941,80 @@ mod tests { rules.iter().any(|r| r.matches(&o)) } + /// A body that stops arriving ends the request; it does not hold it open. + #[tokio::test] + async fn a_stalled_request_body_ends_the_request() { + use tower::ServiceExt; + let app: Router = Router::new() + .route( + "/echo", + axum::routing::post( + |body: axum::body::Bytes| async move { body.len().to_string() }, + ), + ) + .layer(tower_http::timeout::RequestBodyTimeoutLayer::new( + std::time::Duration::from_millis(100), + )); + // One chunk, then nothing, and never an end. + let stalled = futures_util::StreamExt::chain( + futures_util::stream::once(async { + Ok::<_, std::io::Error>(axum::body::Bytes::from("{")) + }), + futures_util::stream::pending(), + ); + let request = axum::http::Request::post("/echo") + .body(axum::body::Body::from_stream(stalled)) + .unwrap(); + let response = + tokio::time::timeout(std::time::Duration::from_secs(5), app.oneshot(request)) + .await + .expect("the request must not hang") + .unwrap(); + assert!(response.status().is_client_error(), "{}", response.status()); + } + + #[tokio::test] + async fn a_periodic_sweep_runs_until_told_to_stop() { + use std::sync::atomic::{AtomicU32, Ordering}; + let runs = std::sync::Arc::new(AtomicU32::new(0)); + let seen = runs.clone(); + run_every(std::time::Duration::from_millis(5), move || { + seen.fetch_add(1, Ordering::SeqCst) < 2 + }); + tokio::time::sleep(std::time::Duration::from_millis(200)).await; + // Three calls: two that said carry on, and the one that said stop. + assert_eq!(runs.load(Ordering::SeqCst), 3); + } + + /// The limiter's map must not keep every address it has ever seen. + #[tokio::test] + async fn an_idle_clients_rate_limit_entry_is_dropped() { + let conf = GovernorConfigBuilder::default() + .per_millisecond(1) + .burst_size(1) + .key_extractor(IpKeyExtractor::new(false, &[])) + .finish() + .unwrap(); + let limiter = conf.limiter().clone(); + for n in 0..50u8 { + let _ = limiter.check_key(&std::net::IpAddr::from([10, 0, 0, n])); + } + assert_eq!(limiter.len(), 50); + // Past the 1 ms refill, every entry is idle. + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + limiter.retain_recent(); + assert_eq!(limiter.len(), 0); + } + + #[test] + fn a_logged_uri_leaves_out_the_query_and_its_credentials() { + let uri: axum::http::Uri = + "/api/v3/monitors/1/snapshot?token=eyJhbGciOi.secret&st=1.m.1.sig" + .parse() + .unwrap(); + assert_eq!(logged_uri(&uri), "/api/v3/monitors/1/snapshot"); + } + #[test] fn any_port_rule_matches_localhost_on_any_port() { let rules = parse_origin_rules("http://localhost:*,http://127.0.0.1:*"); diff --git a/src/server/mod.rs b/src/server/mod.rs index 549213f6..b2526521 100644 --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -45,6 +45,33 @@ async fn shutdown_signal() { tracing::info!("Shutdown signal received; draining in-flight requests."); } +/// How long a client has to send a request's headers. +const HEADER_READ_TIMEOUT: Duration = Duration::from_secs(30); + +/// `server`, closing any connection that has not sent a full request head in +/// [`HEADER_READ_TIMEOUT`]. +/// +/// hyper only enforces that limit when given a timer, and neither +/// `axum::serve` nor `axum_server` gives it one. Without it a connection that +/// sends its headers a byte at a time, or never, is held open for ever, and +/// enough of them use up the process's file descriptors: nobody else can +/// connect, and no login is needed to do it (Slowloris). +fn bounded(server: axum_server::Server) -> axum_server::Server { + bounded_by(server, HEADER_READ_TIMEOUT) +} + +fn bounded_by( + mut server: axum_server::Server, + header_read_timeout: Duration, +) -> axum_server::Server { + server + .http_builder() + .http1() + .timer(hyper_util::rt::TokioTimer::new()) + .header_read_timeout(header_read_timeout); + server +} + /// Spawn a task that triggers `axum_server` graceful shutdown on a signal, /// bounding the drain with `timeout`. fn spawn_graceful_shutdown(handle: axum_server::Handle, timeout: Duration) { @@ -254,16 +281,16 @@ impl AppServer { "/.well-known/acme-challenge/{challenge_token}", challenge_service, ); - let http_server = axum_server::bind(http_addr) + let http_server = bounded(axum_server::bind(http_addr)) .handle(handle.clone()) .serve(http_router.into_make_service()); - let https_server = axum_server::bind(addr) + let https_server = bounded(axum_server::bind(addr)) .handle(handle) .acceptor(acceptor) .serve(router.into_make_service_with_connect_info::()); tokio::try_join!(https_server, http_server)?; } else { - axum_server::bind(addr) + bounded(axum_server::bind(addr)) .handle(handle) .acceptor(acceptor) .serve(router.into_make_service_with_connect_info::()) @@ -284,30 +311,29 @@ impl AppServer { let tls = tls_from_pem_files(cert_path, key_path).await?; let handle = axum_server::Handle::new(); spawn_graceful_shutdown(handle.clone(), shutdown_timeout); - axum_server::bind_rustls(addr, tls) + bounded(axum_server::bind_rustls(addr, tls)) .handle(handle) .serve(router.into_make_service_with_connect_info::()) .await?; } else { tracing::info!("Starting HTTP server on: {addr}"); - let tcp = tokio::net::TcpListener::bind(addr).await?; - // Bounded like the TLS paths: an unbounded drain let one slow - // response hold the exit past TimeoutStopSec (#116). - let deadline = async { - signalled().await; - tokio::time::sleep(shutdown_timeout).await; - }; - tokio::select! { - served = axum::serve( - tcp, - router.into_make_service_with_connect_info::(), - ) - .with_graceful_shutdown(signalled()) => served?, - _ = deadline => tracing::warn!( - "HTTP drain exceeded {:?}; exiting with requests in flight", - shutdown_timeout - ), - } + // axum_server here too, not `axum::serve`: only it lets the + // header timeout below be set. The drain is bounded like the + // TLS paths: an unbounded one let a slow response hold the + // exit past TimeoutStopSec (#116). + let handle = axum_server::Handle::new(); + tokio::spawn({ + let handle = handle.clone(); + let signal = signalled(); + async move { + signal.await; + handle.graceful_shutdown(Some(shutdown_timeout)); + } + }); + bounded(axum_server::bind(addr)) + .handle(handle) + .serve(router.into_make_service_with_connect_info::()) + .await?; } Ok(()) } @@ -353,3 +379,77 @@ pub async fn tls_from_pem_files( ) -> std::io::Result { axum_server::tls_rustls::RustlsConfig::from_pem_file(cert_path, key_path).await } + +#[cfg(test)] +mod header_timeout_tests { + use super::*; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + async fn serve(timeout: Option) -> (SocketAddr, axum_server::Handle) { + let app = axum::Router::new().route("/", axum::routing::get(|| async { "ok" })); + let handle = axum_server::Handle::new(); + let server = axum_server::bind(SocketAddr::from(([127, 0, 0, 1], 0))); + let server = match timeout { + Some(t) => bounded_by(server, t), + None => server, + }; + tokio::spawn( + server + .handle(handle.clone()) + .serve(app.into_make_service_with_connect_info::()), + ); + let addr = handle.listening().await.expect("server is listening"); + (addr, handle) + } + + /// Whether the server closes a connection that sends half a request head + /// and then nothing, within two seconds. + async fn closes_a_stalled_request(addr: SocketAddr) -> bool { + let mut conn = tokio::net::TcpStream::connect(addr).await.unwrap(); + conn.write_all(b"GET / HTTP/1.1\r\nHost: x\r\n") + .await + .unwrap(); + let mut buf = [0u8; 256]; + // Closed: the read ends (EOF, or a 408 and then EOF). Held: it hangs. + tokio::time::timeout(Duration::from_secs(2), async { + loop { + match conn.read(&mut buf).await { + Ok(0) | Err(_) => break, + Ok(_) => continue, + } + } + }) + .await + .is_ok() + } + + #[tokio::test] + async fn a_request_that_never_finishes_its_headers_is_dropped() { + let (addr, handle) = serve(Some(Duration::from_millis(200))).await; + assert!(closes_a_stalled_request(addr).await); + handle.shutdown(); + } + + /// The control: without the timer the same connection is held, which is + /// what the servers did before. + #[tokio::test] + async fn without_the_timeout_the_connection_is_held() { + let (addr, handle) = serve(None).await; + assert!(!closes_a_stalled_request(addr).await); + handle.shutdown(); + } + + #[tokio::test] + async fn a_whole_request_is_still_answered() { + let (addr, handle) = serve(Some(Duration::from_millis(200))).await; + let mut conn = tokio::net::TcpStream::connect(addr).await.unwrap(); + conn.write_all(b"GET / HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n") + .await + .unwrap(); + let mut reply = String::new(); + conn.read_to_string(&mut reply).await.unwrap(); + assert!(reply.starts_with("HTTP/1.1 200"), "{reply}"); + assert!(reply.ends_with("ok"), "{reply}"); + handle.shutdown(); + } +} diff --git a/src/server/state.rs b/src/server/state.rs index 37f210fa..f3a249ba 100644 --- a/src/server/state.rs +++ b/src/server/state.rs @@ -63,6 +63,22 @@ pub struct AppState { pub server_id: Option, } +/// How long a request to another service (the search models, telemetry) may +/// take before it is given up on. +const OUTBOUND_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(120); + +/// The client for requests to other services. reqwest has no timeout unless +/// given one, so a model server that accepted a connection and then hung +/// would hold every search that reached it open for ever, each with its task +/// and connection. +fn outbound_client(timeout: std::time::Duration) -> reqwest::Result { + reqwest::Client::builder() + .no_proxy() + .connect_timeout(timeout.min(std::time::Duration::from_secs(10))) + .timeout(timeout) + .build() +} + impl AppState { pub async fn new(mut config: AppConfig) -> AppResult { crate::configure::server::set_public_prefix(&config.server.public_prefix) @@ -110,10 +126,7 @@ impl AppState { ) .await; - let http = reqwest::Client::builder() - .no_proxy() - .build() - .expect("http client"); + let http = outbound_client(OUTBOUND_TIMEOUT).expect("http client"); // Natural-language / semantic event search. Resolves its vector backend // (probing the DB only when enabled) and creates its schema; off by @@ -415,6 +428,21 @@ impl AppState { } }; + // Its own client, which doesn't follow redirects: the transport checks + // the address it is given, and a redirect would take the request (and + // the camera's credentials) to one it didn't check. + let onvif_http = match reqwest::Client::builder() + .no_proxy() + .redirect(reqwest::redirect::Policy::none()) + .build() + { + Ok(c) => c, + Err(e) => { + tracing::warn!("ONVIF event listeners: http client: {e}"); + return; + } + }; + let mut spawned = 0usize; for m in monitors { // A deleted monitor must not get a listener inserting events (#120). @@ -429,7 +457,7 @@ impl AppState { m.onvif_password.clone(), ) }); - let transport = crate::onvif::transport::OnvifTransport::new(self.http.clone()); + let transport = crate::onvif::transport::OnvifTransport::new(onvif_http.clone()); let client = crate::onvif::events::EventsClient::new(transport, events_xaddr, creds); let alarm_cause = m .onvif_alarm_text @@ -566,3 +594,33 @@ pub fn live_services( snapshot_service, } } + +#[cfg(test)] +mod outbound_tests { + use super::*; + + /// A service that takes the connection and never answers must not hold + /// the caller for ever. + #[tokio::test] + async fn a_service_that_never_answers_is_given_up_on() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + // Accept and hold the connection open, saying nothing. + tokio::spawn(async move { + let mut held = Vec::new(); + while let Ok((conn, _)) = listener.accept().await { + held.push(conn); + } + }); + + let client = outbound_client(std::time::Duration::from_millis(200)).unwrap(); + let started = std::time::Instant::now(); + let err = client + .get(format!("http://{addr}/embed")) + .send() + .await + .expect_err("no answer ever comes"); + assert!(err.is_timeout(), "{err}"); + assert!(started.elapsed() < std::time::Duration::from_secs(5)); + } +} diff --git a/src/service/discovery.rs b/src/service/discovery.rs index 6ef82491..372ae4aa 100644 --- a/src/service/discovery.rs +++ b/src/service/discovery.rs @@ -501,6 +501,7 @@ fn onvif_to_app_error(e: OnvifError) -> AppError { warn!(error = %msg, "Malformed ONVIF response."); AppError::ServiceUnavailableError("the device's answer is not ONVIF".into()) } + OnvifError::Refused(msg) => AppError::PermissionDeniedError(msg), } } diff --git a/src/service/media_jobs.rs b/src/service/media_jobs.rs index 8ef8c870..f9e84943 100644 --- a/src/service/media_jobs.rs +++ b/src/service/media_jobs.rs @@ -103,6 +103,33 @@ pub fn video_file_name(event_name: &str, req: &GenerateVideoRequest, format: &st format!("{}.{format}", parts.join("-")) } +/// The longest side a generated video may have: 8K, the largest ZoneMinder +/// captures. +const MAX_OUTPUT_SIDE: u32 = 7680; + +/// Refuse an output larger than [`MAX_OUTPUT_SIDE`] on a side. `size` and +/// `scale` are each held to four times the event's frame, but four times an +/// 8K event is 30720x17280, close to 800 MB a frame for an encoder that holds +/// several: one request from an Events editor could take the server down. +fn output_size_allowed(req: &GenerateVideoRequest, width: u16, height: u16) -> AppResult<()> { + let (w, h) = if let Some(s) = req.scale { + (f64::from(width) * s, f64::from(height) * s) + } else if let Some((w, h)) = req.size.as_deref().and_then(|s| s.split_once('x')) { + ( + w.parse().unwrap_or(f64::INFINITY), + h.parse().unwrap_or(f64::INFINITY), + ) + } else { + return Ok(()); + }; + if w > f64::from(MAX_OUTPUT_SIDE) || h > f64::from(MAX_OUTPUT_SIDE) { + return Err(AppError::BadRequestError(format!( + "the video would be {w:.0}x{h:.0}; the most allowed is {MAX_OUTPUT_SIDE} on a side" + ))); + } + Ok(()) +} + /// The `-r`/`-R`/`-s`/`-S` parts of a generated file's name. pub fn parse_video_name(stem: &str) -> (Option, Option, Option, Option) { let num = |s: &str| s.replacen('_', ".", 1).parse::().ok(); @@ -385,6 +412,7 @@ pub async fn enqueue_video( )); } let event = visible_event(state, scope, event_id, Level::Edit).await?; + output_size_allowed(&req, event.width, event.height)?; let (formats, default) = offered_formats(state).await; let format = match req.format.take().or(default) { Some(f) if formats.contains(&f) => f, @@ -666,6 +694,25 @@ pub async fn worker(state: AppState) { mod tests { use super::*; + #[test] + fn an_output_larger_than_8k_is_refused() { + let sized = |size: &str| GenerateVideoRequest { + size: Some(size.into()), + ..Default::default() + }; + let scaled = |scale: f64| GenerateVideoRequest { + scale: Some(scale), + ..Default::default() + }; + assert!(output_size_allowed(&GenerateVideoRequest::default(), 7680, 4320).is_ok()); + assert!(output_size_allowed(&sized("1920x1080"), 640, 480).is_ok()); + assert!(output_size_allowed(&sized("7680x4320"), 640, 480).is_ok()); + assert!(output_size_allowed(&sized("99999x99999"), 640, 480).is_err()); + assert!(output_size_allowed(&sized("640x99999"), 640, 480).is_err()); + assert!(output_size_allowed(&scaled(4.0), 1920, 1080).is_ok()); + assert!(output_size_allowed(&scaled(4.0), 3840, 2160).is_err()); + } + fn req() -> GenerateVideoRequest { GenerateVideoRequest::default() } diff --git a/src/service/synopsis/mod.rs b/src/service/synopsis/mod.rs index 0ea8a704..31c9aef0 100644 --- a/src/service/synopsis/mod.rs +++ b/src/service/synopsis/mod.rs @@ -70,6 +70,45 @@ pub struct SynopsisStatusView { pub expires_at: Option, } +/// How many stills are composited at once: one per core, at least two. The +/// mp4 renders have `max_concurrent_renders`; stills had no limit, and each +/// request for one not yet cached composites it on a blocking thread, so a +/// viewer paging through events could occupy every core. Past the limit a +/// request waits its turn. +fn still_limit() -> usize { + std::thread::available_parallelism() + .map(|n| n.get()) + .unwrap_or(2) + .max(2) +} + +static STILL_SLOTS: std::sync::OnceLock = std::sync::OnceLock::new(); + +async fn still_slot() -> tokio::sync::SemaphorePermit<'static> { + STILL_SLOTS + .get_or_init(|| Semaphore::new(still_limit())) + .acquire() + .await + .expect("the still semaphore is never closed") +} + +/// The most stills kept in memory. Each is a JPEG of a few hundred kilobytes +/// and the cache is keyed by event, so without a limit a viewer paging through +/// events would grow it until the server ran out of memory. +const MAX_CACHED_STILLS: usize = 256; + +/// Cache `still`, dropping others first if the cache is full. Which ones go is +/// arbitrary: a dropped still is rendered again when next asked for. +fn remember_still(cache: &DashMap>>, id: u64, still: Arc>) { + while cache.len() >= MAX_CACHED_STILLS { + let Some(victim) = cache.iter().next().map(|e| *e.key()) else { + break; + }; + cache.remove(&victim); + } + cache.insert(id, still); +} + /// Renders, caches and serves motion synopses. Mirrors `SnapshotService`: holds /// the db handle, config, and an in-memory cache of rendered artifacts. pub struct SynopsisService { @@ -130,13 +169,14 @@ impl SynopsisService { let asset_dir = row.asset_dir.clone(); let feather = self.config.mask_feather_px; + let _slot = still_slot().await; let bytes = tokio::task::spawn_blocking(move || { compositor::render_still(&manifest, Path::new(&asset_dir), feather) }) .await??; let arc = Arc::new(bytes); - self.still_cache.insert(row.id, arc.clone()); + remember_still(&self.still_cache, row.id, arc.clone()); Ok(arc) } @@ -319,6 +359,7 @@ impl SynopsisService { let max_tubes = self.config.max_tubes_per_frame.max(1).saturating_mul(8); let feather = self.config.mask_feather_px; + let _slot = still_slot().await; let bytes = tokio::task::spawn_blocking(move || { compositor::render_overview_still(&parsed, &class_filter, max_tubes, feather) }) @@ -433,3 +474,36 @@ async fn run_render( Ok(out.to_string_lossy().into_owned()) } + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn stills_past_the_limit_wait_their_turn() { + let mut held = Vec::new(); + for _ in 0..still_limit() { + held.push(still_slot().await); + } + let waiting = + tokio::time::timeout(std::time::Duration::from_millis(50), still_slot()).await; + assert!(waiting.is_err()); + drop(held); + assert!( + tokio::time::timeout(std::time::Duration::from_secs(5), still_slot()) + .await + .is_ok() + ); + } + + #[test] + fn the_still_cache_stops_growing_at_its_limit() { + let cache = DashMap::new(); + for id in 0..(MAX_CACHED_STILLS as u64 + 50) { + remember_still(&cache, id, Arc::new(vec![0u8; 8])); + } + assert_eq!(cache.len(), MAX_CACHED_STILLS); + // The newest is always kept. + assert!(cache.contains_key(&(MAX_CACHED_STILLS as u64 + 49))); + } +} diff --git a/src/service/zmnext/ondemand.rs b/src/service/zmnext/ondemand.rs index b80f2093..7e8861f4 100644 --- a/src/service/zmnext/ondemand.rs +++ b/src/service/zmnext/ondemand.rs @@ -81,12 +81,65 @@ async fn send( "live streaming is disabled, so there is no worker connection".into(), ) })?; + let _slot = IN_FLIGHT + .try_acquire(monitor_id, MAX_IN_FLIGHT_PER_MONITOR) + .ok_or_else(|| { + AppError::ServiceUnavailableError(format!( + "monitor {monitor_id}'s worker is already answering \ + {MAX_IN_FLIGHT_PER_MONITOR} requests; try again shortly" + )) + })?; router .send_command(monitor_id, command, timeout) .await .map_err(command_error) } +/// The most on-demand commands one monitor's worker is sent at a time. Anyone +/// who may view the monitor can ask for a description, which runs a language +/// model on the worker for up to the describe timeout. Unlimited, a viewer in +/// a loop would keep the worker's model busy and starve its own detection. +const MAX_IN_FLIGHT_PER_MONITOR: usize = 2; + +static IN_FLIGHT: once_cell::sync::Lazy = once_cell::sync::Lazy::new(InFlight::default); + +/// How many commands each monitor's worker is answering. +#[derive(Default)] +struct InFlight(std::sync::Mutex>); + +/// One command in flight, counted until dropped. +struct InFlightSlot<'a> { + counts: &'a InFlight, + monitor_id: u32, +} + +impl InFlight { + fn try_acquire(&self, monitor_id: u32, limit: usize) -> Option> { + let mut counts = self.0.lock().unwrap_or_else(|p| p.into_inner()); + let held = counts.entry(monitor_id).or_insert(0); + if *held >= limit { + return None; + } + *held += 1; + Some(InFlightSlot { + counts: self, + monitor_id, + }) + } +} + +impl Drop for InFlightSlot<'_> { + fn drop(&mut self) { + let mut counts = self.counts.0.lock().unwrap_or_else(|p| p.into_inner()); + if let Some(held) = counts.get_mut(&self.monitor_id) { + *held -= 1; + if *held == 0 { + counts.remove(&self.monitor_id); + } + } + } +} + fn command_error(e: CommandError) -> AppError { // All of these mean the worker, not the caller, couldn't deliver. AppError::ServiceUnavailableError(e.to_string()) @@ -143,6 +196,19 @@ fn u32_field(detail: &Value, key: &str) -> Option { #[cfg(test)] mod tests { + #[test] + fn a_monitors_worker_is_sent_only_so_many_commands_at_once() { + let counts = super::InFlight::default(); + let a = counts.try_acquire(7, 2).unwrap(); + let _b = counts.try_acquire(7, 2).unwrap(); + assert!(counts.try_acquire(7, 2).is_none()); + // Another monitor has its own allowance. + assert!(counts.try_acquire(8, 2).is_some()); + // A finished command frees its place. + drop(a); + assert!(counts.try_acquire(7, 2).is_some()); + } + use super::*; #[tokio::test] diff --git a/src/streaming/hls/vod.rs b/src/streaming/hls/vod.rs index 5745b0fd..d596254a 100644 --- a/src/streaming/hls/vod.rs +++ b/src/streaming/hls/vod.rs @@ -170,6 +170,16 @@ fn cached(id: u64, stamp: Option) -> Option> { .get(id, stamp, Instant::now()) } +/// How many recordings are packaged at once. Packaging reads the whole +/// recording into memory, and the per-event lock below only stops the same +/// event being built twice. A viewer opening many long events together would +/// otherwise have them all in memory at the same time; past this many, a +/// build waits for one to finish. +const MAX_CONCURRENT_BUILDS: usize = 2; + +static BUILD_SLOTS: tokio::sync::Semaphore = + tokio::sync::Semaphore::const_new(MAX_CONCURRENT_BUILDS); + fn locks() -> &'static DashMap>> { static LOCKS: OnceLock>>> = OnceLock::new(); LOCKS.get_or_init(DashMap::new) @@ -196,6 +206,10 @@ pub async fn get_or_build( Some(a) => Ok(a), None => { let target = Duration::from_secs(VOD_SEGMENT_SECONDS); + let _slot = BUILD_SLOTS + .acquire() + .await + .expect("the build semaphore is never closed"); let built = tokio::task::spawn_blocking(move || { package_blocking(&video_path, info, target) }) @@ -296,11 +310,13 @@ fn read_extradata(params: &ffmpeg_next::codec::Parameters) -> Vec { // `params`; we only read the extradata slice it points at. unsafe { let p = params.as_ptr(); - let size = (*p).extradata_size as usize; - if size == 0 || (*p).extradata.is_null() { + // `extradata_size` is a C int: a negative one cast to usize would + // ask for a slice of nearly the whole address space. + let size = (*p).extradata_size; + if size <= 0 || (*p).extradata.is_null() { return Vec::new(); } - std::slice::from_raw_parts((*p).extradata, size).to_vec() + std::slice::from_raw_parts((*p).extradata, size as usize).to_vec() } } @@ -337,6 +353,23 @@ fn build_playlist(segments: &[FMP4Segment], target: Duration) -> String { mod tests { use super::*; + /// A build past the limit waits for a place instead of starting. + #[tokio::test] + async fn only_so_many_recordings_are_packaged_at_once() { + let mut held = Vec::new(); + for _ in 0..MAX_CONCURRENT_BUILDS { + held.push(BUILD_SLOTS.acquire().await.unwrap()); + } + let waiting = tokio::time::timeout(Duration::from_millis(50), BUILD_SLOTS.acquire()).await; + assert!(waiting.is_err(), "a build past the limit must wait"); + drop(held); + assert!( + tokio::time::timeout(Duration::from_secs(5), BUILD_SLOTS.acquire()) + .await + .is_ok() + ); + } + fn assets(bytes: usize) -> Arc { Arc::new(VodAssets { init: vec![0; bytes], diff --git a/src/streaming/live/webrtc.rs b/src/streaming/live/webrtc.rs index 1d1c9fa1..9d8ae832 100644 --- a/src/streaming/live/webrtc.rs +++ b/src/streaming/live/webrtc.rs @@ -487,6 +487,43 @@ pub struct WebRtcLiveSession { pub created_at: chrono::DateTime, packets_sent: AtomicU64, bytes_sent: AtomicU64, + /// Candidates the viewer has sent so far. + remote_candidates: AtomicU64, +} + +/// The most ICE candidates a viewer may send for one session. A real client +/// sends a handful. Each is paired with every local candidate and probed, so +/// a viewer sending them without end would keep the server checking +/// connectivity to addresses of the viewer's choosing. +const MAX_REMOTE_CANDIDATES: u64 = 64; + +/// The largest SDP a viewer may send. Real offers and answers are a few +/// kilobytes. +const MAX_SDP_BYTES: usize = 64 * 1024; + +/// Refuse a viewer's SDP that is far larger than any real one, or that +/// carries more candidates than [`MAX_REMOTE_CANDIDATES`]: candidates in the +/// SDP are probed like trickled ones, and would otherwise get round that +/// limit. +pub fn check_remote_sdp(sdp: &str) -> Result<(), String> { + if sdp.len() > MAX_SDP_BYTES { + return Err(format!("the SDP is larger than {MAX_SDP_BYTES} bytes")); + } + let candidates = sdp + .lines() + .filter(|l| l.trim_start().starts_with("a=candidate:")) + .count() as u64; + if candidates > MAX_REMOTE_CANDIDATES { + return Err(format!( + "the SDP lists {candidates} ICE candidates; at most {MAX_REMOTE_CANDIDATES}" + )); + } + Ok(()) +} + +/// Count one more candidate against `sent`; false once past the limit. +fn candidate_allowed(sent: &AtomicU64) -> bool { + sent.fetch_add(1, Ordering::Relaxed) < MAX_REMOTE_CANDIDATES } impl WebRtcLiveSession { @@ -1047,6 +1084,7 @@ impl WebRtcLiveManager { created_at: chrono::Utc::now(), packets_sent: AtomicU64::new(0), bytes_sent: AtomicU64::new(0), + remote_candidates: AtomicU64::new(0), }; let session_id_str = session_id.to_string(); self.sessions @@ -1329,6 +1367,11 @@ impl WebRtcLiveManager { .ok_or_else(|| WebRtcLiveError::SessionNotFound(session_id.to_string()))?; let session = session_lock.read().await; + if !candidate_allowed(&session.remote_candidates) { + return Err(WebRtcLiveError::WebRtcError(format!( + "more than {MAX_REMOTE_CANDIDATES} ICE candidates for one session" + ))); + } let ice_candidate = RTCIceCandidateInit { candidate: candidate.to_string(), @@ -1569,6 +1612,27 @@ impl MediaPump { mod tests { use super::*; + #[test] + fn an_oversized_or_candidate_stuffed_sdp_is_refused() { + let line = "a=candidate:1 1 UDP 2122252543 192.0.2.1 50000 typ host\r\n"; + let ok = format!("v=0\r\n{}", line.repeat(8)); + assert!(check_remote_sdp(&ok).is_ok()); + let stuffed = format!("v=0\r\n{}", line.repeat(MAX_REMOTE_CANDIDATES as usize + 1)); + assert!(check_remote_sdp(&stuffed).is_err()); + let huge = format!("v=0\r\na=x:{}\r\n", "y".repeat(MAX_SDP_BYTES)); + assert!(check_remote_sdp(&huge).is_err()); + } + + #[test] + fn a_session_takes_only_so_many_ice_candidates() { + let sent = AtomicU64::new(0); + for _ in 0..MAX_REMOTE_CANDIDATES { + assert!(candidate_allowed(&sent)); + } + assert!(!candidate_allowed(&sent)); + assert!(!candidate_allowed(&sent)); + } + #[test] fn test_webrtc_live_config_default() { let config = WebRtcLiveConfig::default(); diff --git a/src/streaming/live/whep.rs b/src/streaming/live/whep.rs index 3be1022e..ca6070e3 100644 --- a/src/streaming/live/whep.rs +++ b/src/streaming/live/whep.rs @@ -83,6 +83,8 @@ impl WhepSessions { uid: u32, offer_sdp: String, ) -> Result<(String, String), WhepError> { + crate::streaming::live::webrtc::check_remote_sdp(&offer_sdp) + .map_err(WhepError::BadOffer)?; let router = state .source_router .as_ref() diff --git a/src/streaming/probe.rs b/src/streaming/probe.rs index abcb1b11..8e28f74c 100644 --- a/src/streaming/probe.rs +++ b/src/streaming/probe.rs @@ -34,6 +34,20 @@ fn cache() -> &'static DashMap { CACHE.get_or_init(DashMap::new) } +/// The most probe results kept. One is added for every event anyone plays +/// and none was ever dropped, so over a long uptime the cache grew with the +/// number of events ever recorded. +const MAX_CACHED_PROBES: usize = 10_000; + +/// Cache `info`, starting over when the cache is full. A dropped result +/// costs one more probe of that file. +fn remember(cache: &DashMap, event_id: u64, info: MediaInfo) { + if cache.len() >= MAX_CACHED_PROBES { + cache.clear(); + } + cache.insert(event_id, info); +} + /// Probe an event's video file, caching the result by event id. pub async fn probe_event_media(event_id: u64, path: PathBuf) -> Result { if let Some(info) = cache().get(&event_id) { @@ -42,7 +56,7 @@ pub async fn probe_event_media(event_id: u64, path: PathBuf) -> Result Result { mod tests { use super::*; + #[test] + fn the_probe_cache_does_not_grow_without_limit() { + let cache = DashMap::new(); + for id in 0..(MAX_CACHED_PROBES as u64 + 10) { + remember(&cache, id, info(VideoCodec::H264)); + } + assert!(cache.len() <= MAX_CACHED_PROBES); + assert!(cache.contains_key(&(MAX_CACHED_PROBES as u64 + 9))); + } + fn info(codec: VideoCodec) -> MediaInfo { MediaInfo { codec, diff --git a/src/streaming/rtsp/mod.rs b/src/streaming/rtsp/mod.rs index 45bb585f..ecd709e9 100644 --- a/src/streaming/rtsp/mod.rs +++ b/src/streaming/rtsp/mod.rs @@ -128,6 +128,8 @@ pub async fn start(state: AppState, shutdown: watch::Receiver) { state: state.clone(), }; let slots = Arc::new(Semaphore::new(cfg.max_connections.max(1))); + // Shared by the plain and TLS listeners: an address is one client. + let per_address = PerAddress::default(); let tls = match cfg.tls_port { None => None, @@ -170,16 +172,63 @@ pub async fn start(state: AppState, shutdown: watch::Receiver) { acceptor, backend.clone(), slots.clone(), + per_address.clone(), shutdown.clone(), )); } } +/// The most connections one address may hold at a time. A connection takes a +/// slot before it has shown a signed link, and keeps it for up to 15 seconds +/// without one, so with only the overall limit a single host could hold every +/// slot and shut all viewers out. Sixteen leaves room for a recorder pulling +/// many cameras from one address. +const MAX_PER_ADDRESS: usize = 16; + +/// How many connections each address holds. +#[derive(Clone, Default)] +struct PerAddress(Arc>>); + +/// One address's connection, counted until dropped. +struct AddressSlot { + counts: PerAddress, + ip: std::net::IpAddr, +} + +impl PerAddress { + /// A slot for `ip`, unless it already holds `limit`. + fn try_acquire(&self, ip: std::net::IpAddr, limit: usize) -> Option { + let mut counts = self.0.lock().unwrap_or_else(|p| p.into_inner()); + let held = counts.entry(ip).or_insert(0); + if *held >= limit { + return None; + } + *held += 1; + Some(AddressSlot { + counts: self.clone(), + ip, + }) + } +} + +impl Drop for AddressSlot { + fn drop(&mut self) { + let mut counts = self.counts.0.lock().unwrap_or_else(|p| p.into_inner()); + if let Some(held) = counts.get_mut(&self.ip) { + *held -= 1; + if *held == 0 { + counts.remove(&self.ip); + } + } + } +} + async fn accept_loop( listener: TcpListener, tls: Option, backend: ZmBackend, slots: Arc, + per_address: PerAddress, mut shutdown: watch::Receiver, ) { loop { @@ -194,6 +243,10 @@ async fn accept_loop( }, _ = async { let _ = shutdown.wait_for(|v| *v).await; } => return, }; + let Some(address_slot) = per_address.try_acquire(peer.ip(), MAX_PER_ADDRESS) else { + warn!("rtsp: {peer} already holds {MAX_PER_ADDRESS} connections; refusing another"); + continue; + }; let Ok(permit) = slots.clone().try_acquire_owned() else { warn!("rtsp: connection limit reached; refusing {peer}"); continue; @@ -203,6 +256,7 @@ async fn accept_loop( let tls = tls.clone(); tokio::spawn(async move { let _permit = permit; + let _address_slot = address_slot; let peer = peer.to_string(); match tls { None => session::serve(sock, backend, peer).await, @@ -264,6 +318,24 @@ mod tests { use super::*; use crate::configure::streaming::RtspConfig; + #[test] + fn one_address_cannot_take_every_connection() { + let counts = PerAddress::default(); + let hog: std::net::IpAddr = "203.0.113.7".parse().unwrap(); + let viewer: std::net::IpAddr = "198.51.100.2".parse().unwrap(); + + let held: Vec<_> = (0..3) + .map(|_| counts.try_acquire(hog, 3).unwrap()) + .collect(); + assert!(counts.try_acquire(hog, 3).is_none()); + // Someone else is not affected. + assert!(counts.try_acquire(viewer, 3).is_some()); + // A closed connection frees its place, and an idle address is forgotten. + drop(held); + assert!(counts.try_acquire(hog, 3).is_some()); + assert!(counts.0.lock().unwrap().is_empty()); + } + #[test] fn links_use_the_public_host_or_the_request_host() { let mut cfg = RtspConfig::default(); diff --git a/src/streaming/snapshot.rs b/src/streaming/snapshot.rs index 5ab07de7..459a857f 100644 --- a/src/streaming/snapshot.rs +++ b/src/streaming/snapshot.rs @@ -186,6 +186,7 @@ impl SnapshotService { codec: VideoCodec, ) -> Result, SnapshotError> { let data = video_data.to_vec(); + let _slot = decode_slot().await; tokio::task::spawn_blocking(move || Self::decode_to_jpeg_blocking(&data, codec)) .await .map_err(|e| SnapshotError::DecodeFailed(format!("Task join error: {}", e)))? @@ -305,6 +306,31 @@ impl SnapshotService { } } +/// How many frames may be decoded at once: one per core, and at least two. +/// +/// Each snapshot, thumbnail and frame request decodes video on a blocking +/// thread, and Tokio will start hundreds of those. A viewer asking for many +/// at once (a page of thumbnails, or on purpose) would have every core +/// decoding and nothing left for capture or the API. Requests past the limit +/// wait their turn. +fn decode_limit() -> usize { + std::thread::available_parallelism() + .map(|n| n.get()) + .unwrap_or(2) + .max(2) +} + +static DECODE_SLOTS: std::sync::OnceLock = std::sync::OnceLock::new(); + +/// Wait for a place to decode. Dropped when the decode is done. +async fn decode_slot() -> tokio::sync::SemaphorePermit<'static> { + DECODE_SLOTS + .get_or_init(|| tokio::sync::Semaphore::new(decode_limit())) + .acquire() + .await + .expect("the decode semaphore is never closed") +} + /// Extract the first decodable video frame from an MP4 and encode it as JPEG. /// /// Async wrapper around the blocking libav pipeline; runs on a blocking thread @@ -315,6 +341,7 @@ pub async fn extract_mp4_thumbnail( path: PathBuf, max_width: u32, ) -> Result, SnapshotError> { + let _slot = decode_slot().await; tokio::task::spawn_blocking(move || extract_mp4_thumbnail_blocking(&path, None, max_width)) .await .map_err(|e| SnapshotError::DecodeFailed(format!("Task join error: {}", e)))? @@ -329,6 +356,7 @@ pub async fn extract_mp4_frame_at( seconds: f64, max_width: u32, ) -> Result, SnapshotError> { + let _slot = decode_slot().await; tokio::task::spawn_blocking(move || { extract_mp4_thumbnail_blocking(&path, Some(seconds.max(0.0)), max_width) }) @@ -637,6 +665,22 @@ impl KeyframeCollector { mod tests { use super::*; + /// Decodes past the limit wait; they are not all started at once. + #[tokio::test] + async fn decodes_are_limited_to_the_number_of_cores() { + assert!(decode_limit() >= 2); + let held: Vec<_> = + futures_util::future::join_all((0..decode_limit()).map(|_| decode_slot())).await; + // Every place is taken, so one more has to wait. + let waiting = + tokio::time::timeout(std::time::Duration::from_millis(50), decode_slot()).await; + assert!(waiting.is_err(), "a decode past the limit must wait"); + drop(held); + // And gets its turn once one finishes. + let turn = tokio::time::timeout(std::time::Duration::from_secs(5), decode_slot()).await; + assert!(turn.is_ok()); + } + /// Build a single-NAL `VideoPacket`. `nal_type` is the raw NAL header byte /// (lower 5 bits select the type: 7 = SPS, 8 = PPS, 5 = IDR slice). fn nal_packet(nal_type: u8, ts: i64, is_keyframe: bool) -> VideoPacket { diff --git a/src/util/net_guard.rs b/src/util/net_guard.rs index 3d41a09e..71627541 100644 --- a/src/util/net_guard.rs +++ b/src/util/net_guard.rs @@ -29,6 +29,38 @@ pub fn own_addresses() -> Vec { .collect() } +/// Whether `address` names a cloud metadata service outright: its literal +/// address, or one of the names providers give it. No lookup is made, so this +/// suits request validation; it does not catch a name of the caller's own +/// that resolves there. +pub fn names_metadata_service(address: &str) -> bool { + match address_host(address) { + Some((url::Host::Ipv4(v4), _)) => METADATA.contains(&IpAddr::V4(v4)), + Some((url::Host::Ipv6(v6), _)) => { + let ip = v6.to_ipv4_mapped().map_or(IpAddr::V6(v6), IpAddr::V4); + METADATA.contains(&ip) + } + Some((url::Host::Domain(name), _)) => { + // Only http(s) URLs get their host parsed as an address; in an + // `rtsp://` one an IP arrives here as a name. + let name = name.trim_end_matches('.').to_ascii_lowercase(); + let bare = name.trim_start_matches('[').trim_end_matches(']'); + match bare.parse::() { + Ok(IpAddr::V6(v6)) => { + METADATA.contains(&v6.to_ipv4_mapped().map_or(IpAddr::V6(v6), IpAddr::V4)) + } + Ok(ip) => METADATA.contains(&ip), + Err(_) => { + name == "metadata.google.internal" + || name == "metadata" + || name == "instance-data" + } + } + } + None => false, + } +} + /// Whether `ip` is this server (loopback, the unspecified address, one of /// `own`) or a cloud metadata service. IPv4-mapped IPv6 counts as IPv4. pub fn is_server_or_metadata(ip: IpAddr, own: &[IpAddr]) -> bool { @@ -73,10 +105,93 @@ pub async fn forbidden_target(address: &str, own: &[IpAddr]) -> Option { ips.into_iter().find(|&ip| is_server_or_metadata(ip, own)) } +/// What a checked address resolved to. +#[derive(Debug, PartialEq, Eq)] +pub enum Checked { + /// A literal IP (or no network host at all): nothing to pin. + Literal, + /// A host name and the addresses it resolved to, all allowed. Connect to + /// these and not to the name: a second lookup may answer differently + /// (DNS rebinding), handing the request to an address this check refused. + Name(String, Vec), +} + +/// Check `address` as [`forbidden_target`] does and say what it resolved to, +/// so the caller can connect to exactly the addresses that were checked. +/// `Err` holds the forbidden address. +pub async fn check_and_resolve(address: &str, own: &[IpAddr]) -> Result { + let Some((host, port)) = address_host(address) else { + return Ok(Checked::Literal); + }; + let name = match host { + url::Host::Ipv4(v4) => return literal(IpAddr::V4(v4), own), + url::Host::Ipv6(v6) => return literal(IpAddr::V6(v6), own), + url::Host::Domain(name) => name, + }; + let addrs: Vec = tokio::net::lookup_host((name.as_str(), port)) + .await + .map(|a| a.collect()) + .unwrap_or_default(); + match addrs.iter().find(|a| is_server_or_metadata(a.ip(), own)) { + Some(bad) => Err(bad.ip()), + None => Ok(Checked::Name(name, addrs)), + } +} + +fn literal(ip: IpAddr, own: &[IpAddr]) -> Result { + if is_server_or_metadata(ip, own) { + Err(ip) + } else { + Ok(Checked::Literal) + } +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn metadata_services_are_recognised_by_address_and_name() { + for yes in [ + "http://169.254.169.254/latest/meta-data/", + "rtsp://169.254.169.254:554/x", + "http://[::ffff:169.254.169.254]/", + "http://metadata.google.internal/computeMetadata/v1/", + ] { + assert!(names_metadata_service(yes), "{yes}"); + } + for no in [ + "rtsp://192.168.1.10/stream", + "http://127.0.0.1:8554/cam", + "/dev/video0", + "", + ] { + assert!(!names_metadata_service(no), "{no}"); + } + } + + #[tokio::test] + async fn a_checked_name_comes_back_with_the_addresses_it_was_checked_as() { + // Literals need no pinning. + assert_eq!( + check_and_resolve("http://192.168.1.10/onvif", &[]).await, + Ok(Checked::Literal) + ); + assert!(check_and_resolve("http://127.0.0.1/onvif", &[]) + .await + .is_err()); + // `localhost` resolves, to loopback, which is refused. + assert!(check_and_resolve("http://localhost:8080/onvif", &[]) + .await + .is_err()); + // A name that doesn't resolve is pinned to nothing, so the request + // can't go anywhere unchecked. + assert_eq!( + check_and_resolve("http://no-such-host.invalid/onvif", &[]).await, + Ok(Checked::Name("no-such-host.invalid".into(), vec![])) + ); + } + #[tokio::test] async fn refuses_the_server_and_metadata_however_written() { for address in [ diff --git a/src/util/rate_limit.rs b/src/util/rate_limit.rs index b8dd7a96..c2af8828 100644 --- a/src/util/rate_limit.rs +++ b/src/util/rate_limit.rs @@ -134,7 +134,20 @@ impl KeyExtractor for IpKeyExtractor { .get::>() .map(|ConnectInfo(a)| a.ip()) .ok_or(GovernorError::UnableToExtractKey)?; - Ok(self.client_ip(peer, req.headers())) + Ok(limit_key(self.client_ip(peer, req.headers()))) + } +} + +/// The address a client is counted under. An IPv6 client is its /64: a +/// subscriber is given at least that many addresses, so counting each one +/// separately would hand them 2^64 allowances and no limit on login guesses. +fn limit_key(ip: IpAddr) -> IpAddr { + match canonical(ip) { + IpAddr::V6(v6) => { + let s = v6.segments(); + IpAddr::V6(std::net::Ipv6Addr::new(s[0], s[1], s[2], s[3], 0, 0, 0, 0)) + } + v4 => v4, } } @@ -317,6 +330,21 @@ mod tests { use super::*; use std::net::Ipv4Addr; + #[test] + fn ipv6_clients_are_counted_by_their_64() { + let key = |s: &str| limit_key(s.parse().unwrap()); + // Two addresses a single subscriber can pick at will: one bucket. + assert_eq!( + key("2001:db8:1:2::1"), + key("2001:db8:1:2:ffff:ffff:ffff:ffff") + ); + // Another /64 is another client. + assert_ne!(key("2001:db8:1:2::1"), key("2001:db8:1:3::1")); + // IPv4 is counted per address, mapped or not. + assert_eq!(key("203.0.113.9"), key("::ffff:203.0.113.9")); + assert_ne!(key("203.0.113.9"), key("203.0.113.10")); + } + fn defaults(trust_proxy: bool) -> IpKeyExtractor { let list: Vec = DEFAULT_TRUSTED_PROXIES .iter() @@ -434,7 +462,8 @@ mod tests { ); assert_eq!( key(&e, "127.0.0.1", &[("x-forwarded-for", "[2001:db8::1]")]), - ip("2001:db8::1") + // The limiter's key for an IPv6 client is its /64. + ip("2001:db8::") ); // A v4-mapped peer is loopback too. assert_eq!(