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
/* Copyright (c) 2018 Debily
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in the
 * Software without restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies of the
 * Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
 * KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
 * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
 * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

extern crate rand;
use self::rand::{Rng, OsRng};
use std;

/// The `MutatorEngine` struct used to mutate fuzzing data
pub struct MutatorEngine {
    rng: OsRng,
    mutationgrade: f64,
    truncationgrade: f64,
}

impl MutatorEngine {
    /// Creates a new `MutatorEngine` struct
    pub fn new() -> Result<MutatorEngine, std::io::Error> {
        Ok(MutatorEngine {
            rng: OsRng::new()?,
            mutationgrade: 0.01,
            truncationgrade: 0.999,
        })
    }

    /// If you don't need specialized mutation you can use
    /// this function to choose the kind of
    /// mutation at random.
    #[inline]
    pub fn mutate(&mut self, data: &mut Vec<u8>) {
        match rand_usize(0, 4, &mut self.rng) {
            0 => self.special_ints(data),
            1 => self.bitflipping(data),
            2 => self.byteflipping(data),
            3 => self.add_substract_binary(data),
            4 => self.chunk_spew(data),
            _ => unreachable!(),
        }
    }

    /// Flips bits at random in `data`.
    #[inline]
    pub fn bitflipping(&mut self, data: &mut Vec<u8>) {
        let mut count = ((data.len() as f64 * 8.0) * self.mutationgrade) as i64;
        let mut bit: usize;
        let mut idx_bit: usize;
        let mut idx_byte: usize;
        let mut data_len: usize;

        if count == 0 {
            count = 1;
        }


        for _ in 0..count {
            data_len = data.len();

            if data_len <= 1 {
                self.append_data(data);
                continue;
            }

            bit = rand_usize(0, data_len * 8 - 1, &mut self.rng);
            idx_bit = bit % 8;
            idx_byte = bit / 8;

            if let Some(idx) = data.get_mut(idx_byte) {
                *idx ^= 1 << idx_bit;
            }
        }
    }

    /// This function flips bytes in `data`
    #[inline]
    pub fn byteflipping(&mut self, data: &mut Vec<u8>) {
        let mut count = (data.len() as f64 * self.mutationgrade) as usize;
        let mut index: usize;

        if count == 0 {
            count = 1;
        }
        for _ in 0..count {
            index = rand_usize(
                0,
                if data.len() <= 1 {
                    self.append_data(data);
                    continue;
                } else {
                    data.len() - 1
                },
                &mut self.rng,
            );
            if index < data.len() {
                data[index] = rand_u8(&mut self.rng);
            }
        }
    }

    /// In this function some special integers will be
    /// placed in `data`.
    #[inline]
    pub fn special_ints(&mut self, data: &mut Vec<u8>) {
        let byte: [u8; 3] = [0xff, 0x7f, 0];
        let short: [[u8; 2]; 2] = [[0xff, 0xff], [0x0, 0x0]];
        let int32: [[u8; 4]; 5] = [
            [0xff, 0xff, 0xff, 0xff],
            [0, 0, 0, 0],
            [0x80, 0, 0, 0],
            [0x40, 0, 0, 0],
            [0x7f, 0xff, 0xff, 0xff],
        ];
        let mut count = (data.len() as f64 * self.mutationgrade) as usize;
        let mut index: usize;
        let mut n_size: u8;
        let mut sz: i64;
        let mut result: usize;

        if count == 0 {
            count = 1;
        }
        for _ in 0..count {
            result = rand_usize(0, 2, &mut self.rng);
            if result == 0 {
                /* u8 */
                index = rand_usize(
                    0,
                    if data.len() == 0 {
                        self.append_data(data);
                        continue;
                    } else {
                        if data.len() > 0 {
                            data.len() - 1
                        } else {
                            continue;
                        }
                    },
                    &mut self.rng,
                );
                data[index] = byte[rand_usize(0, 2, &mut self.rng)];
            } else if result == 1 {
                /* u16 */
                n_size = 2;
                sz = data.len() as i64 - n_size as i64;
                if sz <= 0 {
                    continue;
                }
                index = rand_usize(0, sz as usize, &mut self.rng);
                for i in short[rand_usize(0, 1, &mut self.rng)].iter() {
                    if index < data.len() {
                        data[index] = *i;
                        index += 1;
                    }
                }
            } else {
                /* u32 */
                n_size = 4;
                sz = data.len() as i64 - n_size as i64;
                if sz <= 0 {
                    continue;
                }
                index = rand_usize(0, sz as usize, &mut self.rng);
                for i in int32[rand_usize(0, 1, &mut self.rng)].iter() {
                    if index < data.len() {
                        data[index] = *i;
                        index += 1;
                    }
                }
            }
        }
    }

    /// In this function values in `data` will be decremented
    /// or incremented a random number of times.
    #[inline]
    pub fn add_substract_binary(&mut self, data: &mut Vec<u8>) {
        let mut count = (data.len() as f64 * self.mutationgrade) as usize;
        let mut substract: usize;
        let mut index: usize;
        let mut un8: u8;

        if count == 0 {
            count = 1;
        }
        for _ in 0..count {
            substract = rand_usize(0, 1, &mut self.rng);
            index = rand_usize(
                0,
                if data.len() == 0 {
                    self.append_data(data);
                    continue;
                } else {
                    if data.len() > 0 {
                        data.len() - 1
                    } else {
                        continue;
                    }
                },
                &mut self.rng,
            );
            un8 = rand_u8(&mut self.rng);
            if substract == 1 {
                if data[index] >= un8 {
                    data[index] = data[index] - un8;
                }
            } else {
                if (data[index] as u32 + un8 as u32) < (u8::max_value() as u32) {
                    data[index] = data[index] + un8;
                }
            }
        }
    }

    /// This function will replace a value in `data` with
    /// another one in `data`.<br>
    /// Here is an example:<br>
    /// [1,2,3,4,5,6,7,8,9,0]<br>
    ///  <- - - - - - -<br>
    /// [6,2,3,4,5,6,7,8,9,0]<br>
    /// In the above example 6 has been copied where 1 has
    /// previously been.
    #[inline]
    pub fn chunk_spew(&mut self, data: &mut Vec<u8>) {
        let mut count = (data.len() as f64 * self.mutationgrade) as usize;
        let mut offset_sz_src: usize;
        let mut offsetsrc: usize;
        let mut offsetdest: usize;

        if count == 0 {
            count = 1;
        }
        for _ in 0..count {
            offset_sz_src = rand_usize(
                0,
                if data.len() / 2 == 0 {
                    self.append_data(data);
                    continue;
                } else {
                    data.len() / 2
                },
                &mut self.rng,
            );
            offsetsrc = rand_usize(
                0,
                if (data.len() as i64 - offset_sz_src as i64) < 0 {
                    self.append_data(data);
                    continue;
                } else {
                    data.len() - offset_sz_src
                },
                &mut self.rng,
            );
            offsetdest = rand_usize(
                0,
                if (data.len() as i64 - offset_sz_src as i64) < 0 {
                    self.append_data(data);
                    continue;
                } else {
                    data.len() - offset_sz_src
                },
                &mut self.rng,
            );
            for _ in 0..offset_sz_src {
                if offsetsrc < data.len() && offsetdest < data.len() {
                    /* Using the offsets like raw pointers */
                    data[offsetdest] = data[offsetsrc];
                    offsetdest += 1;
                    offsetsrc += 1;
                } else {
                    /* Errors do not matter, we will just save time and break to continue */
                    break;
                }
            }
        }
    }

    /// Appends random bytes to `data`.
    /// # Remarks
    /// Do not use this function too often,
    /// if `data` becomes too long it will take too long to
    /// process it with the other functions since it takes
    /// exponentially longer to process.
    /// This function will be called automagically if a function
    /// detects that `data` is too short.
    #[inline]
    pub fn append_data(&mut self, data: &mut Vec<u8>) {
        let mut count = (data.len() as f64 * self.mutationgrade) as usize;

        if count == 0 {
            count = 1;
        }
        for _ in 0..count {
            data.push(rand_u8(&mut self.rng));
        }
    }

    /// Converts `data` to valid UTF-8.
    /// This can be used to make fuzzing parsers that only
    /// accept UTF-8 encoding more effective.
    #[inline]
    pub fn to_utf8(&mut self, data: &Vec<u8>) -> Vec<u8> {
        /*
         * Using the std library implementation because it gets much more maintenance
         * and bug fixes.
         */
        Vec::from(String::from_utf8_lossy(&data[..]).as_bytes())
    }

    /// Shrinks `data` to a smaller size.
    /// # Remarks
    /// Do not use this function too often, in a loop it
    /// will keep the length of `data` at 0.
    #[allow(dead_code)]
    /*
     * Since this function might not
     * be called at all
     */
    #[inline]
    pub fn truncate(&mut self, data: &mut Vec<u8>) {
        let mut count: usize;

        if data.len() == 0 {
            return;
        }
        count = (data.len() as f64 * self.truncationgrade) as usize;
        if count == 0 {
            count = 1;
        }
        data.truncate(count);
    }

    /// Creates a String based on the data provided in `data`
    #[inline]
    pub fn to_string(&mut self, data: &Vec<u8>) -> Result<String, ()> {
        if let Ok(ret) = std::str::from_utf8(&self.to_utf8(data)[..]) {
            Ok(String::from(ret))
        } else {
            Err(())
        }
    }

    /// Borrows the engine's RNG
    #[inline]
    pub fn borrow_rng(&mut self) -> &mut OsRng {
        &mut self.rng
    }
}

#[inline]
fn rand_usize(min: usize, max: usize, rng: &mut OsRng) -> usize {
    rng.gen_range(min, max + 1)
}


#[inline]
fn rand_u8(rng: &mut OsRng) -> u8 {
    rng.gen_range(0u16, u8::max_value() as u16 + 1) as u8
    /* The cast to u16 is needed because it would not include the highest u8 otherwise.
     * The cast itself is save from overflowing because it can only generate a number between
     * the highest and lowest u8
     */
}

/// The mutator will fuzz itself in the hopes of identifing bugs early.
/// To try it just type `cargo test` in the crates root.
#[test]
fn mutate_tester() {
    let mut data = vec![0xde, 0xad, 0xbe, 0xef];
    let testnum = 500000;

    if let Ok(mut mutatoren) = MutatorEngine::new() {
        mutatoren.mutation_grade(0.199);
        for _ in 0..testnum {
            mutatoren.mutate(&mut data);
            let utf8_vec = mutatoren.to_utf8(&data);
            mutatoren.truncate(&mut data);
            match std::str::from_utf8(&utf8_vec[..]) {
                Ok(_) => {}
                Err(_) => panic!("to_utf8() failed."),
            };
        }
    }
}