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
#![allow(clippy::use_self)] // clippy false-positive on Action, doesn't want to apply directly to the enums that derive Serialize
use std::fmt::{self, Debug, Display, Formatter};
use std::marker::PhantomData;
use std::ops::{Index, IndexMut};

use super::typestate::NoItems;
use super::{Corpus, CorpusType, Named};
use crate::corpora::typestate::{CorpusBuildState, HasItems, HasName, NoName};
use crate::input::Data;
use crate::std_ext::fmt::DisplayExt;
use crate::std_ext::ops::Len;
use crate::AsInner;

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// Represents logical groupings of HTTP methods.
///
/// All method groupings were taken from [RFC 7231](https://tools.ietf.org/html/rfc7231#section-4.2)
#[derive(Copy, Clone, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
enum HttpMethodGroup {
    /// Represents HTTP methods that are deemed 'safe', i.e. it doesn't alter the state of the server
    ///
    /// members of this group are: GET, HEAD, OPTIONS, and TRACE
    #[default]
    Safe,

    /// Represents HTTP methods that are deemed 'idempotent', i.e. an identical request
    /// can be made once or several times in a row with the same effect while leaving
    /// the server in the same state
    ///
    /// members of this group are: GET, HEAD, OPTIONS, TRACE, PUT, and DELETE
    Idempotent,

    /// Represents HTTP methods that indicate responses to them are allowed to
    /// be stored for future reuse
    ///
    /// members of this group are: GET and HEAD
    Cacheable,

    /// Represents all HTTP methods
    All,
}

/// corpus consisting of http verbs (GET, POST, etc)
///
/// # Examples
///
/// ```
/// # use feroxfuzz::corpora::HttpMethodsCorpus;
/// # use feroxfuzz::prelude::*;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
///
/// // create a Corpus of all HTTP methods
/// let corpus = HttpMethodsCorpus::all().name("corpus").build();
///
/// let expected = vec![
///     "GET",
///     "HEAD",
///     "POST",
///     "PUT",
///     "DELETE",
///     "CONNECT",
///     "OPTIONS",
///     "TRACE",
///     "PATCH",
/// ];
///
/// // resulting HttpMethodsCorpus has 9 entries
/// assert_eq!(corpus.len(), 9);
/// assert_eq!(corpus.items(), &expected);
/// # Ok(())
/// # }
/// ```
///
/// ```
/// # use feroxfuzz::corpora::HttpMethodsCorpus;
/// # use feroxfuzz::prelude::*;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
///
/// // create a Corpus of all HTTP methods
/// let corpus = HttpMethodsCorpus::new().method("GET").method("POST").name("corpus").build();
///
/// let expected = vec![
///     "GET",
///     "POST",
/// ];
///
/// // resulting HttpMethodsCorpus has 9 entries
/// assert_eq!(corpus.len(), 2);
/// assert_eq!(corpus.items(), &expected);
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Default, Debug, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct HttpMethodsCorpus {
    items: Vec<Data>,
    corpus_name: String,
}

impl Corpus for HttpMethodsCorpus {
    fn add(&mut self, value: Data) {
        self.items.push(value);
    }

    fn get(&self, index: usize) -> Option<&Data> {
        self.items.get(index)
    }

    #[inline]
    fn items(&self) -> &[Data] {
        &self.items
    }
}

impl Named for HttpMethodsCorpus {
    fn name(&self) -> &str {
        &self.corpus_name
    }
}

impl HttpMethodsCorpus {
    /// create a default (empty) `HttpMethodsBuilder` consisting of http methods that are
    /// deemed 'safe', i.e. it doesn't alter the state of the server
    ///
    /// # Note
    ///
    /// `HttpMethodsBuilder::build` can only be called after `HttpMethodsBuilder::name` and
    /// `HttpMethodsBuilder::method` have been called.
    ///
    /// There are other constructors to immediately provide the corpus items, if desired.
    ///
    /// - [`HttpMethodsCorpus::all`]
    /// - [`HttpMethodsCorpus::safe`]
    /// - [`HttpMethodsCorpus::idempotent`]
    /// - [`HttpMethodsCorpus::cacheable`]
    #[must_use]
    #[allow(clippy::new_ret_no_self)]
    pub const fn new() -> HttpMethodsBuilder<NoItems, NoName> {
        HttpMethodsBuilder {
            items: None,
            corpus_name: None,
            _item_state: PhantomData,
            _name_state: PhantomData,
        }
    }

    /// create a new [`Corpus`] consisting of all http methods
    ///
    /// members of this group are: GET, HEAD, POST, PUT, DELETE, CONNECT,
    /// OPTIONS, TRACE, and PATCH
    #[must_use]
    pub fn all() -> HttpMethodsBuilder<HasItems, NoName> {
        HttpMethodsBuilder {
            items: Some(Self::from_group(HttpMethodGroup::All)),
            corpus_name: None,
            _item_state: PhantomData,
            _name_state: PhantomData,
        }
    }

    /// create a new [`Corpus`] consisting of HTTP methods that are
    /// deemed 'safe', i.e. it doesn't alter the state of the server
    ///
    /// members of this group are: GET, HEAD, OPTIONS, and TRACE
    #[must_use]
    pub fn safe() -> HttpMethodsBuilder<HasItems, NoName> {
        HttpMethodsBuilder {
            items: Some(Self::from_group(HttpMethodGroup::Safe)),
            corpus_name: None,
            _item_state: PhantomData,
            _name_state: PhantomData,
        }
    }

    /// create a new [`Corpus`] consisting of HTTP methods that are
    /// deemed 'idempotent', i.e. an identical request can be made
    /// once or several times in a row with the same effect while leaving
    /// the server in the same state
    ///
    /// members of this group are: GET, HEAD, OPTIONS, TRACE, PUT, and DELETE
    #[must_use]
    pub fn idempotent() -> HttpMethodsBuilder<HasItems, NoName> {
        HttpMethodsBuilder {
            items: Some(Self::from_group(HttpMethodGroup::Idempotent)),
            corpus_name: None,
            _item_state: PhantomData,
            _name_state: PhantomData,
        }
    }

    /// create a new [`Corpus`] consisting of HTTP methods that
    /// indicate responses to them are allowed to be stored for
    /// future reuse
    ///
    /// members of this group are: GET and HEAD
    #[must_use]
    pub fn cacheable() -> HttpMethodsBuilder<HasItems, NoName> {
        HttpMethodsBuilder {
            items: Some(Self::from_group(HttpMethodGroup::Cacheable)),
            corpus_name: None,
            _item_state: PhantomData,
            _name_state: PhantomData,
        }
    }

    /// given a collection of items, create a new `HttpMethodsBuilder`
    ///
    /// # Note
    ///
    /// `HttpMethodsBuilder::build` can only be called after `HttpMethodsBuilder::name` and
    /// `HttpMethodsBuilder::method` or `HttpMethodsBuilder::methods` have been called.
    ///
    /// # Examples
    ///
    /// ```
    /// # use feroxfuzz::corpora::HttpMethodsCorpus;
    /// let methods_corpus = HttpMethodsCorpus::with_methods(["GET", "POST"]).name("methods").build();
    /// ```
    #[inline]
    pub fn with_methods<I, T>(http_methods: I) -> HttpMethodsBuilder<HasItems, NoName>
    where
        Data: From<T>,
        I: IntoIterator<Item = T>,
    {
        HttpMethodsBuilder {
            items: Some(http_methods.into_iter().map(Data::from).collect()),
            corpus_name: None,
            _item_state: PhantomData,
            _name_state: PhantomData,
        }
    }

    /// create a new [`Corpus`] of HTTP methods from the given [`HttpMethodGroup`]
    #[must_use]
    fn from_group(group: HttpMethodGroup) -> Vec<Data> {
        let mut items = Vec::new();

        match group {
            HttpMethodGroup::Safe => {
                items.push("GET".into());
                items.push("HEAD".into());
                items.push("OPTIONS".into());
                items.push("TRACE".into());
            }
            HttpMethodGroup::Idempotent => {
                items.push("GET".into());
                items.push("HEAD".into());
                items.push("OPTIONS".into());
                items.push("TRACE".into());
                items.push("PUT".into());
                items.push("DELETE".into());
            }
            HttpMethodGroup::Cacheable => {
                items.push("GET".into());
                items.push("HEAD".into());
            }
            HttpMethodGroup::All => {
                items.push("GET".into());
                items.push("HEAD".into());
                items.push("POST".into());
                items.push("PUT".into());
                items.push("DELETE".into());
                items.push("CONNECT".into());
                items.push("OPTIONS".into());
                items.push("TRACE".into());
                items.push("PATCH".into());
            }
        }

        items
    }

    /// get a mutable reference to the inner collection of corpus items
    #[must_use]
    #[inline]
    pub fn items_mut(&mut self) -> &mut [Data] {
        &mut self.items
    }

    /// Returns a mutable iterator over the items in the corpus.
    #[must_use]
    pub fn iter_mut(&mut self) -> <&mut [Data] as IntoIterator>::IntoIter {
        <&mut Self as IntoIterator>::into_iter(self)
    }

    /// Returns an iterator over the items in the corpus.
    #[must_use]
    pub fn iter(&self) -> <&[Data] as IntoIterator>::IntoIter {
        <&Self as IntoIterator>::into_iter(self)
    }
}

impl Len for HttpMethodsCorpus {
    #[inline]
    fn len(&self) -> usize {
        self.items.len()
    }
}

impl AsInner for HttpMethodsCorpus {
    type Type = Vec<Data>;

    fn inner(&self) -> &Self::Type {
        &self.items
    }
}

impl Display for HttpMethodsCorpus {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.display_top(3))
    }
}

impl Index<usize> for HttpMethodsCorpus {
    type Output = Data;

    fn index(&self, index: usize) -> &Self::Output {
        &self.items()[index]
    }
}

impl IndexMut<usize> for HttpMethodsCorpus {
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        &mut self.items_mut()[index]
    }
}

/// non-consuming mutable iterator over `HttpMethodsCorpus`
///
/// # Examples
///
/// ```
/// # use feroxfuzz::corpora::HttpMethodsCorpus;
/// # use feroxfuzz::prelude::*;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
///
/// // create a Corpus of safe HTTP methods
/// let mut corpus = HttpMethodsCorpus::safe().name("corpus").build();
///
/// let expected = Data::from("a");
///
/// // resulting HttpMethodsCorpus has 4 entries
/// assert_eq!(corpus.len(), 4);
///
/// for item in &mut corpus {
///     // not useful, just showing that we can mutate the items
///     *item = "a".into();
/// }
///
/// for item in &corpus {
///     assert_eq!(&expected, item);
/// }
/// # Ok(())
/// # }
/// ```
///
impl<'i> IntoIterator for &'i mut HttpMethodsCorpus {
    /// the type of the elements being iterated over
    type Item = &'i mut Data;

    /// the kind of iterator we're turning `HttpMethodsCorpus` into
    type IntoIter = <&'i mut [Data] as IntoIterator>::IntoIter;

    /// creates an iterator from `HttpMethodsCorpus.items`
    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.items.iter_mut()
    }
}

/// consuming iterator over `HttpMethodsCorpus`
///
/// # Examples
///
/// ```
/// # use feroxfuzz::corpora::HttpMethodsCorpus;
/// # use feroxfuzz::prelude::*;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
///
/// // create a Corpus of idempotent HTTP methods
/// let corpus = HttpMethodsCorpus::idempotent().name("corpus").build();
///
/// let expected = corpus.clone();
///
/// // resulting HttpMethodsCorpus has 6 entries
/// assert_eq!(corpus.len(), 6);
///
/// let mut gathered = vec![];
///
/// for item in corpus {
///     gathered.push(item);
/// }
///
/// assert_eq!(gathered, expected.items());
/// # Ok(())
/// # }
/// ```
///
impl IntoIterator for HttpMethodsCorpus {
    /// the type of the elements being iterated over
    type Item = Data;

    /// the kind of iterator we're turning `HttpMethodsCorpus` into
    type IntoIter = <Vec<Data> as IntoIterator>::IntoIter;

    /// creates an iterator from `HttpMethodsCorpus.items`
    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.items.into_iter()
    }
}

/// non-consuming iterator over `HttpMethodsCorpus`
///
/// # Examples
///
/// ```
/// # use feroxfuzz::corpora::HttpMethodsCorpus;
/// # use feroxfuzz::prelude::*;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
///
/// // create a Corpus of cacheable HTTP methods
/// let corpus = HttpMethodsCorpus::cacheable().name("corpus").build();
///
/// // resulting HttpMethodsCorpus has 2 entries
/// assert_eq!(corpus.len(), 2);
///
/// let mut gathered = vec![];
///
/// for item in &corpus {
///     gathered.push(item);
/// }
///
/// assert_eq!(gathered, corpus.items());
/// # Ok(())
/// # }
/// ```
impl<'i> IntoIterator for &'i HttpMethodsCorpus {
    /// the type of the elements being iterated over
    type Item = &'i Data;

    /// the kind of iterator we're turning `HttpMethodsCorpus` into
    type IntoIter = <&'i [Data] as IntoIterator>::IntoIter;

    /// creates an iterator from `HttpMethodsCorpus.items`
    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.items.iter()
    }
}

pub struct HttpMethodsBuilder<IS, NS>
where
    IS: CorpusBuildState,
    NS: CorpusBuildState,
{
    items: Option<Vec<Data>>,
    corpus_name: Option<String>,
    _item_state: PhantomData<IS>,
    _name_state: PhantomData<NS>,
}

impl<IS> HttpMethodsBuilder<IS, NoName>
where
    IS: CorpusBuildState,
{
    pub fn name(self, corpus_name: &str) -> HttpMethodsBuilder<IS, HasName> {
        HttpMethodsBuilder {
            items: self.items,
            corpus_name: Some(corpus_name.to_string()),
            _item_state: PhantomData,
            _name_state: PhantomData,
        }
    }
}

impl<IS, NS> HttpMethodsBuilder<IS, NS>
where
    IS: CorpusBuildState,
    NS: CorpusBuildState,
{
    pub fn method<T>(self, http_method: T) -> HttpMethodsBuilder<HasItems, NS>
    where
        Data: From<T>,
    {
        let mut items = self.items.unwrap_or_default();
        items.push(http_method.into());

        HttpMethodsBuilder {
            items: Some(items),
            corpus_name: self.corpus_name,
            _item_state: PhantomData,
            _name_state: PhantomData,
        }
    }

    pub fn methods<I, T>(self, http_methods: I) -> HttpMethodsBuilder<HasItems, NS>
    where
        Data: From<T>,
        I: IntoIterator<Item = T>,
    {
        let mut items = self.items.unwrap_or_default();

        items.extend(http_methods.into_iter().map(Data::from));

        HttpMethodsBuilder {
            items: Some(items),
            corpus_name: self.corpus_name,
            _item_state: PhantomData,
            _name_state: PhantomData,
        }
    }
}

impl HttpMethodsBuilder<HasItems, HasName> {
    pub fn build(self) -> CorpusType {
        CorpusType::HttpMethods(HttpMethodsCorpus {
            items: self.items.unwrap(),
            corpus_name: self.corpus_name.unwrap(),
        })
    }
}