pwn-helper 0.1.0

A crate to help with binary exploitation
Documentation
pub use pwn_helper_macros::bytes;
pub use pwn_helper_macros::pack;

pub fn concat_bytes(l: &[u8], r: &[u8]) -> Vec<u8> {
    let mut l = l.to_vec();
    for x in r {
        l.push(*x)
    }
    l
}

pub fn concat_vec(mut l: Vec<u8>, r: &[u8]) -> Vec<u8> {
    for x in r {
        l.push(*x)
    }
    l
}

/// Pads the end of l to length `len` with `c`
pub fn ljust(l: &[u8], c: u8, len: usize) -> Vec<u8> {
    let cur_len = l.len();
    let mut l = l.to_vec();

    if cur_len < len {
        for _ in 0..len - cur_len {
            l.push(c)
        }
    }

    l
}

/// Pads the beginning of l to length `len` with `c`
pub fn rjust(l: &[u8], c: u8, len: usize) -> Vec<u8> {
    let cur_len = l.len();

    if cur_len < len {
        let mut out = Vec::with_capacity(len);

        for _ in 0..len - cur_len {
            out.push(c);
        }

        for x in l {
            out.push(*x);
        }

        out
    } else {
        l.to_vec()
    }
}

/// Copies the array `l` into the output `len` times
pub fn multiply_bytes(l: &[u8], len: usize) -> Vec<u8> {
    let mut out = Vec::with_capacity(len * l.len());

    for _ in 0..len {
        for x in l {
            out.push(*x)
        }
    }

    out
}

#[cfg(test)]
mod tests {
    use pwn_helper_macros::{bytes, pack};

    use crate::bytes::{ljust, rjust};

    #[test]
    fn test_ljust() {
        let justified = ljust(b"Test", 0, 0x20);

        assert_eq!(&justified, b"Test\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00");
    }

    #[test]
    fn test_rjust() {
        let justified = rjust(b"Test", 0, 0x20);

        assert_eq!(&justified, b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00Test");
    }

    #[test]
    #[allow(clippy::eq_op)]
    fn test_mul_bytestr() {
        assert_eq!(bytes!(b"OwO" * 2), b"OwOOwO");
    }

    #[test]
    #[allow(clippy::eq_op)]
    fn test_add_byte() {
        assert_eq!(bytes!(b'O' + b'U'), b"OU");
    }

    #[test]
    #[allow(clippy::eq_op)]
    fn test_add_bytestr() {
        assert_eq!(bytes!(b"OwO" + b"UwU"), b"OwOUwU");
    }

    #[test]
    #[allow(clippy::eq_op)]
    fn test_add_bytestr_byte() {
        assert_eq!(bytes!(b"OwOUw" + b'U'), b"OwOUwU");
    }

    #[test]
    #[allow(clippy::eq_op)]
    fn test_add_byte_bytestr() {
        assert_eq!(bytes!(b'O' + b"wOUwU"), b"OwOUwU");
    }

    #[test]
    #[allow(clippy::eq_op)]
    fn test_pack_32() {
        assert_eq!(pack!(0xcafebabe, 32), b"\xbe\xba\xfe\xca");
    }

    #[test]
    #[allow(clippy::eq_op)]
    fn test_pack_64() {
        assert_eq!(pack!(0xcafebabe, 64), b"\xbe\xba\xfe\xca\x00\x00\x00\x00");
    }
}