- Introduced `relay_dual_lock_race_harness_security_tests.rs` to validate user liveness during lock hold and release cycles.
- Added `relay_quota_extended_attack_surface_security_tests.rs` to cover various quota scenarios including positive, negative, edge cases, and adversarial conditions.
- Implemented `relay_quota_lock_eviction_lifecycle_tdd_tests.rs` to ensure proper eviction of stale entries and lifecycle management of quota locks.
- Created `relay_quota_lock_eviction_stress_security_tests.rs` to stress test the eviction mechanism under high churn conditions.
- Enhanced `relay_quota_lock_pressure_adversarial_tests.rs` to verify reclaiming of unreferenced entries after explicit eviction.
- Developed `relay_quota_retry_allocation_latency_security_tests.rs` to benchmark and validate latency and allocation behavior under contention.
This commit introduces a comprehensive set of improvements to enhance
the security, reliability, and configurability of the proxy server,
specifically targeting adversarial resilience and high-load concurrency.
Security & Cryptography:
- Zeroize MTProto cryptographic key material (`dec_key`, `enc_key`)
immediately after use to prevent memory leakage on early returns.
- Move TLS handshake replay tracking after full policy/ALPN validation
to prevent cache poisoning by unauthenticated probes.
- Add `proxy_protocol_trusted_cidrs` configuration to restrict PROXY
protocol headers to trusted networks, rejecting spoofed IPs.
Adversarial Resilience & DoS Mitigation:
- Implement "Tiny Frame Debt" tracking in the middle-relay to prevent
CPU exhaustion from malicious 0-byte or 1-byte frame floods.
- Add `mask_relay_max_bytes` to strictly bound unauthenticated fallback
connections, preventing the proxy from being abused as an open relay.
- Add a 5ms prefetch window (`mask_classifier_prefetch_timeout_ms`) to
correctly assemble and classify fragmented HTTP/1.1 and HTTP/2 probes
(e.g., `PRI * HTTP/2.0`) before routing them to masking heuristics.
- Prevent recursive masking loops (FD exhaustion) by verifying the mask
target is not the proxy's own listener via local interface enumeration.
Concurrency & Reliability:
- Eliminate executor waker storms during quota lock contention by replacing
the spin-waker task with inline `Sleep` and exponential backoff.
- Roll back user quota reservations (`rollback_me2c_quota_reservation`)
if a network write fails, preventing Head-of-Line (HoL) blocking from
permanently burning data quotas.
- Recover gracefully from idle-registry `Mutex` poisoning instead of
panicking, ensuring isolated thread failures do not break the proxy.
- Fix `auth_probe_scan_start_offset` modulo logic to ensure bounds safety.
Testing:
- Add extensive adversarial, timing, fuzzing, and invariant test suites
for both the client and handshake modules.
- Introduced `handshake_real_bug_stress_tests.rs` to validate TLS and MTProto handshake behaviors under various conditions, including ALPN rejection and session ID handling.
- Implemented tests to ensure replay cache integrity and proper handling of malicious input without panicking.
- Added `handshake_timing_manual_bench_tests.rs` for performance benchmarking of user authentication paths, comparing preferred user handling against full user scans in both MTProto and TLS contexts.
- Included timing-sensitive tests to measure the impact of SNI on handshake performance.
Implement logging infrastructure for non-systemd platforms:
- Add src/logging.rs with syslog and file logging support
- New CLI flags: --syslog, --log-file, --log-file-daily
- Syslog uses libc directly with LOG_DAEMON facility
- File logging via tracing-appender with optional daily rotation
Update service scripts:
- OpenRC and FreeBSD rc.d now use --syslog by default
- Ensures logs are captured on platforms without journald
Default (stderr) behavior unchanged for systemd compatibility.
Log destination is selected at startup based on CLI flags.
Signed-off-by: Vladimir Krivopalov <argenet@yandex.ru>
Implement automatic init system detection and service file generation
for systemd, OpenRC (Alpine/Gentoo), and FreeBSD rc.d:
- Add src/service module with init system detection and generators
- Auto-detect init system via filesystem probes
- Generate platform-appropriate service files during --init
systemd enhancements:
- ExecReload for SIGHUP config reload
- PIDFile directive
- Comprehensive security hardening (ProtectKernelTunables,
RestrictAddressFamilies, MemoryDenyWriteExecute, etc.)
- CAP_NET_BIND_SERVICE for privileged ports
OpenRC support:
- Standard openrc-run script with depend/reload functions
- Directory setup in start_pre
FreeBSD rc.d support:
- rc.subr integration with rc.conf variables
- reload extra command
The --init command now detects the init system and runs the
appropriate enable/start commands (systemctl, rc-update, sysrc).
Signed-off-by: Vladimir Krivopalov <argenet@yandex.ru>
Implement CLI subcommands for managing telemt as a daemon:
- `start [config.toml]` - Start as background daemon (implies --daemon)
- `stop` - Stop running daemon by sending SIGTERM
- `reload` - Reload configuration by sending SIGHUP
- `status` - Check if daemon is running via PID file
Subcommands use the PID file (default /var/run/telemt.pid) to locate
the running daemon. Stop command waits up to 10 seconds for graceful
shutdown. Status cleans up stale PID files automatically.
Updated help text with subcommand documentation and usage examples.
Exit codes follow Unix convention: 0 for success, 1 for not running
or error.
Signed-off-by: Vladimir Krivopalov <argenet@yandex.ru>
Enhance signal handling to support proper daemon operation:
- SIGTERM: Graceful shutdown (same behavior as SIGINT)
- SIGQUIT: Graceful shutdown with full statistics dump
- SIGUSR1: Log rotation acknowledgment for external tools
- SIGUSR2: Dump runtime status to log without stopping
Statistics dump includes connection counts, ME keepalive metrics,
and relay adaptive tuning counters. SIGHUP config reload unchanged
(handled in hot_reload.rs).
Signals are handled via tokio::signal::unix with async select!
to avoid blocking the runtime. Non-shutdown signals (USR1/USR2)
run in a background task spawned at startup.
Signed-off-by: Vladimir Krivopalov <argenet@yandex.ru>
Implement core daemon infrastructure for running telemt as a background
service on Unix platforms (Linux, FreeBSD, etc.):
- Add src/daemon module with classic double-fork daemonization
- Implement flock-based PID file management to prevent duplicate instances
- Add privilege dropping (setuid/setgid) after socket binding
- New CLI flags: --daemon, --foreground, --pid-file, --run-as-user,
--run-as-group, --working-dir
Daemonization occurs before tokio runtime starts to ensure clean fork.
PID file uses exclusive locking to detect already-running instances.
Privilege dropping happens after bind_listeners() to allow binding
to privileged ports (< 1024) before switching to unprivileged user.
Signed-off-by: Vladimir Krivopalov <argenet@yandex.ru>