feroxfuzz 1.0.0-rc.13

Structure-aware, black box HTTP fuzzing library
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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
//! Use data from an [`Observer`] to make a decision about the supplied data
//!
//! [`Observer`]: crate::observers::Observer
mod length;
mod regex;
mod status_code;
use crate::actions::Action;
use crate::metadata::AsAny;
use crate::observers::Observers;
use crate::requests::Request;
use crate::responses::Response;
use crate::state::SharedState;
use crate::std_ext::tuple::Named;
use crate::DecidersList;

pub use self::length::ContentLengthDecider;
pub use self::regex::RequestRegexDecider;
pub use self::regex::ResponseRegexDecider;
pub use self::status_code::StatusCodeDecider;
// re-export LogicOperation from here, for a more logical location from an external user's perspective
pub use crate::std_ext::ops::LogicOperation;

use dyn_clone::DynClone;

/// A `Decider` pulls information from some [`Observer`] in order to
/// reach a decision about what [`Action`] should be taken
///
/// [`Action`]: crate::actions::Action
/// [`Observer`]: crate::observers::Observer
pub trait Decider<O, R>: DynClone + AsAny + Named
where
    O: Observers<R>,
    R: Response,
{
    /// given the fuzzer's [`SharedState`], and the current mutated [`Request`] to be sent,
    /// make a decision that returns an [`Action`]
    ///
    /// this is typically called via the `pre_send_hook`
    ///
    /// [`SharedState`]: crate::state::SharedState
    /// [`Request`]: crate::requests::Request
    /// [`Action`]: crate::actions::Action
    fn decide_with_request(&mut self, _state: &SharedState, _request: &Request) -> Option<Action> {
        None
    }

    /// given the fuzzer's [`SharedState`], and a collection of [`Observers`], make a decision that
    /// returns an [`Action`]
    ///
    /// this is typically called via the `post_send_hook`
    ///
    /// [`SharedState`]: crate::state::SharedState
    /// [`Observers`]: crate::observers::Observers
    /// [`Action`]: crate::actions::Action
    fn decide_with_observers(&mut self, _state: &SharedState, _observers: &O) -> Option<Action> {
        None
    }
}

impl<O, R> Clone for Box<dyn Decider<O, R>>
where
    O: Observers<R>,
    R: Response,
{
    fn clone(&self) -> Self {
        dyn_clone::clone_box(&**self)
    }
}

impl<O, R> Clone for Box<dyn DeciderHooks<O, R>>
where
    O: Observers<R>,
    R: Response,
{
    fn clone(&self) -> Self {
        dyn_clone::clone_box(&**self)
    }
}

/// defines the hooks that are executed before a request is sent
/// and after a response is received
///
/// expected order of operations:
/// - `pre_send_hook(.., request, ..)`
/// - `let response = client.send(request)`
/// - `post_send_hook(.., response,)`
pub trait DeciderHooks<O, R>: Decider<O, R> + DynClone + AsAny + Sync + Send
where
    O: Observers<R>,
    R: Response,
{
    /// called before an [`HttpClient`] sends a [`Request`]
    ///
    /// [`HttpClient`]: crate::client::HttpClient
    /// [`Request`]: crate::requests::Request
    fn pre_send_hook(
        &mut self,
        state: &SharedState,
        request: &Request,
        action: Option<Action>,
        operation: LogicOperation,
    ) -> Option<Action> {
        // short-circuit logic
        if let Some(ref inner) = action {
            match (inner, operation) {
                // received a Discard with an And, or a Keep with an Or
                // this means we can skip the decide_with_observers call
                // altogether and simply return the current action
                (Action::Discard, LogicOperation::And) => return Some(Action::Discard),
                (Action::Keep, LogicOperation::Or) => return Some(Action::Keep),
                _ => {}
            }
        }

        let new_action = self.decide_with_request(state, request);

        // take the current action that was decided upon via decide_with_request, and the
        // previously decided action (if any) to arrive at what should be returned as the
        // current decided action
        match (action, new_action, operation) {
            (None, None, _) => None,
            (None, Some(new_action), _) => Some(new_action),
            (Some(old_action), None, _) => Some(old_action),
            (Some(old_action), Some(new_action), LogicOperation::And) => {
                Some(old_action & new_action)
            }
            (Some(old_action), Some(new_action), LogicOperation::Or) => {
                Some(old_action | new_action)
            }
        }
    }

    /// called after an [`HttpClient`] receives a [`Response`]
    ///
    /// [`HttpClient`]: crate::client::HttpClient
    /// [`Request`]: crate::requests::Request
    fn post_send_hook(
        &mut self,
        state: &SharedState,
        observers: &O,
        action: Option<Action>,
        operation: LogicOperation,
    ) -> Option<Action> {
        // short-circuit logic
        if let Some(ref inner) = action {
            match (inner, operation) {
                // received a Discard with an And, or a Keep with an Or
                // this means we can skip the decide_with_observers call
                // altogether and simply return the current action
                (Action::Discard, LogicOperation::And) => return Some(Action::Discard),
                (Action::Keep, LogicOperation::Or) => return Some(Action::Keep),
                _ => {}
            }
        }

        let new_action = self.decide_with_observers(state, observers);

        // take the current action that was decided upon via decide_with_observers, and the
        // previously decided action (if any) to arrive at what should be returned as the
        // current decided action
        match (action, new_action, operation) {
            (None, None, _) => None,
            (None, Some(new_action), _) => Some(new_action),
            (Some(old_action), None, _) => Some(old_action),
            (Some(old_action), Some(new_action), LogicOperation::And) => {
                Some(old_action & new_action)
            }
            (Some(old_action), Some(new_action), LogicOperation::Or) => {
                Some(old_action | new_action)
            }
        }
    }
}

/// marker trait for a collection of implementors of [`DeciderHooks`]
///
/// recursively calls [`DeciderHooks::pre_send_hook`] or [`DeciderHooks::post_send_hook`]
/// as appropriate.
///
/// The given [`LogicOperation`] is chained between all implementors of [`DeciderHooks`]
/// for the current [`DecidersList`]. This means that a single group of `DeciderHooks` will
/// all share the same logical operation, i.e. hook AND hook AND hook AND ... etc.
///
/// In order to logically group different sets of hooks, with different logic, we need
/// to make a separate [`Deciders`] tuple for each logical grouping.
///
/// [`Deciders`]: crate::deciders::Deciders
/// [`DeciderHooks`]: crate::deciders::DeciderHooks
/// [`DecidersList`]: crate::DecidersList
/// [`LogicOperation`]: crate::deciders::LogicOperation
pub trait Deciders<O, R>
where
    O: Observers<R>,
    R: Response,
{
    /// called before an [`HttpClient`] sends a [`Request`]
    ///
    /// recursively calls [`DeciderHooks::pre_send_hook`]
    ///
    /// [`HttpClient`]: crate::client::HttpClient
    /// [`Request`]: crate::requests::Request
    /// [`DeciderHooks::pre_send_hook`]: crate::deciders::DeciderHooks::pre_send_hook
    fn call_pre_send_hooks(
        &mut self,
        _state: &SharedState,
        _request: &Request,
        action: Option<Action>,
        _operation: LogicOperation,
    ) -> Option<Action> {
        action
    }

    /// called after an [`HttpClient`] receives a [`Response`]
    ///
    /// recursively calls [`DeciderHooks::post_send_hook`]
    ///
    /// [`HttpClient`]: crate::client::HttpClient
    /// [`Request`]: crate::requests::Request
    /// [`DeciderHooks::post_send_hook`]: crate::deciders::DeciderHooks::post_send_hook
    fn call_post_send_hooks(
        &mut self,
        _state: &SharedState,
        _observers: &O,
        action: Option<Action>,
        _operation: LogicOperation,
    ) -> Option<Action> {
        action
    }
}

impl<O, R> Deciders<O, R> for ()
where
    O: Observers<R>,
    R: Response,
{
}

impl<Head, Tail, O, R> Deciders<O, R> for (Head, Tail)
where
    Head: DeciderHooks<O, R>,
    Tail: Deciders<O, R> + DecidersList,
    O: Observers<R>,
    R: Response,
{
    fn call_pre_send_hooks(
        &mut self,
        state: &SharedState,
        request: &Request,
        action: Option<Action>,
        operation: LogicOperation,
    ) -> Option<Action> {
        let action = self.0.pre_send_hook(state, request, action, operation);
        self.1
            .call_pre_send_hooks(state, request, action, operation)
    }

    fn call_post_send_hooks(
        &mut self,
        state: &SharedState,
        observers: &O,
        action: Option<Action>,
        operation: LogicOperation,
    ) -> Option<Action> {
        let action = self.0.post_send_hook(state, observers, action, operation);
        self.1
            .call_post_send_hooks(state, observers, action, operation)
    }
}

#[cfg(all(test, feature = "blocking"))]
mod tests {
    #![allow(clippy::similar_names)]
    use super::*;
    use crate::client::{BlockingClient, BlockingRequests};
    use crate::corpora::RangeCorpus;
    use crate::fuzzers::BlockingFuzzer;
    use crate::mutators::ReplaceKeyword;
    use crate::observers::ResponseObserver;
    use crate::prelude::*;
    use crate::processors::ResponseProcessor;
    use crate::requests::ShouldFuzz;
    use crate::responses::BlockingResponse;
    use crate::schedulers::OrderedScheduler;
    use ::regex::Regex;
    use httpmock::Method::GET;
    use httpmock::MockServer;
    use reqwest;
    use std::time::Duration;

    /// corpus has 3 entries, two of which should be discarded due to the two regex deciders
    /// chained by a logical AND (non-default); chaining deciders with an AND that return
    /// Discards can be thought of as a denylist
    #[test]
    fn pre_send_deciders_used_as_denylist() -> Result<(), Box<dyn std::error::Error>> {
        let srv = MockServer::start();

        let mock = srv.mock(|when, then| {
            // registers hits for 0, 1, 2
            when.method(GET).path_matches(Regex::new("[012]").unwrap());
            then.status(200).body("this is a test");
        });

        // 0, 1, 2
        let range = RangeCorpus::with_stop(3).name("range").build()?;
        let mut state = SharedState::with_corpus(range);

        let req_client = reqwest::blocking::Client::builder()
            .timeout(Duration::from_secs(1))
            .build()?;

        let client = BlockingClient::with_client(req_client);

        let mutator = ReplaceKeyword::new(&"FUZZ", "range");

        let request = Request::from_url(&srv.url("/FUZZ"), Some(&[ShouldFuzz::URLPath]))?;

        // discard if path matches '1'
        let decider1 = RequestRegexDecider::new("1", |regex, request, _state| {
            if regex.is_match(request.path().inner()) {
                Action::Discard
            } else {
                Action::Keep
            }
        });

        // discard if path matches '2'
        let decider2 = RequestRegexDecider::new("2", |regex, request, _state| {
            if regex.is_match(request.path().inner()) {
                Action::Discard
            } else {
                Action::Keep
            }
        });

        let scheduler = OrderedScheduler::new(state.clone())?;
        let response_observer: ResponseObserver<BlockingResponse> = ResponseObserver::new();

        let observers = build_observers!(response_observer);
        let deciders = build_deciders!(decider1, decider2);
        let mutators = build_mutators!(mutator);

        let mut fuzzer = BlockingFuzzer::new()
            .client(client)
            .request(request)
            .scheduler(scheduler)
            .mutators(mutators)
            .observers(observers)
            .deciders(deciders)
            .pre_send_logic(LogicOperation::And) // this call is key to making a denylist work with chained Discard actions
            .build();

        fuzzer.fuzz_once(&mut state)?;

        // /1 and /2 never sent
        mock.assert_calls(1);

        Ok(())
    }

    /// corpus has 3 entries, two of which should be kept due to the two regex deciders
    /// chained by a logical OR; chaining deciders with an OR that return
    /// Discard can be thought of as an allowlist
    #[test]
    fn pre_send_deciders_used_as_allow_list() -> Result<(), Box<dyn std::error::Error>> {
        let srv = MockServer::start();

        let mock = srv.mock(|when, then| {
            when.method(GET).path_matches(Regex::new("[012]").unwrap());
            then.status(200).body("this is a test");
        });

        let range = RangeCorpus::with_stop(3).name("range").build()?;
        let mut state = SharedState::with_corpus(range);

        let req_client = reqwest::blocking::Client::builder()
            .timeout(Duration::from_secs(1))
            .build()?;

        let client = BlockingClient::with_client(req_client);

        let mutator = ReplaceKeyword::new(&"FUZZ", "range");

        let request = Request::from_url(&srv.url("/FUZZ"), Some(&[ShouldFuzz::URLPath]))?;

        let decider1 = RequestRegexDecider::new("1", |regex, request, _state| {
            if regex.is_match(request.path().inner()) {
                Action::Keep
            } else {
                Action::Discard
            }
        });

        let decider2 = RequestRegexDecider::new("2", |regex, request, _state| {
            if regex.is_match(request.path().inner()) {
                Action::Keep
            } else {
                Action::Discard
            }
        });

        let scheduler = OrderedScheduler::new(state.clone())?;
        let response_observer: ResponseObserver<BlockingResponse> = ResponseObserver::new();

        let observers = build_observers!(response_observer);
        let deciders = build_deciders!(decider1, decider2);
        let mutators = build_mutators!(mutator);

        let mut fuzzer = BlockingFuzzer::new()
            .client(client)
            .request(request)
            .scheduler(scheduler)
            .mutators(mutators)
            .observers(observers)
            .deciders(deciders)
            .build();

        fuzzer.fuzz_once(&mut state)?;

        // only /1 and /2 sent
        mock.assert_calls(2);

        Ok(())
    }

    /// corpus has 3 entries, two of which should be discarded due to the two regex deciders
    /// chained by a logical AND (non-default); chaining deciders with an AND that return
    /// Discards can be thought of as a denylist
    #[test]
    fn post_send_deciders_used_as_denylist() -> Result<(), Box<dyn std::error::Error>> {
        let srv = MockServer::start();

        let mock_200s = srv.mock(|when, then| {
            // registers 200 response for 0
            when.method(GET).path("/0");
            then.status(200).body("this is a test");
        });
        let mock_401s = srv.mock(|when, then| {
            // registers 401 response for 1
            when.method(GET).path("/1");
            then.status(401).body("this is a test");
        });
        let mock_404s = srv.mock(|when, then| {
            // registers 404 response for 2
            when.method(GET).path("/2");
            then.status(404).body("this is a test");
        });
        let mock_tracked_side_effects = srv.mock(|when, then| {
            // registers 404 response for 2
            when.method(GET).path("/side-effect");
            then.status(301).body("this is a test");
        });

        // 0, 1, 2
        let range = RangeCorpus::with_stop(3).name("range").build()?;
        let mut state = SharedState::with_corpus(range);

        let req_client = reqwest::blocking::Client::builder()
            .timeout(Duration::from_secs(1))
            .build()?;

        // cloning so i can reuse the client to produce the testable side-effect
        let client = BlockingClient::with_client(req_client);
        let side_effect_generator = client.clone();

        let mutator = ReplaceKeyword::new(&"FUZZ", "range");

        let request = Request::from_url(&srv.url("/FUZZ"), Some(&[ShouldFuzz::URLPath]))?;

        // discard if response's status code matches 401
        let decider1 = StatusCodeDecider::new(401, |status, observed, _state| {
            if status == observed {
                Action::Discard
            } else {
                Action::Keep
            }
        });

        // discard if response's status code matches 404
        let decider2 = StatusCodeDecider::new(404, |status, observed, _state| {
            if status == observed {
                Action::Discard
            } else {
                Action::Keep
            }
        });

        let side_effect_url = srv.url("/side-effect");

        let processor = ResponseProcessor::new(
            move |observer: &ResponseObserver<BlockingResponse>, action, _state| {
                if let Some(action) = action {
                    if matches!(action, Action::Discard) {
                        assert!([401, 404].contains(&observer.status_code()));
                        let req = Request::from_url(&side_effect_url, None).unwrap();
                        side_effect_generator.send(req).unwrap();
                    }
                }
            },
        );

        let scheduler = OrderedScheduler::new(state.clone())?;
        let response_observer: ResponseObserver<BlockingResponse> = ResponseObserver::new();

        let observers = build_observers!(response_observer);
        let deciders = build_deciders!(decider1, decider2);
        let mutators = build_mutators!(mutator);
        let processors = build_processors!(processor);

        let mut fuzzer = BlockingFuzzer::new()
            .client(client)
            .request(request)
            .scheduler(scheduler)
            .mutators(mutators)
            .observers(observers)
            .processors(processors)
            .deciders(deciders)
            .post_send_logic(LogicOperation::And) // this call is key to making a denylist work with chained Discard actions
            .build();

        // this call is key to making a denylist work with chained Discard actions

        fuzzer.fuzz_once(&mut state)?;

        mock_200s.assert_calls(1);
        mock_401s.assert_calls(1);
        mock_404s.assert_calls(1); // just ensures the right endpoints were hit

        // processor should have hit this endpoint for each discarded item
        mock_tracked_side_effects.assert_calls(2);

        Ok(())
    }

    /// corpus has 3 entries, two of which should be kept due to the two regex deciders
    /// chained by a logical OR; chaining deciders with an OR that return
    /// Keep can be thought of as an allowlist
    #[test]
    fn post_send_deciders_used_as_allow_list() -> Result<(), Box<dyn std::error::Error>> {
        let srv = MockServer::start();

        let mock_200s = srv.mock(|when, then| {
            // registers 200 response for 0
            when.method(GET).path("/0");
            then.status(200).body("this is a test");
        });
        let mock_403s = srv.mock(|when, then| {
            // registers 403 response for 1
            when.method(GET).path("/1");
            then.status(403).body("this is a test");
        });
        let mock_404s = srv.mock(|when, then| {
            // registers 404 response for 2
            when.method(GET).path("/2");
            then.status(404).body("this is a test");
        });
        let mock_tracked_side_effects = srv.mock(|when, then| {
            // registers 404 response for 2
            when.method(GET).path("/side-effect");
            then.status(301).body("this is a test");
        });

        let range = RangeCorpus::with_stop(3).name("range").build()?;
        let mut state = SharedState::with_corpus(range);

        let req_client = reqwest::blocking::Client::builder()
            .timeout(Duration::from_secs(1))
            .build()?;

        // cloning so i can reuse the client to produce the testable side-effect
        let client = BlockingClient::with_client(req_client);
        let side_effect_generator = client.clone();

        let mutator = ReplaceKeyword::new(&"FUZZ", "range");

        let request = Request::from_url(&srv.url("/FUZZ"), Some(&[ShouldFuzz::URLPath]))?;

        // keep if response's status code matches 200
        let decider1 = StatusCodeDecider::new(200, |status, observed, _state| {
            if status == observed {
                Action::Keep
            } else {
                Action::Discard
            }
        });

        // keep if response's status code matches 403
        let decider2 = StatusCodeDecider::new(403, |status, observed, _state| {
            if status == observed {
                Action::Keep
            } else {
                Action::Discard
            }
        });

        let side_effect_url = srv.url("/side-effect");

        let processor = ResponseProcessor::new(
            move |observer: &ResponseObserver<BlockingResponse>, action, _state| {
                if let Some(action) = action {
                    if matches!(action, Action::Keep) {
                        assert!([200, 403].contains(&observer.status_code()));
                        let req = Request::from_url(&side_effect_url, None).unwrap();
                        side_effect_generator.send(req).unwrap();
                    }
                }
            },
        );

        let scheduler = OrderedScheduler::new(state.clone())?;
        let response_observer: ResponseObserver<BlockingResponse> = ResponseObserver::new();

        let observers = build_observers!(response_observer);
        let deciders = build_deciders!(decider1, decider2);
        let mutators = build_mutators!(mutator);
        let processors = build_processors!(processor);

        let mut fuzzer = BlockingFuzzer::new()
            .client(client)
            .request(request)
            .scheduler(scheduler)
            .mutators(mutators)
            .observers(observers)
            .processors(processors)
            .deciders(deciders)
            .build();

        fuzzer.fuzz_once(&mut state)?;

        mock_200s.assert_calls(1);
        mock_403s.assert_calls(1);
        mock_404s.assert_calls(1); // just ensures the right endpoints were hit

        // processor should have hit this endpoint for each discarded item
        mock_tracked_side_effects.assert_calls(2);

        Ok(())
    }
}