onionRush 1.0.0

Parallel multi-circuit downloader and uploader over Tor.
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
use crate::args::UploadArgs;
use crate::proxy;
use anyhow::{anyhow, Result};
use bytes::Bytes;
use rand::seq::SliceRandom;
use rand::Rng;
use reqwest::multipart::{Form, Part};
use reqwest::Client;
use std::fs::File;
use std::io::Read;
use std::path::Path;
use std::sync::Arc;
use std::time::Duration;
use tokio::time::sleep;
use tracing::{debug, error, info, warn};

pub struct UploadChunk {
    pub index: usize,
    pub data: Bytes,
    pub offset: u64,
    pub size: usize,
}

#[derive(Debug, Clone, Copy)]
enum Schedule {
    Random { mean: f64, jitter: f64 },
    Fixed(u64),
    Immediate,
}

enum FormField {
    File(String, Part),
    Text(String, String),
}

pub async fn upload_file(args: &UploadArgs) -> Result<()> {
    if !args.skip_isolation_check {
        verify_socks_isolation(&args.socks).await?;
    }

    let mut file_path_str = args.file.clone();
    if args.strip_metadata {
        file_path_str = strip_file_metadata(&args.file).await?;
    } else {
        warn_metadata_leak(&args.file);
    }

    let file_path = Path::new(&file_path_str);
    if !file_path.exists() {
        return Err(anyhow!("File not found: {}", file_path_str));
    }

    let file_size = file_path.metadata()?.len();
    info!("[+] Uploading: {} ({:.2} MB)", file_path_str, file_size as f64 / 1024.0 / 1024.0);
    info!("[*] Base chunk size: {} bytes (jittered +/-20%)", args.chunk_size);
    info!("[*] Streams: {}", args.streams);

    let chunks = split_file_into_chunks(file_path, args.chunk_size)?;
    info!("[*] Split into {} chunks", chunks.len());

    let headers = parse_headers(&args.headers);
    let cookies = parse_cookies(&args.cookies);
    let schedule = parse_interval(&args.interval)?;
    info!("[*] Upload schedule: {:?}", schedule);

    upload_chunks_parallel(args, chunks, headers, cookies, schedule).await?;

    if args.strip_metadata && file_path_str != args.file {
        let _ = std::fs::remove_file(&file_path_str);
    }

    info!("[+] Upload completed successfully!");
    Ok(())
}

fn warn_metadata_leak(file_path: &str) {
    if let Some(ext) = Path::new(file_path).extension().and_then(|s| s.to_str()) {
        let dangerous = ["jpg", "jpeg", "png", "pdf", "docx", "xlsx", "pptx", "zip"];
        if dangerous.contains(&ext.to_lowercase().as_str()) {
            warn!("[!] WARNING: Uploading .{} without --strip-metadata may leak EXIF/document properties.", ext);
        }
    }
}

async fn strip_file_metadata(file_path: &str) -> Result<String> {
    info!("[*] Stripping metadata from file: {}", file_path);
    let path = Path::new(file_path);
    let ext = path.extension().and_then(|s| s.to_str()).unwrap_or("tmp");
    let random_id = proxy::random_identity();
    let cleaned_path = format!("{}_cleaned.{}", random_id, ext);

    std::fs::copy(file_path, &cleaned_path)?;

    let status = tokio::process::Command::new("mat2")
        .arg(&cleaned_path)
        .status()
        .await;

    match status {
        Ok(s) if s.success() => {
            let mat2_out = format!("{}.cleaned", cleaned_path);
            if Path::new(&mat2_out).exists() {
                let _ = std::fs::remove_file(&cleaned_path);
                info!("[+] Metadata successfully stripped using mat2.");
                return Ok(mat2_out);
            }
        }
        _ => {
            warn!("[!] mat2 failed or is not installed. Aborting due to --strip-metadata constraint.");
            let _ = std::fs::remove_file(&cleaned_path);
            return Err(anyhow!("Failed to strip metadata. Ensure mat2 is installed on your path."));
        }
    }

    Ok(cleaned_path)
}

async fn verify_socks_isolation(socks_addr: &str) -> Result<()> {
    info!("[*] Performing Tor SOCKS isolation validation check...");
    let id_a = proxy::random_identity();
    let id_b = proxy::random_identity();

    let client_a = proxy::build_client(socks_addr, &id_a, Duration::from_secs(20), false)?;
    let client_b = proxy::build_client(socks_addr, &id_b, Duration::from_secs(20), false)?;

    let fetch_ip = |client: Client| async move {
        client.get("https://api.ipify.org")
            .send()
            .await?
            .text()
            .await
    };

    let (ip_a, ip_b) = tokio::join!(
        fetch_ip(client_a),
        fetch_ip(client_b)
    );

    match (ip_a, ip_b) {
        (Ok(a), Ok(b)) => {
            let a = a.trim();
            let b = b.trim();
            if a == b {
                warn!("[!] WARNING: Tor circuit isolation check failed. Both SOCKS credentials resolved to IP: {}", a);
                warn!("[!] Ensure that 'IsolateSOCKSAuth' is configured inside your torrc.");
            } else {
                info!("[+] Tor circuit isolation check passed: SOCKS identities mapped to different exit IPs.");
            }
        }
        _ => {
            warn!("[!] SOCKS isolation self-test could not complete (destination server offline or unreachable). Proceeding...");
        }
    }
    Ok(())
}

fn split_file_into_chunks(path: &Path, base_chunk_size: u64) -> Result<Vec<UploadChunk>> {
    let mut file = File::open(path)?;
    let mut chunks = Vec::new();
    let mut offset = 0u64;
    let mut index = 0;
    let mut rng = rand::thread_rng();

    loop {
        let jitter_factor: f64 = rng.gen_range(0.8..1.2);
        let target_size = ((base_chunk_size as f64) * jitter_factor).round() as usize;
        let mut buffer = vec![0u8; target_size.max(1)];

        let bytes_read = file.read(&mut buffer)?;
        if bytes_read == 0 {
            break;
        }

        let data = Bytes::from(buffer[..bytes_read].to_vec());
        chunks.push(UploadChunk {
            index,
            data,
            offset,
            size: bytes_read,
        });
        offset += bytes_read as u64;
        index += 1;
    }

    Ok(chunks)
}

fn parse_headers(headers: &Option<Vec<String>>) -> Vec<(String, String)> {
    let mut parsed = Vec::new();
    if let Some(headers) = headers {
        for header in headers {
            if let Some((key, value)) = header.split_once(": ") {
                parsed.push((key.to_string(), value.to_string()));
            }
        }
    }
    parsed
}

fn parse_cookies(cookies: &Option<Vec<String>>) -> Vec<String> {
    cookies.clone().unwrap_or_default()
}

fn parse_interval(interval: &Option<String>) -> Result<Schedule> {
    let s = match interval {
        None => return Ok(Schedule::Immediate),
        Some(s) => s,
    };

    if s == "rand" {
        return Ok(Schedule::Random { mean: 15.0, jitter: 10.0 });
    }

    if let Some(params) = s.strip_prefix("rand:") {
        let mut mean = 15.0_f64;
        let mut jitter = 10.0_f64;

        for kv in params.split(',') {
            let kv = kv.trim();
            if kv.is_empty() {
                continue;
            }
            let mut parts = kv.splitn(2, '=');
            let key = parts.next().unwrap_or("").trim();
            let val = parts.next().unwrap_or("").trim();
            match key {
                "mean" => {
                    mean = val
                        .parse::<f64>()
                        .map_err(|_| anyhow!("invalid mean value '{val}' in --interval"))?;
                }
                "jitter" => {
                    jitter = val
                        .parse::<f64>()
                        .map_err(|_| anyhow!("invalid jitter value '{val}' in --interval"))?;
                }
                other => {
                    return Err(anyhow!(
                        "unknown --interval param '{other}', expected 'mean' or 'jitter'"
                    ));
                }
            }
        }

        if mean <= 0.0 {
            return Err(anyhow!("--interval mean must be > 0"));
        }

        return Ok(Schedule::Random { mean, jitter: jitter.max(0.0) });
    }

    s.parse::<u64>().map(Schedule::Fixed).map_err(|_| {
        anyhow!(
            "--interval must be 'rand', 'rand:mean=<secs>,jitter=<secs>', or an integer (seconds); got '{s}'"
        )
    })
}

fn sample_delay_secs(mean: f64, jitter: f64) -> u64 {
    let mut rng = rand::thread_rng();

    let u1: f64 = rng.gen_range(0.0001_f64..1.0);
    let u2: f64 = rng.gen_range(0.0_f64..1.0);
    let z0 = (-2.0 * u1.ln()).sqrt() * (2.0 * std::f64::consts::PI * u2).cos();

    let mean = mean.max(0.5);
    let cv = (jitter / mean).clamp(0.05, 2.0);
    let sigma = (1.0 + cv * cv).ln().sqrt();
    let mu = mean.ln() - 0.5 * sigma * sigma;

    let sample = (mu + sigma * z0).exp();
    sample.clamp(0.5, mean * 6.0).round() as u64
}

async fn upload_chunks_parallel(
    args: &UploadArgs,
    mut chunks: Vec<UploadChunk>,
    headers: Vec<(String, String)>,
    cookies: Vec<String>,
    schedule: Schedule,
) -> Result<()> {
    use tokio::sync::Semaphore;
    use tokio::task::JoinSet;

    let semaphore = Arc::new(Semaphore::new(args.streams));
    let mut set = JoinSet::new();

    {
        let mut rng = rand::thread_rng();
        chunks.shuffle(&mut rng);
    }

    let total_chunks = chunks.len();
    let mut uploaded = 0;

    let mut persistent_clients = Vec::new();
    if args.reuse_connections {
        for _ in 0..args.streams {
            let identity = proxy::random_identity();
            let client = proxy::build_client(&args.socks, &identity, Duration::from_secs(args.timeout), true)?;
            persistent_clients.push(Arc::new(client));
        }
    }

    let start_time = std::time::Instant::now();
    let session_window_secs = args.session_window.map(|w| w * 3600.0);

    for (i, chunk) in chunks.into_iter().enumerate() {
        let permit = semaphore.clone().acquire_owned().await?;
        let args_c = args.clone();
        let headers_c = headers.clone();
        let cookies_c = cookies.clone();

        let client = if args.reuse_connections {
            let client_idx = i % args.streams;
            Some(persistent_clients[client_idx].clone())
        } else {
            None
        };

        if i > 0 {
            if let Some(chance) = args.session_pause_chance {
                let mut rng = rand::thread_rng();
                if rng.gen_bool(chance) {
                    let pause = rng.gen_range(args.session_pause_min..=args.session_pause_max);
                    info!("[*] Injecting session-level off gap: {} seconds", pause);
                    sleep(Duration::from_secs(pause)).await;
                }
            }

            let active_schedule = if let Some(total_secs) = session_window_secs {
                let elapsed = start_time.elapsed().as_secs_f64();
                let remaining_time = (total_secs - elapsed).max(0.0);
                let remaining_chunks = (total_chunks - i) as f64;
                let current_mean = if remaining_chunks > 1.0 {
                    remaining_time / remaining_chunks
                } else {
                    0.0
                };
                Schedule::Random {
                    mean: current_mean,
                    jitter: current_mean * 0.5,
                }
            } else {
                schedule
            };

            match active_schedule {
                Schedule::Random { mean, jitter } => {
                    if mean > 0.0 {
                        let delay = sample_delay_secs(mean, jitter);
                        info!("[*] Paced delay: {}s (mean={:.1}s, jitter={:.1}s)", delay, mean, jitter);
                        sleep(Duration::from_secs(delay)).await;
                    }
                }
                Schedule::Fixed(secs) => {
                    info!("[*] Fixed delay: {} seconds", secs);
                    sleep(Duration::from_secs(secs)).await;
                }
                Schedule::Immediate => {}
            }
        }

        set.spawn(async move {
            let result = upload_single_chunk(&args_c, &chunk, &headers_c, &cookies_c, client).await;
            drop(permit);
            result
        });
    }

    while let Some(res) = set.join_next().await {
        match res {
            Ok(Ok(())) => {
                uploaded += 1;
                let progress = (uploaded as f64 / total_chunks as f64) * 100.0;
                info!("[*] Upload progress: {:.1}% ({}/{})", progress, uploaded, total_chunks);
            }
            Ok(Err(e)) => {
                error!("[-] Chunk upload failed: {}", e);
            }
            Err(e) => {
                error!("[-] Task panicked: {}", e);
            }
        }
    }

    Ok(())
}

async fn upload_single_chunk(
    args: &UploadArgs,
    chunk: &UploadChunk,
    headers: &[(String, String)],
    cookies: &[String],
    client: Option<Arc<Client>>,
) -> Result<()> {
    let mut retries = 0;
    while retries < args.retries {
        let active_client = match &client {
            Some(c) => c.as_ref().clone(),
            None => {
                let identity = proxy::random_identity();
                match proxy::build_client(&args.socks, &identity, Duration::from_secs(args.timeout), false) {
                    Ok(c) => c,
                    Err(e) => {
                        warn!("[!] Failed to build client: {}", e);
                        retries += 1;
                        continue;
                    }
                }
            }
        };

        let data_vec = chunk.data.to_vec();
        let part = Part::bytes(data_vec)
            .file_name(format!("chunk_{}", chunk.index))
            .mime_str("application/octet-stream")?;

        let mut form_fields = vec![
            FormField::File(args.field_file.clone(), part),
            FormField::Text(args.field_index.clone(), chunk.index.to_string()),
            FormField::Text(args.field_offset.clone(), chunk.offset.to_string()),
            FormField::Text(args.field_size.clone(), chunk.size.to_string()),
        ];

        if args.randomize_fields {
            form_fields.shuffle(&mut rand::thread_rng());
        }

        let mut form = Form::new();
        for field in form_fields {
            form = match field {
                FormField::File(name, value) => form.part(name, value),
                FormField::Text(name, value) => form.text(name, value),
            };
        }

        let mut request = active_client.post(&args.url).multipart(form);

        for (key, value) in headers {
            request = request.header(key, value);
        }

        for cookie in cookies {
            request = request.header("Cookie", cookie);
        }

        request = request.header("X-Request-ID", uuid::Uuid::new_v4().to_string());
        request = request.header("X-Timestamp", chrono::Utc::now().to_rfc3339());

        match request.send().await {
            Ok(resp) => {
                if resp.status().is_success() {
                    debug!("[+] Chunk {} uploaded successfully", chunk.index);
                    return Ok(());
                } else {
                    let status = resp.status();
                    let text = resp.text().await.unwrap_or_default();
                    warn!("[!] Upload failed with status {}: {}", status, text);
                    retries += 1;
                }
            }
            Err(e) => {
                warn!("[!] Upload error: {}", e);
                retries += 1;
            }
        }

        let backoff = {
            let mut rng = rand::thread_rng();
            let base = 2.0_f64;
            let max_backoff = 60.0_f64;
            let limit = (base * 2.0_f64.powi(retries as i32)).min(max_backoff);
            rng.gen_range(0.5..limit).round() as u64
        };
        info!("[*] Retry {} in {} seconds", retries, backoff);
        sleep(Duration::from_secs(backoff)).await;
    }

    Err(anyhow!("Failed to upload chunk {} after {} retries", chunk.index, args.retries))
}