use anyhow::{bail, ensure, Context, Result}; use axum::body::Body; use clap::{parser::ValueSource, Args, CommandFactory, FromArgMatches, Parser, Subcommand}; use http::{Method, Request, StatusCode}; use http_body_util::{BodyExt, Limited}; use hyper_rustls::{HttpsConnector, HttpsConnectorBuilder}; use hyper_util::{ client::legacy::{connect::HttpConnector, Client}, rt::TokioExecutor, }; use rust_proxy::{ auth, config::{self, Config, Envelope, ValidationPolicy}, db::Store, runtime::App, }; use rustls::{ client::{ danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier}, WebPkiServerVerifier, }, pki_types::{CertificateDer, ServerName, UnixTime}, ClientConfig, DigitallySignedStruct, RootCertStore, SignatureScheme, }; use sha2::{Digest, Sha256}; use std::io::{self, BufRead, IsTerminal, Read, Write}; use std::{ net::SocketAddr, path::{Path, PathBuf}, sync::Arc, time::Duration, }; use tokio::{ net::{TcpListener, UdpSocket}, task::JoinSet, }; use tracing_subscriber::prelude::*; use zeroize::Zeroizing; #[derive(Parser)] #[command( name = "rust-proxy", version, about = "RustProxy - independent Rust reverse proxy and static Web Server" )] struct Cli { #[arg( long, global = true, env = "RUST_PROXY_DATA_DIR", default_value = "/var/lib/rustproxy" )] data_dir: PathBuf, #[arg(long, global = true, env = "RUST_PROXY_CONFIG")] config: Option, #[arg( long, global = true, env = "RUST_PROXY_ADMIN_LISTEN", default_value = "127.0.0.1:9090" )] admin_listen: SocketAddr, #[arg(long, global = true, env = "RUST_PROXY_UPDATE_REPOSITORY_URL")] update_repository_url: Option, #[arg(long, global = true, env = "RUST_PROXY_UPDATE_VERSION_URL")] update_version_url: Option, #[arg(long, global = true, env = "RUST_PROXY_UPDATE_CHECK_INTERVAL_SECS")] update_check_interval_secs: Option, #[arg(long = "accept-remote-admin-risk", global = true, hide = true)] _accept_remote_admin_risk: bool, #[arg(long, global = true)] livelogs: bool, #[arg( long, global = true, env = "RUST_PROXY_HEADLESS", action = clap::ArgAction::SetTrue, value_parser = clap::builder::BoolishValueParser::new() )] headless: bool, #[command(subcommand)] command: Option, } #[derive(Subcommand)] enum Command { Serve(ServeOptions), Reload, Token, Admin { #[command(subcommand)] action: AdminCommand, }, Tls { #[command(subcommand)] action: TlsCommand, }, Config { #[command(subcommand)] action: ConfigCommand, }, Backup { #[command(subcommand)] action: BackupCommand, }, } #[derive(Subcommand)] enum AdminCommand { Init { #[arg(long)] username: Option, #[arg(long)] password_stdin: bool, }, ResetPassword { #[arg(long)] password_stdin: bool, }, SetupToken, Status, LogoutAll, } #[derive(Subcommand)] enum ConfigCommand { Get, Reload, Apply { file: PathBuf }, Validate { file: PathBuf, #[command(flatten)] tls: Box, }, } #[derive(Subcommand)] enum BackupCommand { Create { #[arg(long)] output: Option, }, Restore { archive: PathBuf, }, } #[derive(Subcommand)] enum TlsCommand { Generate { #[arg(long)] name: String, #[arg(long, value_delimiter = ',', required = true)] hosts: Vec, }, Import { #[arg(long)] name: String, #[arg(long)] cert: PathBuf, #[arg(long)] key: PathBuf, }, Deploy { #[arg(long)] id: String, #[arg(long)] cert: PathBuf, #[arg(long)] key: PathBuf, }, Reload, Renew { #[arg(long = "id", value_delimiter = ',')] ids: Vec, #[arg(long, conflicts_with = "dry_run")] force: bool, #[arg(long)] dry_run: bool, }, } #[derive(Args)] struct ServeOptions { #[arg(long, env = "RUST_PROXY_TLS_LISTEN")] tls_listen: Option, #[arg( long, env = "RUST_PROXY_PROXY_LISTEN", default_value = "127.0.0.1:8080" )] proxy_listen: SocketAddr, #[arg(long)] demo: bool, #[arg(long, env = "RUST_PROXY_DEMO_LISTEN", default_value = "127.0.0.1:9000")] demo_listen: SocketAddr, #[arg(long, default_value_t = 512)] max_connections: usize, #[arg(long, default_value_t = 256)] max_inflight: usize, #[arg(long, default_value_t = 120)] upstream_timeout_secs: u64, #[arg(long, default_value_t = 60)] body_idle_timeout_secs: u64, #[arg(long, default_value_t = 300)] websocket_idle_timeout_secs: u64, #[arg(long, default_value_t = 10)] shutdown_timeout_secs: u64, #[arg(long)] allow_remote_admin: bool, #[arg(long, env = "RUST_PROXY_HEALTH_LISTEN")] health_listen: Option, #[command(flatten)] headless_tls: Box, } #[derive(Args, Clone, Default)] struct HeadlessTlsArgs { #[arg(long = "tls-cert-file", env = "RUST_PROXY_TLS_CERT_FILE", value_delimiter = ',', value_name = "PEM")] tls_cert_file: Vec, #[arg(long = "tls-key-file", env = "RUST_PROXY_TLS_KEY_FILE", value_delimiter = ',', value_name = "PEM")] tls_key_file: Vec, #[arg(long = "tls-cert-dir", env = "RUST_PROXY_TLS_CERT_DIR", value_delimiter = ',', value_name = "DIR")] tls_cert_dir: Vec, #[arg(long = "acme-domains", env = "RUST_PROXY_ACME_DOMAINS", value_delimiter = ';', value_name = "NAMES")] acme_domains: Vec, #[arg(long = "acme-email", env = "RUST_PROXY_ACME_EMAIL")] acme_email: Option, #[arg(long = "acme-agree-tos", env = "RUST_PROXY_ACME_AGREE_TOS", action = clap::ArgAction::SetTrue, value_parser = clap::builder::BoolishValueParser::new())] acme_agree_tos: bool, #[arg(long = "acme-staging", env = "RUST_PROXY_ACME_STAGING", action = clap::ArgAction::SetTrue, value_parser = clap::builder::BoolishValueParser::new())] acme_staging: bool, #[arg(long = "acme-provider", env = "RUST_PROXY_ACME_PROVIDER", value_parser = ["http01", "cloudflare", "ovh", "rfc2136"])] acme_provider: Option, #[arg(long = "acme-dns-credentials", env = "RUST_PROXY_ACME_DNS_CREDENTIALS", value_name = "INI")] acme_dns_credentials: Option, #[arg(long = "acme-propagation-seconds", env = "RUST_PROXY_ACME_PROPAGATION_SECONDS", value_parser = clap::value_parser!(u64).range(10..=900))] acme_propagation_seconds: Option, #[arg(long = "acme-renew-days", env = "RUST_PROXY_ACME_RENEW_DAYS", value_parser = clap::value_parser!(u64).range(1..=60))] acme_renew_days: Option, #[arg(long = "acme-auto", env = "RUST_PROXY_ACME_AUTO", action = clap::ArgAction::SetTrue, value_parser = clap::builder::BoolishValueParser::new())] acme_auto: bool, #[arg(long = "route", env = "RUST_PROXY_ROUTES", value_delimiter = ';', value_name = "HOSTS=URLS")] route: Vec, #[arg(long = "force-https", env = "RUST_PROXY_FORCE_HTTPS", action = clap::ArgAction::SetTrue, value_parser = clap::builder::BoolishValueParser::new())] force_https: bool, #[arg(long = "watch", env = "RUST_PROXY_WATCH", action = clap::ArgAction::SetTrue, value_parser = clap::builder::BoolishValueParser::new())] watch: bool, } impl HeadlessTlsArgs { fn requested(&self) -> bool { !self.tls_cert_file.is_empty() || !self.tls_key_file.is_empty() || !self.tls_cert_dir.is_empty() || !self.acme_domains.is_empty() || self.acme_auto || !self.route.is_empty() || self.watch } fn resolve(self, headless: bool) -> Result { if !self.requested() { return Ok(Default::default()); } ensure!( headless, "--tls-cert-file, --tls-cert-dir, --acme-*, --route and --watch are headless options; in panel mode use the panel" ); ensure!( self.tls_cert_file.len() == self.tls_key_file.len(), "every --tls-cert-file needs a matching --tls-key-file (in the same order)" ); let cwd = std::env::current_dir()?; let absolute = |path: PathBuf| if path.is_absolute() { path } else { cwd.join(path) }; let cert_files = self .tls_cert_file .into_iter() .zip(self.tls_key_file) .map(|(cert, key)| (absolute(cert), absolute(key))) .collect(); let cert_dirs = self.tls_cert_dir.into_iter().map(absolute).collect(); let acme = rust_proxy::runtime::HeadlessAcmeSettings { domains: self .acme_domains .into_iter() .filter(|value| !value.trim().is_empty()) .map(rust_proxy::runtime::HeadlessNames::Text) .collect(), auto: self.acme_auto, email: self.acme_email, agree_tos: self.acme_agree_tos, staging: self.acme_staging, provider: self.acme_provider, dns_credentials: self.acme_dns_credentials.map(absolute), propagation_seconds: self.acme_propagation_seconds, renew_days: self.acme_renew_days, }; let routes = self .route .iter() .filter(|value| !value.trim().is_empty()) .map(|value| rust_proxy::runtime::HeadlessRoute::parse(value)) .collect::>>()?; let mut ids = std::collections::HashSet::new(); for route in &routes { ensure!(ids.insert(route.id()), "--route lists the same hosts twice"); } Ok(rust_proxy::runtime::HeadlessOptions { cert_files, cert_dirs, acme, routes, force_https: self.force_https, watch: self.watch, }) } } #[cfg(target_os = "linux")] fn disable_transparent_huge_pages() { let result = unsafe { libc::prctl(libc::PR_SET_THP_DISABLE, 1, 0, 0, 0) }; if result != 0 { eprintln!( "RustProxy warning: could not disable Transparent Huge Pages for this process: {}", io::Error::last_os_error() ); } } #[cfg(not(target_os = "linux"))] fn disable_transparent_huge_pages() {} fn main() -> Result<()> { disable_transparent_huge_pages(); let runtime = tokio::runtime::Builder::new_multi_thread() .enable_all() .build()?; let result = runtime.block_on(application()); runtime.shutdown_timeout(Duration::from_secs(2)); result } fn installed_data_dir_candidates() -> &'static [&'static str] { #[cfg(any( target_os = "freebsd", target_os = "openbsd", target_os = "netbsd", target_os = "dragonfly" ))] { return &["/var/db/rustproxy", "/var/lib/rustproxy"]; } #[cfg(not(any( target_os = "freebsd", target_os = "openbsd", target_os = "netbsd", target_os = "dragonfly" )))] { &["/var/lib/rustproxy", "/var/db/rustproxy"] } } fn resolve_installed_data_dir(configured: PathBuf, explicitly_configured: bool) -> PathBuf { if explicitly_configured || configured.join("config.sqlite3").is_file() { return configured; } installed_data_dir_candidates() .iter() .map(PathBuf::from) .find(|candidate| candidate.join("config.sqlite3").is_file()) .unwrap_or(configured) } async fn application() -> Result<()> { let error_log = rust_proxy::logging::ErrorLogController::start(); rust_proxy::logging::install_error_log_controller(error_log.clone())?; let console_router = error_log.clone(); let filter = tracing_subscriber::EnvFilter::try_from_default_env() .unwrap_or_else(|_| "rust_proxy=info,warn".into()); tracing_subscriber::registry() .with(filter) .with( tracing_subscriber::fmt::layer() .with_target(false) .with_writer(rust_proxy::logging::RedactingStderr) .with_filter(tracing_subscriber::filter::filter_fn(move |metadata| { console_router.console_enabled_for(metadata.level()) })), ) .with(rust_proxy::logging::ErrorLogLayer::new(error_log)) .init(); std::panic::set_hook(Box::new(|info| { let payload = if let Some(value) = info.payload().downcast_ref::<&str>() { (*value).to_owned() } else if let Some(value) = info.payload().downcast_ref::() { value.clone() } else { "non-string panic payload".to_owned() }; let location = info.location().map_or_else( || "unknown".to_owned(), |place| format!("{}:{}:{}", place.file(), place.line(), place.column()), ); let thread = std::thread::current(); tracing::error!( target: "rust_proxy::panic", thread = thread.name().unwrap_or("unnamed"), location = %location, panic = %payload, "RustProxy worker panicked" ); })); let matches = Cli::command().get_matches(); let explicit = |matches: &clap::ArgMatches, id: &str| { matches.value_source(id).is_some_and(|source| { matches!(source, ValueSource::CommandLine | ValueSource::EnvVariable) }) }; let serve_matches = matches.subcommand_matches("serve"); let startup_locks = rust_proxy::settings::StartupLocks { administration: explicit(&matches, "admin_listen").then(|| { *matches .get_one::("admin_listen") .expect("parsed admin listener") }), http: serve_matches .filter(|sub| explicit(sub, "proxy_listen")) .map(|sub| { *sub.get_one::("proxy_listen") .expect("parsed proxy listener") }), https: serve_matches .filter(|sub| explicit(sub, "tls_listen")) .and_then(|sub| sub.get_one::("tls_listen").copied()), }; let cli = Cli::from_arg_matches(&matches)?; let data_dir_explicit = explicit(&matches, "data_dir"); if cli.livelogs { ensure!( cli.command.is_none(), "--livelogs cannot be combined with a subcommand" ); let data_dir = resolve_installed_data_dir(cli.data_dir, data_dir_explicit); return live_logs_command(data_dir, cli.admin_listen).await; } let command = cli .command .context("a subcommand is required (or use --livelogs)")?; match command { Command::Reload if cli.headless => { signal_headless_reload(&resolve_installed_data_dir(cli.data_dir, data_dir_explicit)) } Command::Config { action: ConfigCommand::Reload, } if cli.headless => { signal_headless_reload(&resolve_installed_data_dir(cli.data_dir, data_dir_explicit)) } Command::Config { action: ConfigCommand::Validate { file, tls }, } if cli.headless => { validate_headless_file( resolve_installed_data_dir(cli.data_dir, data_dir_explicit), cli.admin_listen, file, tls.resolve(true)?, ) .await } Command::Tls { action: TlsCommand::Renew { ids, force, dry_run }, } if cli.headless => { ensure!( !dry_run, "--dry-run is not available in headless mode; use --acme-staging to test issuance" ); signal_headless_renew( &resolve_installed_data_dir(cli.data_dir, data_dir_explicit), ids, force, ) } Command::Reload => { config_command( resolve_installed_data_dir(cli.data_dir, data_dir_explicit), cli.admin_listen, ConfigCommand::Reload, ) .await } Command::Token => { admin_command( resolve_installed_data_dir(cli.data_dir, data_dir_explicit), AdminCommand::SetupToken, ) .await } Command::Admin { action } => { admin_command( resolve_installed_data_dir(cli.data_dir, data_dir_explicit), action, ) .await } Command::Tls { action } => { tls_command( resolve_installed_data_dir(cli.data_dir, data_dir_explicit), cli.admin_listen, action, ) .await } Command::Config { action } => { config_command( resolve_installed_data_dir(cli.data_dir, data_dir_explicit), cli.admin_listen, action, ) .await } Command::Backup { action } => { backup_command( resolve_installed_data_dir(cli.data_dir, data_dir_explicit), action, ) .await } Command::Serve(options) => { let update_check = rust_proxy::update_check::Config::embedded()?.with_overrides( cli.update_repository_url, cli.update_version_url, cli.update_check_interval_secs, )?; run( cli.data_dir, cli.admin_listen, options, cli.config, startup_locks, update_check, cli.headless, ) .await } } } async fn backup_command(data_dir: PathBuf, action: BackupCommand) -> Result<()> { match action { BackupCommand::Create { output } => { let output = output.unwrap_or_else(|| { PathBuf::from(format!("rustproxy-backup-{}.rpb", rust_proxy::auth::now())) }); let mut generated = false; let password = if io::stdin().is_terminal() { let value = Zeroizing::new(rpassword::prompt_password( "Backup password (leave empty to generate): ", )?); if value.is_empty() { generated = true; Zeroizing::new(rust_proxy::backup::generated_password()) } else { let confirmation = Zeroizing::new(rpassword::prompt_password("Confirm backup password: ")?); ensure!( value.as_str() == confirmation.as_str(), "backup passwords do not match" ); value } } else { generated = true; Zeroizing::new(rust_proxy::backup::generated_password()) }; let summary = rust_proxy::backup::create(&data_dir, &output, password.as_str()).await?; println!( "Encrypted backup created: {} ({} files, configuration revision {})", summary.path.display(), summary.files, summary.configuration_revision ); if generated { println!( "Generated backup password (shown once): {}", password.as_str() ); println!("Store this password securely; restore is impossible without it."); } Ok(()) } BackupCommand::Restore { archive } => { ensure!( io::stdin().is_terminal(), "backup restore requires an interactive TTY for the password" ); let password = Zeroizing::new(rpassword::prompt_password("Backup password: ")?); ensure!(!password.is_empty(), "backup password cannot be empty"); let summary = rust_proxy::backup::restore(&archive, &data_dir, password.as_str()).await?; println!( "Backup restored to {} ({} files, configuration revision {})", data_dir.display(), summary.files, summary.configuration_revision ); Ok(()) } } } fn validate_admin_binding(admin_addr: SocketAddr, tls: bool, allow_remote: bool) -> Result { let remote_admin = !admin_addr.ip().is_loopback(); ensure!( !remote_admin || tls || allow_remote, "remote plain-HTTP administration requires --allow-remote-admin" ); Ok(remote_admin) }