Commit Graph

125 Commits

Author SHA1 Message Date
Alexey d7bbb376c9
Format 2026-03-21 15:45:29 +03:00
David Osipov c1ee43fbac
Add stress testing for quota-lock and refactor test guard usage 2026-03-21 15:54:14 +04:00
David Osipov c8632de5b6
Update dependencies and refactor random number generation
- Bump versions of several dependencies in Cargo.toml for improved functionality and security, including:
  - socket2 to 0.6
  - nix to 0.31
  - toml to 1.0
  - x509-parser to 0.18
  - dashmap to 6.1
  - rand to 0.10
  - reqwest to 0.13
  - notify to 8.2
  - ipnetwork to 0.21
  - webpki-roots to 1.0
  - criterion to 0.8
- Introduce `OnceLock` for secure random number generation in multiple modules to ensure thread safety and reduce overhead.
- Refactor random number generation calls to use the new `RngExt` trait methods for consistency and clarity.
- Add new PNG files for architectural documentation.
2026-03-21 15:43:07 +04:00
David Osipov b930ea1ec5
Add regression and security tests for relay quota and TLS stream handling
- Introduced regression tests for relay quota wake liveness to ensure proper handling of contention and wake events.
- Added adversarial tests to validate the behavior of the quota system under stress and contention scenarios.
- Implemented security tests for the TLS stream to verify the preservation of pending plaintext during state transitions.
- Enhanced the pool writer tests to ensure proper quarantine behavior and validate the removal of writers from the registry.
- Included fuzz testing to assess the robustness of the quota and TLS handling mechanisms against unexpected inputs and states.
2026-03-21 15:16:20 +04:00
David Osipov 3b86a883b9
Add comprehensive tests for relay quota management and adversarial scenarios
- Introduced `relay_quota_boundary_blackhat_tests.rs` to validate behavior under quota limits, including edge cases and adversarial conditions.
- Added `relay_quota_model_adversarial_tests.rs` to ensure quota management maintains integrity during bidirectional communication and various load scenarios.
- Created `relay_quota_overflow_regression_tests.rs` to address overflow issues and ensure that quota limits are respected during aggressive data transmission.
- Implemented `route_mode_coherence_adversarial_tests.rs` to verify the consistency of route mode transitions and timestamp management across different relay modes.
2026-03-21 14:14:58 +04:00
David Osipov 5933b5e821
Refactor and enhance tests for proxy and relay functionality
- Renamed test functions in `client_tls_clienthello_truncation_adversarial_tests.rs` to remove "but_leaks" suffix for clarity.
- Added new tests in `direct_relay_business_logic_tests.rs` to validate business logic for data center resolution and scope hints.
- Introduced tests in `direct_relay_common_mistakes_tests.rs` to cover common mistakes in direct relay configurations.
- Added security tests in `direct_relay_security_tests.rs` to ensure proper handling of symlink and parent swap scenarios.
- Created `direct_relay_subtle_adversarial_tests.rs` to stress test concurrent logging and validate scope hint behavior.
- Implemented `relay_quota_lock_pressure_adversarial_tests.rs` to test quota lock behavior under high contention and stress.
- Updated `relay_security_tests.rs` to include quota lock contention tests ensuring proper behavior under concurrent access.
- Introduced `ip_tracker_hotpath_adversarial_tests.rs` to validate the performance and correctness of the IP tracking logic under various scenarios.
2026-03-21 13:38:17 +04:00
David Osipov 8188fedf6a
Add masking shape classifier and guard tests for adversarial resistance
- Implemented tests for masking shape classifier resistance against threshold attacks, ensuring that blurring reduces accuracy and increases overlap between classes.
- Added tests for masking shape guard functionality, verifying that it maintains expected behavior under various conditions, including timeout paths and clean EOF scenarios.
- Introduced helper functions for calculating accuracy and handling timing samples to support the new tests.
- Ensured that the masking shape hardening configuration is properly utilized in tests to validate its effectiveness.
2026-03-21 12:43:25 +04:00
David Osipov bb355e916f
Add comprehensive security tests for masking and shape hardening features
- Introduced red-team expected-fail tests for client masking shape hardening.
- Added integration tests for masking AB envelope blur to improve obfuscation.
- Implemented masking security tests to validate the behavior of masking under various conditions.
- Created tests for masking shape above-cap blur to ensure proper functionality.
- Developed adversarial tests for masking shape hardening to evaluate robustness against attacks.
- Added timing normalization security tests to assess the effectiveness of timing obfuscation.
- Implemented red-team expected-fail tests for timing side-channel vulnerabilities.
2026-03-21 00:30:51 +04:00
David Osipov ebd37932c5
Merge latest upstream/main into test/main-into-flow-sec 2026-03-20 23:21:22 +04:00
David Osipov 43d7e6e991
moved tests to subdirs 2026-03-20 22:55:19 +04:00
David Osipov 0eca535955
Refactor TLS fallback tests to remove unnecessary client hello assertions
- Removed assertions for expected client hello messages in multiple TLS fallback tests to streamline the test logic.
- Updated the tests to focus on verifying the trailing TLS records received after the fallback.
- Enhanced the masking functionality by adding shape hardening features, including dynamic padding based on sent data size.
- Modified the relay_to_mask function to accommodate new parameters for shape hardening.
- Updated masking security tests to reflect changes in the relay_to_mask function signature.
2026-03-20 22:44:39 +04:00
David Osipov 3abde52de8
refactor: update TLS record size constants and related validations
- Rename MAX_TLS_RECORD_SIZE to MAX_TLS_PLAINTEXT_SIZE for clarity.
- Rename MAX_TLS_CHUNK_SIZE to MAX_TLS_CIPHERTEXT_SIZE to reflect its purpose.
- Deprecate old constants in favor of new ones.
- Update various parts of the codebase to use the new constants, including validation checks and tests.
- Add new tests to ensure compliance with RFC 8446 regarding TLS record sizes.
2026-03-20 21:00:36 +04:00
David Osipov 801f670827
Add comprehensive TLS ClientHello size validation and adversarial tests
- Refactor existing tests to improve clarity and specificity in naming.
- Introduce new tests for minimum and maximum TLS ClientHello sizes, ensuring proper masking behavior for malformed probes.
- Implement differential timing tests to compare latency between malformed TLS and plain web requests, ensuring similar performance characteristics.
- Add adversarial tests for truncated TLS ClientHello probes, verifying that even malformed traffic is masked as legitimate responses.
- Enhance the overall test suite for robustness against probing attacks, focusing on edge cases and potential vulnerabilities in TLS handling.
2026-03-20 20:30:02 +04:00
David Osipov babd902d95
Add adversarial tests for MTProto handshake and enhance masking functionality
- Introduced multiple adversarial tests for MTProto handshake to ensure robustness against replay attacks, invalid mutations, and concurrent flooding.
- Implemented a function to build proxy headers based on the specified version, improving the handling of masking protocols.
- Added tests to validate the behavior of the masking functionality under various conditions, including unknown proxy protocol versions and oversized payloads.
- Enhanced relay tests to ensure stability and performance under high load and half-close scenarios.
2026-03-20 18:48:19 +04:00
David Osipov 35a8f5b2e5
Add method to retrieve inner reader with pending plaintext
This commit introduces the `into_inner_with_pending_plaintext` method to the `FakeTlsReader` struct. This method allows users to extract the underlying reader along with any pending plaintext data that may have been buffered during the TLS reading process. The method handles the state transition and ensures that any buffered data is returned as a vector, facilitating easier management of plaintext data in TLS streams.
2026-03-20 17:56:37 +04:00
David Osipov 8f1ffe8c25
fix(proxy): исправление wire-transparency при fallback и усиление безопасности
Исправлена критическая логическая ошибка в цепочке Fake TLS -> MTProto.
Ранее при валидном TLS-хендшейке, но неверном MTProto-пакете, прокси
ошибочно передавал в маскирующий релей обернутый (FakeTls) поток.
Теперь транспорт корректно разворачивается (unwrap) до сырого сокета
через .into_inner(), обеспечивая полную прозрачность (wire-transparency)
для DPI и маскирующего бэкенда.

Security & Hardening:
- Логика приведена в соответствие с требованиями OWASP ASVS L2 (V5: Validation, Sanitization and Encoding).
- Реализовано поведение "fail-closed": при любой ошибке верификации прокси мимикрирует под обычный веб-сервер, не раскрывая своей роли.
- Улучшена диагностика и логирование состояний аутентификации для защиты от активного пробинга.

Adversarial Testing (Black-hat mindset):
- Добавлен отдельный пакет `client_tls_mtproto_fallback_security_tests.rs` (18+ тестов).
- Покрыты сценарии: хаос-фрагментация (побайтовая нарезка TLS-записей), record-splitting,
  half-close состояния, сбросы бэкенда и replay-pressure.
- В `client_adversarial_tests.rs` добавлено 10+ тестов на "злые" гонки (race conditions),
  утечки лимитов по IP и проверку изоляции состояний параллельных сессий.
- Все 832 теста проходят (passed) в locked-режиме.
2026-03-20 17:33:46 +04:00
David Osipov a78c3e3ebd
One more small test fix 2026-03-20 16:48:14 +04:00
David Osipov a4b70405b8
Add adversarial tests module for client security testing 2026-03-20 16:47:26 +04:00
David Osipov 512bee6a8d
Add security tests for middle relay idle policy and enhance stats tracking
- Introduced a new test module for middle relay idle policy security tests, covering various scenarios including soft mark, hard close, and grace periods.
- Implemented functions to create crypto readers and encrypt data for testing.
- Enhanced the Stats struct to include counters for relay idle soft marks, hard closes, pressure evictions, and protocol desync closes.
- Added corresponding increment and retrieval methods for the new stats fields.
2026-03-20 16:43:50 +04:00
David Osipov 7dc3c3666d
Merge upstream/main into test/main-into-flow-sec 2026-03-20 14:20:20 +04:00
David Osipov 7416829e89
Merge remote-tracking branch 'upstream/main' into test/main-into-flow-sec
# Conflicts:
#	Cargo.toml
#	src/api/model.rs
#	src/api/runtime_stats.rs
#	src/transport/middle_proxy/health.rs
#	src/transport/middle_proxy/health_regression_tests.rs
#	src/transport/middle_proxy/pool_status.rs
2026-03-19 23:48:40 +04:00
David Osipov c07b600acb
Integration hardening: reconcile main+flow-sec API drift and restore green suite 2026-03-19 20:24:44 +04:00
David Osipov 7b44496706
Integration test merge: upstream/main into flow-sec security branch (prefer flow-sec on conflicts) 2026-03-19 19:42:04 +04:00
Alexey dd8ef4d996
Merge branch 'main' into feat/shadowsocks-upstream 2026-03-19 17:19:01 +03:00
David Osipov e6ad9e4c7f
Add security tests for connection limits and handshake integrity
- Implement a test to ensure that exceeding the user connection limit does not leak the current connections counter.
- Add tests for direct relay connection refusal and adversarial scenarios to verify proper error handling.
- Introduce fuzz testing for MTProto handshake to ensure robustness against malformed inputs and replay attacks.
- Remove obsolete short TLS probe throttle tests and integrate their functionality into existing security tests.
- Enhance middle relay tests to validate behavior during connection drops and cutovers, ensuring graceful error handling.
- Add a test for half-close scenarios in relay to confirm bidirectional data flow continues as expected.
2026-03-19 17:31:19 +04:00
David Osipov 2a01ca2d6f
Add adversarial tests for client, handshake, masking, and relay modules
- Introduced `client_adversarial_tests.rs` to stress test connection limits and IP tracker race conditions.
- Added `handshake_adversarial_tests.rs` for mutational bit-flipping tests and timing neutrality checks.
- Created `masking_adversarial_tests.rs` to validate probing indistinguishability and SSRF prevention.
- Implemented `relay_adversarial_tests.rs` to ensure HOL blocking prevention and data quota enforcement.
- Updated respective modules to include new test paths.
2026-03-19 17:31:19 +04:00
David Osipov c7cf37898b
feat: enhance quota user lock management and testing
- Adjusted QUOTA_USER_LOCKS_MAX based on test and non-test configurations to improve flexibility.
- Implemented logic to retain existing locks when the maximum quota is reached, ensuring efficient memory usage.
- Added comprehensive tests for quota user lock functionality, including cache reuse, saturation behavior, and race conditions.
- Enhanced StatsIo struct to manage wake scheduling for read and write operations, preventing unnecessary self-wakes.
- Introduced separate replay checker domains for handshake and TLS to ensure isolation and prevent cross-pollution of keys.
- Added security tests for replay checker to validate domain separation and window clamping behavior.
2026-03-18 23:55:08 +04:00
Alexey 89e5668c7e
Runtime guardrails
Co-Authored-By: brekotis <93345790+brekotis@users.noreply.github.com>
2026-03-18 22:33:41 +03:00
David Osipov 20e205189c
Enhance TLS Emulator with ALPN Support and Add Adversarial Tests
- Modified `build_emulated_server_hello` to accept ALPN (Application-Layer Protocol Negotiation) as an optional parameter, allowing for the embedding of ALPN markers in the application data payload.
- Implemented logic to handle oversized ALPN values and ensure they do not interfere with the application data payload.
- Added new security tests in `emulator_security_tests.rs` to validate the behavior of the ALPN embedding, including scenarios for oversized ALPN and preference for certificate payloads over ALPN markers.
- Introduced `send_adversarial_tests.rs` to cover edge cases and potential issues in the middle proxy's send functionality, ensuring robustness against various failure modes.
- Updated `middle_proxy` module to include new test modules and ensure proper handling of writer commands during data transmission.
2026-03-18 17:04:50 +04:00
Maxim Myalin def42f0baa
Add Shadowsocks upstream support 2026-03-18 12:36:44 +03:00
Alexey 3739f38440
Adaptive Buffers + Session Eviction Method 2026-03-18 10:49:02 +03:00
David Osipov 97d4a1c5c8
Refactor and enhance security in proxy and handshake modules
- Updated `direct_relay_security_tests.rs` to ensure sanitized paths are correctly validated against resolved paths.
- Added tests for symlink handling in `unknown_dc_log_path_revalidation` to prevent symlink target escape vulnerabilities.
- Modified `handshake.rs` to use a more robust hashing strategy for eviction offsets, improving the eviction logic in `auth_probe_record_failure_with_state`.
- Introduced new tests in `handshake_security_tests.rs` to validate eviction logic under various conditions, ensuring low fail streak entries are prioritized for eviction.
- Simplified `route_mode.rs` by removing unnecessary atomic mode tracking, streamlining the transition logic in `RouteRuntimeController`.
- Enhanced `route_mode_security_tests.rs` with comprehensive tests for mode transitions and their effects on session states, ensuring consistency under concurrent modifications.
- Cleaned up `emulator.rs` by removing unused ALPN extension handling, improving code clarity and maintainability.
2026-03-18 01:40:38 +04:00
David Osipov c2443e6f1a
Refactor auth probe eviction logic and improve performance
- Simplified eviction candidate selection in `auth_probe_record_failure_with_state` by tracking the oldest candidate directly.
- Enhanced the handling of stale entries to ensure newcomers are tracked even under capacity constraints.
- Added tests to verify behavior under stress conditions and ensure newcomers are correctly managed.
- Updated `decode_user_secrets` to prioritize preferred users based on SNI hints.
- Introduced new tests for TLS SNI handling and replay protection mechanisms.
- Improved deduplication hash stability and collision resistance in middle relay logic.
- Refined cutover handling in route mode to ensure consistent error messaging and session management.
2026-03-18 00:38:59 +04:00
David Osipov a7cffb547e
Implement idle timeout for masking relay and add corresponding tests
- Introduced `copy_with_idle_timeout` function to handle reading and writing with an idle timeout.
- Updated the proxy masking logic to use the new idle timeout function.
- Added tests to verify that idle relays are closed by the idle timeout before the global relay timeout.
- Ensured that connect refusal paths respect the masking budget and that responses followed by silence are cut off by the idle timeout.
- Added tests for adversarial scenarios where clients may attempt to drip-feed data beyond the idle timeout.
2026-03-17 22:48:13 +04:00
David Osipov f0c37f233e
Refactor health management: implement remove_writer_if_empty method for cleaner writer removal logic and update related functions to enhance efficiency in handling closed writers. 2026-03-17 21:38:15 +04:00
David Osipov 60953bcc2c
Refactor user connection limit checks and enhance health monitoring tests: update warning messages, add new tests for draining writers, and improve state management 2026-03-17 20:53:37 +04:00
David Osipov 2c06288b40
Enhance UserConnectionReservation: add runtime handle for cross-thread IP cleanup and implement tests for user expiration and connection limits 2026-03-17 20:21:01 +04:00
David Osipov 4e3f42dce3
Add must_use attribute to UserConnectionReservation and RouteConnectionLease structs for better resource management 2026-03-17 19:55:55 +04:00
David Osipov d81140ccec
Enhance UserConnectionReservation management: add active state and release method, improve cleanup on drop, and implement tests for immediate release and concurrent handling 2026-03-17 19:39:29 +04:00
David Osipov c540a6657f
Implement user connection reservation management and enhance relay task handling in proxy 2026-03-17 19:05:26 +04:00
David Osipov 1357f3cc4c
bump version to 3.3.20 and implement connection lease management for direct and middle relays 2026-03-17 18:16:17 +04:00
David Osipov 93caab1aec
feat(proxy): refactor auth probe failure handling and add concurrent failure tests 2026-03-17 16:25:29 +04:00
David Osipov 0c6bb3a641
feat(proxy): implement auth probe eviction logic and corresponding tests 2026-03-17 15:43:07 +04:00
David Osipov b2e15327fe
feat(proxy): enhance auth probe handling with IPv6 normalization and eviction logic 2026-03-17 15:15:12 +04:00
David Osipov 8821e38013
feat(proxy): enhance auth probe capacity with stale entry pruning and new tests 2026-03-17 02:19:14 +04:00
David Osipov a1caebbe6f
feat(proxy): implement timeout handling for client payload reads and add corresponding tests 2026-03-17 01:53:44 +04:00
David Osipov 205fc88718
feat(proxy): enhance logging and deduplication for unknown datacenters
- Implemented a mechanism to log unknown datacenter indices with a distinct limit to avoid excessive logging.
- Introduced tests to ensure that logging is deduplicated per datacenter index and respects the distinct limit.
- Updated the fallback logic for datacenter resolution to prevent panics when only a single datacenter is available.

feat(proxy): add authentication probe throttling

- Added a pre-authentication probe throttling mechanism to limit the rate of invalid TLS and MTProto handshake attempts.
- Introduced a backoff strategy for repeated failures and ensured that successful handshakes reset the failure count.
- Implemented tests to validate the behavior of the authentication probe under various conditions.

fix(proxy): ensure proper flushing of masked writes

- Added a flush operation after writing initial data to the mask writer to ensure data integrity.

refactor(proxy): optimize desynchronization deduplication

- Replaced the Mutex-based deduplication structure with a DashMap for improved concurrency and performance.
- Implemented a bounded cache for deduplication to limit memory usage and prevent stale entries from persisting.

test(proxy): enhance security tests for middle relay and handshake

- Added comprehensive tests for the middle relay and handshake processes, including scenarios for deduplication and authentication probe behavior.
- Ensured that the tests cover edge cases and validate the expected behavior of the system under load.
2026-03-17 01:29:30 +04:00
David Osipov e4a50f9286
feat(tls): add boot time timestamp constant and validation for SNI hostnames
- Introduced `BOOT_TIME_MAX_SECS` constant to define the maximum accepted boot-time timestamp.
- Updated `validate_tls_handshake_at_time` to utilize the new boot time constant for timestamp validation.
- Enhanced `extract_sni_from_client_hello` to validate SNI hostnames against specified criteria, rejecting invalid hostnames.
- Added tests to ensure proper handling of boot time timestamps and SNI validation.

feat(handshake): improve user secret decoding and ALPN enforcement

- Refactored user secret decoding to provide better error handling and logging for invalid secrets.
- Added tests for concurrent identical handshakes to ensure replay protection works as expected.
- Implemented ALPN enforcement in handshake processing, rejecting unsupported protocols and allowing valid ones.

fix(masking): implement timeout handling for masking operations

- Added timeout handling for writing proxy headers and consuming client data in masking.
- Adjusted timeout durations for testing to ensure faster feedback during unit tests.
- Introduced tests to verify behavior when masking is disabled and when proxy header writes exceed the timeout.

test(masking): add tests for slowloris connections and proxy header timeouts

- Created tests to validate that slowloris connections are closed by consume timeout when masking is disabled.
- Added a test for proxy header write timeout to ensure it returns false when the write operation does not complete.
2026-03-16 21:37:59 +04:00
David Osipov 5a16e68487
Enhance TLS record handling and security tests
- Enforce TLS record length constraints in client handling to comply with RFC 8446, rejecting records outside the range of 512 to 16,384 bytes.
- Update security tests to validate behavior for oversized and undersized TLS records, ensuring they are correctly masked or rejected.
- Introduce new tests to verify the handling of TLS records in both generic and client handler pipelines.
- Refactor handshake logic to enforce mode restrictions based on transport type, preventing misuse of secure tags.
- Add tests for nonce generation and encryption consistency, ensuring correct behavior for different configurations.
- Improve masking tests to ensure proper logging and detection of client types, including SSH and unknown probes.
2026-03-16 20:43:49 +04:00
David Osipov 6ffbc51fb0
security: harden handshake/masking flows and add adversarial regressions
- forward valid-TLS/invalid-MTProto clients to mask backend in both client paths\n- harden TLS validation against timing and clock edge cases\n- move replay tracking behind successful authentication to avoid cache pollution\n- tighten secret decoding and key-material handling paths\n- add dedicated security test modules for tls/client/handshake/masking\n- include production-path regression for ClientHandler fallback behavior
2026-03-16 20:04:41 +04:00