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
use crate::input::HasPackets;
use libafl::{
    bolts::{rands::Rand, tuples::Named, HasLen},
    inputs::Input,
    mutators::{MutationResult, Mutator},
    state::HasRand,
    Error,
};
use std::marker::PhantomData;

/// A mutator that duplicates a single, random packet.
///
/// It respects an upper bound on the number of packets
/// passed as an argument to the constructor.
///
/// # Example
/// ```
/// // Make sure that we never exceed 16 packets in an input
/// let mutator = PacketDuplicateMutator::new(16);
/// ```
pub struct PacketDuplicateMutator<P>
where
    P: Clone,
{
    max_packets: usize,
    phantom: PhantomData<P>,
}

impl<P> PacketDuplicateMutator<P>
where
    P: Clone,
{
    /// Create a new PacketDuplicateMutator with an upper bound on the number of packets
    pub fn new(max_packets: usize) -> Self {
        Self {
            max_packets,
            phantom: PhantomData,
        }
    }
}

impl<I, S, P> Mutator<I, S> for PacketDuplicateMutator<P>
where
    P: Clone,
    I: Input + HasLen + HasPackets<P>,
    S: HasRand,
{
    fn mutate(&mut self, state: &mut S, input: &mut I, _stage_idx: i32) -> Result<MutationResult, Error> {
        if input.len() >= self.max_packets {
            return Ok(MutationResult::Skipped);
        }

        let from = state.rand_mut().below(input.len() as u64) as usize;
        let to = state.rand_mut().below(input.len() as u64 + 1) as usize;

        if from == to {
            return Ok(MutationResult::Skipped);
        }

        let copy = input.packets()[from].clone();
        input.packets_mut().insert(to, copy);

        Ok(MutationResult::Mutated)
    }
}

impl<P> Named for PacketDuplicateMutator<P>
where
    P: Clone,
{
    fn name(&self) -> &str {
        "PacketDuplicateMutator"
    }
}