stochastic-routing-extended 1.0.2

SRX (Stochastic Routing eXtended) — a next-generation VPN protocol with stochastic routing, DPI evasion, post-quantum cryptography, and multi-transport channel splitting
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
//! Decoy protocol endpoints: external-facing APIs that look like normal services.
//!
//! A [`DecoyEndpoint`] answers HTTP probes with plausible responses so that DPI
//! / active probing sees a legitimate-looking REST, health-check, or metrics
//! service rather than a VPN tunnel.
//!
//! Hidden control data can be embedded in request/response bodies using
//! [`DecoyEndpoint::inject_payload`] / [`DecoyEndpoint::extract_payload`].

use std::collections::HashMap;
use std::time::{SystemTime, UNIX_EPOCH};

// ── Decoy profiles ──────────────────────────────────────────────────────────

/// Pre-defined response profiles that mimic common services.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DecoyProfile {
    /// REST API — `{"status":"ok","version":"...","timestamp":...}`
    RestApi,
    /// Health-check — `{"healthy":true,"uptime_s":...}`
    HealthCheck,
    /// Prometheus-style metrics — plain-text gauge/counter lines.
    Metrics,
}

// ── DecoyEndpoint ───────────────────────────────────────────────────────────

/// A decoy endpoint that appears as a normal HTTP service.
///
/// Each endpoint has a path, an allowed HTTP method, a [`DecoyProfile`] that
/// determines the shape of the response, and optional extra headers.
pub struct DecoyEndpoint {
    /// The external path (e.g., "/api/v1/telemetry").
    pub path: String,
    /// HTTP method to respond to.
    pub method: String,
    /// Response profile.
    pub profile: DecoyProfile,
    /// Additional HTTP response headers.
    pub extra_headers: HashMap<String, String>,
}

impl DecoyEndpoint {
    /// Create a new decoy endpoint with a given profile.
    pub fn new(path: impl Into<String>, method: impl Into<String>, profile: DecoyProfile) -> Self {
        Self {
            path: path.into(),
            method: method.into(),
            profile,
            extra_headers: HashMap::new(),
        }
    }

    /// Convenience: REST API decoy on `GET /api/v1/status`.
    pub fn rest_api() -> Self {
        Self::new("/api/v1/status", "GET", DecoyProfile::RestApi)
    }

    /// Convenience: health-check decoy on `GET /healthz`.
    pub fn health_check() -> Self {
        Self::new("/healthz", "GET", DecoyProfile::HealthCheck)
    }

    /// Convenience: metrics decoy on `GET /metrics`.
    pub fn metrics() -> Self {
        Self::new("/metrics", "GET", DecoyProfile::Metrics)
    }

    /// Add an extra response header.
    pub fn with_header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.extra_headers.insert(key.into(), value.into());
        self
    }

    // ── Request matching ────────────────────────────────────────────────

    /// Returns `true` when the incoming request matches this endpoint.
    pub fn matches(&self, method: &str, path: &str) -> bool {
        self.method.eq_ignore_ascii_case(method) && self.path == path
    }

    // ── Response generation ─────────────────────────────────────────────

    /// Generate a plausible HTTP response body for external probes.
    pub fn decoy_response(&self) -> Vec<u8> {
        let ts = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();

        match self.profile {
            DecoyProfile::RestApi => format!(
                r#"{{"status":"ok","version":"2.4.1","timestamp":{ts},"request_id":"{rid}"}}"#,
                rid = pseudo_request_id(ts),
            )
            .into_bytes(),

            DecoyProfile::HealthCheck => format!(
                r#"{{"healthy":true,"uptime_s":{uptime},"checks":{{"db":"pass","cache":"pass"}}}}"#,
                uptime = ts % 864_000, // wrap at ~10 days for realism
            )
            .into_bytes(),

            DecoyProfile::Metrics => format!(
                "# HELP http_requests_total Total HTTP requests.\n\
                 # TYPE http_requests_total counter\n\
                 http_requests_total{{method=\"GET\"}} {get}\n\
                 http_requests_total{{method=\"POST\"}} {post}\n\
                 # HELP process_uptime_seconds Process uptime.\n\
                 # TYPE process_uptime_seconds gauge\n\
                 process_uptime_seconds {uptime}\n",
                get = ts % 100_000,
                post = (ts / 3) % 50_000,
                uptime = ts % 864_000,
            )
            .into_bytes(),
        }
    }

    /// Content-Type matching the profile.
    pub fn content_type(&self) -> &'static str {
        match self.profile {
            DecoyProfile::RestApi | DecoyProfile::HealthCheck => "application/json",
            DecoyProfile::Metrics => "text/plain; version=0.0.4; charset=utf-8",
        }
    }

    /// Build a full HTTP/1.1 response (status line + headers + body).
    pub fn http_response(&self) -> Vec<u8> {
        let body = self.decoy_response();
        let mut resp = format!(
            "HTTP/1.1 200 OK\r\n\
             Content-Type: {ct}\r\n\
             Content-Length: {len}\r\n\
             Server: nginx/1.25.4\r\n\
             Connection: keep-alive\r\n",
            ct = self.content_type(),
            len = body.len(),
        );
        for (k, v) in &self.extra_headers {
            resp.push_str(k);
            resp.push_str(": ");
            resp.push_str(v);
            resp.push_str("\r\n");
        }
        resp.push_str("\r\n");
        let mut bytes = resp.into_bytes();
        bytes.extend_from_slice(&body);
        bytes
    }

    // ── Hidden payload embedding ────────────────────────────────────────

    /// Embed a hidden payload inside a decoy response body.
    ///
    /// The payload is base64-encoded and appended as a JSON field
    /// (`"trace_id":"<base64>"`) for JSON profiles, or as a comment line
    /// (`# trace <base64>`) for Metrics.
    pub fn inject_payload(&self, hidden: &[u8]) -> Vec<u8> {
        use base64::Engine;
        let b64 = base64::engine::general_purpose::STANDARD.encode(hidden);
        let ts = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();

        match self.profile {
            DecoyProfile::RestApi => format!(
                r#"{{"status":"ok","version":"2.4.1","timestamp":{ts},"request_id":"{rid}","trace_id":"{b64}"}}"#,
                rid = pseudo_request_id(ts),
            )
            .into_bytes(),

            DecoyProfile::HealthCheck => format!(
                r#"{{"healthy":true,"uptime_s":{uptime},"checks":{{"db":"pass","cache":"pass"}},"trace_id":"{b64}"}}"#,
                uptime = ts % 864_000,
            )
            .into_bytes(),

            DecoyProfile::Metrics => format!(
                "# HELP http_requests_total Total HTTP requests.\n\
                 # TYPE http_requests_total counter\n\
                 http_requests_total{{method=\"GET\"}} {get}\n\
                 # trace {b64}\n\
                 process_uptime_seconds {uptime}\n",
                get = ts % 100_000,
                uptime = ts % 864_000,
            )
            .into_bytes(),
        }
    }

    /// Extract a hidden payload from a decoy response body.
    ///
    /// Returns `None` if no embedded payload is found.
    pub fn extract_payload(body: &[u8]) -> Option<Vec<u8>> {
        use base64::Engine;
        let text = std::str::from_utf8(body).ok()?;

        // JSON profile: look for "trace_id":"<base64>"
        if let Some(start) = text.find("\"trace_id\":\"") {
            let val_start = start + "\"trace_id\":\"".len();
            let val_end = text[val_start..].find('"')? + val_start;
            let b64 = &text[val_start..val_end];
            return base64::engine::general_purpose::STANDARD.decode(b64).ok();
        }

        // Metrics profile: look for "# trace <base64>"
        for line in text.lines() {
            if let Some(rest) = line.strip_prefix("# trace ") {
                return base64::engine::general_purpose::STANDARD
                    .decode(rest.trim())
                    .ok();
            }
        }

        None
    }
}

// ── DecoyRouter ─────────────────────────────────────────────────────────────

/// A simple router that dispatches incoming requests to registered decoys.
pub struct DecoyRouter {
    endpoints: Vec<DecoyEndpoint>,
}

impl DecoyRouter {
    pub fn new() -> Self {
        Self {
            endpoints: Vec::new(),
        }
    }

    /// Register a decoy endpoint.
    pub fn add(&mut self, endpoint: DecoyEndpoint) {
        self.endpoints.push(endpoint);
    }

    /// Find the first matching endpoint for the given method + path.
    pub fn match_request(&self, method: &str, path: &str) -> Option<&DecoyEndpoint> {
        self.endpoints.iter().find(|e| e.matches(method, path))
    }

    /// Generate a full HTTP response for a request, or a 404 if unmatched.
    pub fn handle(&self, method: &str, path: &str) -> Vec<u8> {
        match self.match_request(method, path) {
            Some(ep) => ep.http_response(),
            None => {
                let body = b"{\"error\":\"not found\"}";
                format!(
                    "HTTP/1.1 404 Not Found\r\n\
                     Content-Type: application/json\r\n\
                     Content-Length: {}\r\n\
                     Server: nginx/1.25.4\r\n\
                     Connection: keep-alive\r\n\
                     \r\n",
                    body.len(),
                )
                .into_bytes()
                .into_iter()
                .chain(body.iter().copied())
                .collect()
            }
        }
    }

    /// Number of registered endpoints.
    pub fn len(&self) -> usize {
        self.endpoints.len()
    }

    /// Whether the router has no endpoints.
    pub fn is_empty(&self) -> bool {
        self.endpoints.is_empty()
    }
}

impl Default for DecoyRouter {
    fn default() -> Self {
        Self::new()
    }
}

// ── Helpers ─────────────────────────────────────────────────────────────────

/// Deterministic but plausible-looking hex "request ID" derived from timestamp.
fn pseudo_request_id(ts: u64) -> String {
    let h = ts.wrapping_mul(0x517cc1b727220a95);
    format!("{h:016x}")
}

// ── Tests ───────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn rest_api_response_is_valid_json() {
        let ep = DecoyEndpoint::rest_api();
        let body = ep.decoy_response();
        let text = std::str::from_utf8(&body).unwrap();
        assert!(text.contains("\"status\":\"ok\""));
        assert!(text.contains("\"version\""));
        assert!(text.contains("\"timestamp\""));
        assert!(text.contains("\"request_id\""));
    }

    #[test]
    fn health_check_response_is_valid_json() {
        let ep = DecoyEndpoint::health_check();
        let body = ep.decoy_response();
        let text = std::str::from_utf8(&body).unwrap();
        assert!(text.contains("\"healthy\":true"));
        assert!(text.contains("\"uptime_s\""));
    }

    #[test]
    fn metrics_response_has_prometheus_format() {
        let ep = DecoyEndpoint::metrics();
        let body = ep.decoy_response();
        let text = std::str::from_utf8(&body).unwrap();
        assert!(text.contains("# HELP"));
        assert!(text.contains("# TYPE"));
        assert!(text.contains("http_requests_total"));
        assert!(text.contains("process_uptime_seconds"));
    }

    #[test]
    fn matches_method_case_insensitive() {
        let ep = DecoyEndpoint::rest_api();
        assert!(ep.matches("GET", "/api/v1/status"));
        assert!(ep.matches("get", "/api/v1/status"));
        assert!(!ep.matches("POST", "/api/v1/status"));
        assert!(!ep.matches("GET", "/other"));
    }

    #[test]
    fn http_response_has_headers() {
        let ep = DecoyEndpoint::rest_api().with_header("X-Custom", "test");
        let resp = ep.http_response();
        let text = std::str::from_utf8(&resp).unwrap();
        assert!(text.starts_with("HTTP/1.1 200 OK\r\n"));
        assert!(text.contains("Content-Type: application/json"));
        assert!(text.contains("X-Custom: test"));
        assert!(text.contains("\r\n\r\n"));
    }

    #[test]
    fn content_type_matches_profile() {
        assert_eq!(DecoyEndpoint::rest_api().content_type(), "application/json");
        assert_eq!(
            DecoyEndpoint::health_check().content_type(),
            "application/json"
        );
        assert!(
            DecoyEndpoint::metrics()
                .content_type()
                .starts_with("text/plain")
        );
    }

    #[test]
    fn inject_extract_roundtrip_json() {
        let ep = DecoyEndpoint::rest_api();
        let hidden = b"secret-signal-data";
        let body = ep.inject_payload(hidden);
        let recovered = DecoyEndpoint::extract_payload(&body).unwrap();
        assert_eq!(recovered, hidden);
    }

    #[test]
    fn inject_extract_roundtrip_health() {
        let ep = DecoyEndpoint::health_check();
        let hidden = b"\x00\x01\x02binary";
        let body = ep.inject_payload(hidden);
        let recovered = DecoyEndpoint::extract_payload(&body).unwrap();
        assert_eq!(recovered, hidden);
    }

    #[test]
    fn inject_extract_roundtrip_metrics() {
        let ep = DecoyEndpoint::metrics();
        let hidden = b"metrics-hidden";
        let body = ep.inject_payload(hidden);
        let recovered = DecoyEndpoint::extract_payload(&body).unwrap();
        assert_eq!(recovered, hidden);
    }

    #[test]
    fn extract_returns_none_for_plain_response() {
        let ep = DecoyEndpoint::rest_api();
        let body = ep.decoy_response();
        assert!(DecoyEndpoint::extract_payload(&body).is_none());
    }

    #[test]
    fn router_matches_and_returns_404() {
        let mut router = DecoyRouter::new();
        router.add(DecoyEndpoint::rest_api());
        router.add(DecoyEndpoint::health_check());

        assert!(router.match_request("GET", "/api/v1/status").is_some());
        assert!(router.match_request("GET", "/healthz").is_some());
        assert!(router.match_request("GET", "/unknown").is_none());

        let resp = router.handle("GET", "/unknown");
        let text = std::str::from_utf8(&resp).unwrap();
        assert!(text.starts_with("HTTP/1.1 404"));
    }

    #[test]
    fn router_len_and_is_empty() {
        let mut router = DecoyRouter::new();
        assert!(router.is_empty());
        assert_eq!(router.len(), 0);
        router.add(DecoyEndpoint::metrics());
        assert!(!router.is_empty());
        assert_eq!(router.len(), 1);
    }
}