pathbuster 0.5.6

A path-normalization pentesting tool.
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
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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
use std::collections::HashSet;

use distance::sift3;

#[derive(Clone, Copy, Debug)]
pub struct ResponseChangeThreshold {
    pub start: f32,
    pub end: f32,
}

pub const DEFAULT_SIFT3_THRESHOLD: ResponseChangeThreshold = ResponseChangeThreshold {
    start: 0.0,
    end: 1000.0,
};

pub fn parse_sift3_threshold_range(value: &str) -> Result<ResponseChangeThreshold, String> {
    let trimmed = value.trim();
    let parts: Vec<&str> = trimmed.split('-').collect();
    if parts.len() != 2 {
        return Err("expected format MIN-MAX".to_string());
    }
    let start: f32 = parts[0]
        .trim()
        .parse()
        .map_err(|_| "invalid MIN value".to_string())?;
    let end: f32 = parts[1]
        .trim()
        .parse()
        .map_err(|_| "invalid MAX value".to_string())?;
    if start < 0.0 || end < 0.0 {
        return Err("threshold values must be non-negative".to_string());
    }
    if start >= end {
        return Err("MIN must be less than MAX".to_string());
    }
    Ok(ResponseChangeThreshold { start, end })
}

pub fn parse_http_methods_csv(value: &str) -> Result<Vec<reqwest::Method>, String> {
    let raw = value.trim();
    if raw.is_empty() {
        return Err("methods list is empty".to_string());
    }

    let mut out: Vec<reqwest::Method> = Vec::new();
    let mut seen: HashSet<String> = HashSet::new();
    for part in raw.split(',') {
        let item = part.trim();
        if item.is_empty() {
            continue;
        }
        let canonical = item.to_ascii_uppercase();
        let method = reqwest::Method::from_bytes(canonical.as_bytes())
            .map_err(|_| format!("invalid method '{item}'"))?;
        if seen.insert(method.as_str().to_string()) {
            out.push(method);
        }
    }

    if out.is_empty() {
        return Err("methods list is empty".to_string());
    }
    Ok(out)
}

pub fn parse_extensions_csv(value: &str) -> Result<Vec<String>, String> {
    let raw = value.trim();
    if raw.is_empty() {
        return Err("extensions list is empty".to_string());
    }
    let mut out: Vec<String> = Vec::new();
    let mut seen: HashSet<String> = HashSet::new();
    for part in raw.split(',') {
        let item = part.trim();
        if item.is_empty() {
            continue;
        }
        let cleaned = item.trim_start_matches('.');
        if cleaned.is_empty() {
            continue;
        }
        let key = cleaned.to_ascii_lowercase();
        if seen.insert(key) {
            out.push(cleaned.to_string());
        }
    }
    if out.is_empty() {
        return Err("extensions list is empty".to_string());
    }
    Ok(out)
}

pub fn get_response_change(a: &str, b: &str, threshold: ResponseChangeThreshold) -> (bool, f32) {
    let s = sift3(a, b);
    if s > threshold.start && s < threshold.end {
        (true, s)
    } else {
        (false, 0.0)
    }
}

pub fn sift3_distance(a: &str, b: &str) -> f32 {
    sift3(a, b)
}

pub fn sift3_distance_in_range(
    a: &str,
    b: &str,
    threshold: ResponseChangeThreshold,
) -> (bool, f32) {
    let d = sift3_distance(a, b);
    if d >= threshold.start && d <= threshold.end {
        (true, d)
    } else {
        (false, d)
    }
}

pub fn parse_u16_set_csv(value: &str) -> Result<HashSet<u16>, String> {
    let raw = value.trim();
    if raw.is_empty() {
        return Err("list is empty".to_string());
    }
    let mut out = HashSet::new();
    for part in raw.split(',') {
        let item = part.trim();
        if item.is_empty() {
            continue;
        }
        let code: u16 = item
            .parse()
            .map_err(|_| format!("invalid status code '{item}'"))?;
        out.insert(code);
    }
    if out.is_empty() {
        return Err("list is empty".to_string());
    }
    Ok(out)
}

pub fn apply_wordlist_extensions(
    words: Vec<String>,
    extensions: &[String],
    dirsearch_compat: bool,
) -> Vec<String> {
    if extensions.is_empty() {
        return words;
    }
    let mut out: Vec<String> = Vec::new();
    if dirsearch_compat {
        for word in words {
            let trimmed = word.trim();
            if trimmed.is_empty() {
                continue;
            }
            if trimmed.contains("%EXT%") {
                for ext in extensions {
                    out.push(trimmed.replace("%EXT%", ext));
                }
            } else {
                out.push(trimmed.to_string());
            }
        }
    } else {
        for word in words {
            let trimmed = word.trim();
            if trimmed.is_empty() {
                continue;
            }
            out.push(trimmed.to_string());
            if trimmed.contains("%EXT%") {
                continue;
            }
            if trimmed.ends_with('/') {
                continue;
            }
            for ext in extensions {
                if ext.is_empty() {
                    continue;
                }
                out.push(format!("{trimmed}.{ext}"));
            }
        }
    }
    out
}

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

    #[test]
    fn parse_u16_set_csv_parses_and_dedupes() {
        let set = parse_u16_set_csv("200, 404,200").unwrap();
        assert!(set.contains(&200));
        assert!(set.contains(&404));
        assert_eq!(set.len(), 2);
    }

    #[test]
    fn parse_extensions_csv_strips_dots_and_dedupes() {
        let out = parse_extensions_csv("php,.asp,PHP").unwrap();
        assert_eq!(out, vec!["php".to_string(), "asp".to_string()]);
    }

    #[test]
    fn apply_wordlist_extensions_appends_when_not_dirsearch() {
        let out = apply_wordlist_extensions(
            vec!["admin".to_string(), "api/".to_string()],
            &vec!["php".to_string(), "asp".to_string()],
            false,
        );
        assert_eq!(
            out,
            vec![
                "admin".to_string(),
                "admin.php".to_string(),
                "admin.asp".to_string(),
                "api/".to_string(),
            ]
        );
    }

    #[test]
    fn apply_wordlist_extensions_replaces_ext_placeholder_in_dirsearch_mode() {
        let out = apply_wordlist_extensions(
            vec!["index.%EXT%".to_string(), "admin".to_string()],
            &vec!["php".to_string(), "asp".to_string()],
            true,
        );
        assert_eq!(
            out,
            vec![
                "index.php".to_string(),
                "index.asp".to_string(),
                "admin".to_string(),
            ]
        );
    }

    #[test]
    fn sift3_distance_in_range_is_inclusive() {
        let threshold = ResponseChangeThreshold {
            start: 0.0,
            end: 0.0,
        };
        let (ok, d) = sift3_distance_in_range("1234", "1234", threshold);
        assert!(ok);
        assert_eq!(d, 0.0);
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WordCase {
    Lower,
    Upper,
    Title,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SmartJoinCase {
    Preserve,
    Lower,
    Upper,
    Title,
    Camel,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SmartJoinSpec {
    pub case: SmartJoinCase,
    pub separator: String,
}

#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct WordlistManipulation {
    pub sort: bool,
    pub unique: bool,
    pub reverse: bool,
    pub case: Option<WordCase>,
    pub prefix: Option<String>,
    pub suffix: Option<String>,
    pub replace: Vec<(String, String)>,
    pub smart: bool,
    pub smart_join: Option<SmartJoinSpec>,
}

pub fn parse_wordlist_manipulation_list(value: &str) -> Result<WordlistManipulation, String> {
    let mut cfg = WordlistManipulation::default();
    let raw = value.trim();
    if raw.is_empty() {
        return Ok(cfg);
    }

    for part in raw.split(',') {
        let item = part.trim();
        if item.is_empty() {
            continue;
        }

        let (key, val) = if let Some((k, v)) = item.split_once('=') {
            (k.trim().to_ascii_lowercase(), Some(v.trim()))
        } else {
            (item.to_ascii_lowercase(), None)
        };

        match key.as_str() {
            "sort" => cfg.sort = true,
            "unique" | "uniq" => cfg.unique = true,
            "reverse" | "rev" => cfg.reverse = true,
            "lower" => {
                if matches!(cfg.case, Some(WordCase::Upper | WordCase::Title)) {
                    return Err("cannot combine lower with upper/title".to_string());
                }
                cfg.case = Some(WordCase::Lower);
            }
            "upper" => {
                if matches!(cfg.case, Some(WordCase::Lower | WordCase::Title)) {
                    return Err("cannot combine upper with lower/title".to_string());
                }
                cfg.case = Some(WordCase::Upper);
            }
            "title" => {
                if matches!(cfg.case, Some(WordCase::Lower | WordCase::Upper)) {
                    return Err("cannot combine title with lower/upper".to_string());
                }
                cfg.case = Some(WordCase::Title);
            }
            "prefix" => {
                let v = val.ok_or_else(|| "prefix requires prefix=<STR>".to_string())?;
                cfg.prefix = Some(v.to_string());
            }
            "suffix" => {
                let v = val.ok_or_else(|| "suffix requires suffix=<STR>".to_string())?;
                cfg.suffix = Some(v.to_string());
            }
            "replace" => {
                let v = val.ok_or_else(|| "replace requires replace=<FROM:TO>".to_string())?;
                let (from, to) = parse_replace_spec(v)?;
                cfg.replace.push((from, to));
            }
            "smart" => cfg.smart = true,
            "smartjoin" | "smart-join" => {
                let v = val.ok_or_else(|| "smartjoin requires smartjoin=<CASE:SEP>".to_string())?;
                cfg.smart_join = Some(parse_smart_join_spec(v)?);
            }
            other => return Err(format!("unknown manipulation '{other}'")),
        }
    }

    Ok(cfg)
}

pub fn parse_smart_join_spec(value: &str) -> Result<SmartJoinSpec, String> {
    let (case_raw, sep_raw) = value
        .split_once(':')
        .ok_or_else(|| "expected CASE:SEP".to_string())?;
    let sep = sep_raw.to_string();
    if sep.is_empty() {
        return Err("separator cannot be empty".to_string());
    }
    let case = match case_raw.trim().to_ascii_lowercase().as_str() {
        "" => SmartJoinCase::Preserve,
        "c" => SmartJoinCase::Camel,
        "l" => SmartJoinCase::Lower,
        "u" => SmartJoinCase::Upper,
        "t" => SmartJoinCase::Title,
        other => return Err(format!("invalid CASE '{other}', expected c,l,u,t or empty")),
    };
    Ok(SmartJoinSpec {
        case,
        separator: sep,
    })
}

pub fn parse_replace_spec(value: &str) -> Result<(String, String), String> {
    let (from_raw, to_raw) = value
        .split_once(':')
        .ok_or_else(|| "expected FROM:TO".to_string())?;
    let from = from_raw.to_string();
    if from.is_empty() {
        return Err("FROM cannot be empty".to_string());
    }
    Ok((from, to_raw.to_string()))
}

pub fn apply_wordlist_manipulations(
    mut words: Vec<String>,
    cfg: &WordlistManipulation,
) -> Vec<String> {
    for w in words.iter_mut() {
        *w = w.trim().to_string();
    }
    words.retain(|w| !w.is_empty());

    if cfg.smart {
        let mut out: Vec<String> = Vec::new();
        for w in words.iter() {
            out.extend(smart_break(w));
        }
        words = out;
    }

    if let Some(spec) = cfg.smart_join.as_ref() {
        let mut out: Vec<String> = Vec::with_capacity(words.len());
        for w in words.iter() {
            if let Some(v) = smart_join(w, spec) {
                if !v.is_empty() {
                    out.push(v);
                }
            }
        }
        words = out;
    }

    if !cfg.replace.is_empty() {
        for w in words.iter_mut() {
            for (from, to) in cfg.replace.iter() {
                if from.is_empty() {
                    continue;
                }
                *w = w.replace(from, to);
            }
        }
    }

    if let Some(prefix) = cfg.prefix.as_deref() {
        if !prefix.is_empty() {
            for w in words.iter_mut() {
                let mut s = String::with_capacity(prefix.len() + w.len());
                s.push_str(prefix);
                s.push_str(w);
                *w = s;
            }
        }
    }

    if let Some(suffix) = cfg.suffix.as_deref() {
        if !suffix.is_empty() {
            for w in words.iter_mut() {
                let mut s = String::with_capacity(suffix.len() + w.len());
                s.push_str(w);
                s.push_str(suffix);
                *w = s;
            }
        }
    }

    if let Some(case) = cfg.case {
        match case {
            WordCase::Lower => {
                for w in words.iter_mut() {
                    w.make_ascii_lowercase();
                }
            }
            WordCase::Upper => {
                for w in words.iter_mut() {
                    w.make_ascii_uppercase();
                }
            }
            WordCase::Title => {
                for w in words.iter_mut() {
                    *w = title_ascii(w);
                }
            }
        }
    }

    if cfg.reverse {
        for w in words.iter_mut() {
            *w = w.chars().rev().collect::<String>();
        }
    }

    for w in words.iter_mut() {
        *w = w.trim().to_string();
    }
    words.retain(|w| !w.is_empty());

    if cfg.sort {
        words.sort();
        if cfg.unique {
            words.dedup();
        }
        return words;
    }

    if cfg.unique {
        let mut seen: HashSet<String> = HashSet::new();
        words.retain(|w| seen.insert(w.clone()));
    }

    words
}

pub fn smart_break(input: &str) -> Vec<String> {
    let chars: Vec<char> = input.chars().collect();
    let mut out: Vec<String> = Vec::new();
    let mut buf = String::new();

    let flush = |buf: &mut String, out: &mut Vec<String>| {
        if !buf.is_empty() {
            out.push(std::mem::take(buf));
        }
    };

    for i in 0..chars.len() {
        let ch = chars[i];
        if is_smart_separator(ch) {
            flush(&mut buf, &mut out);
            continue;
        }
        if !buf.is_empty() {
            let prev = buf.chars().last().unwrap_or(ch);
            let next = chars.get(i + 1).copied();
            if is_boundary(prev, ch, next) {
                flush(&mut buf, &mut out);
            }
        }
        buf.push(ch);
    }
    flush(&mut buf, &mut out);

    out.into_iter()
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .collect()
}

fn is_smart_separator(ch: char) -> bool {
    ch.is_whitespace() || ch == '_' || ch == '-' || ch == '.'
}

fn is_boundary(prev: char, curr: char, next: Option<char>) -> bool {
    if prev.is_ascii_lowercase() && curr.is_ascii_uppercase() {
        return true;
    }
    if prev.is_ascii_uppercase() && curr.is_ascii_uppercase() {
        if let Some(next) = next {
            if next.is_ascii_lowercase() {
                return true;
            }
        }
    }
    if prev.is_ascii_alphabetic() && curr.is_ascii_digit() {
        return true;
    }
    if prev.is_ascii_digit() && curr.is_ascii_alphabetic() {
        return true;
    }
    false
}

fn smart_join(input: &str, spec: &SmartJoinSpec) -> Option<String> {
    let tokens = smart_break(input);
    if tokens.is_empty() {
        return None;
    }
    let mut out_tokens: Vec<String> = Vec::with_capacity(tokens.len());
    for (idx, t) in tokens.iter().enumerate() {
        let mapped = match spec.case {
            SmartJoinCase::Preserve => t.clone(),
            SmartJoinCase::Lower => t.to_ascii_lowercase(),
            SmartJoinCase::Upper => t.to_ascii_uppercase(),
            SmartJoinCase::Title => title_ascii(t),
            SmartJoinCase::Camel => {
                if idx == 0 {
                    t.to_ascii_lowercase()
                } else {
                    title_ascii(t)
                }
            }
        };
        if !mapped.is_empty() {
            out_tokens.push(mapped);
        }
    }
    Some(out_tokens.join(&spec.separator))
}

fn title_ascii(input: &str) -> String {
    let mut chars = input.chars();
    let Some(first) = chars.next() else {
        return String::new();
    };
    let mut out = String::with_capacity(input.len());
    out.push(first.to_ascii_uppercase());
    for ch in chars {
        out.push(ch.to_ascii_lowercase());
    }
    out
}