Playing with libnet

I wrote a function that writes packets to the wire. It takes the source IP, destination IP, and destination port. The fucntion, writePackets(), uses the libnet headers. On ArchLinux these can be installed with pacman -Sy libnet. I was inspired to write this because I am in the process of reading Hacking: The art of exploitation by Jon Erickson. It covers a lot of the basics of reading assembly as well as some often over looked programing flaws that lead to buffer overflows.

// Function for writing new packets
// hard time documenting everything here, it's a bit of a mess
// Most of this was sort of guess and check along with some learn by example
// Not sure what every piece of libnet_build_tcp and libnet_build_ipv4 should be
void writePacket(u_long src_ip, u_long dst_ip, u_short dst_prt, libnet_t *l)
{
        u_short src_prt;
        int bytes_written, checkerr;

        /* build tcp header */

        checkerr = libnet_build_tcp(
                        src_prt = libnet_get_prand(LIBNET_PRu16),
                        dst_prt,
                        libnet_get_prand(LIBNET_PRu32), // SEQ num
                        libnet_get_prand(LIBNET_PRu32), // ACK num
                        TH_SYN,                         // set syn flag
                        libnet_get_prand(LIBNET_PRu16), // window size
                        0,
                        0,
                        LIBNET_TCP_H,
                        NULL,
                        0,
                        l,                              // packet holder
                        0);
        if (checkerr == -1) {
                printf("Error building TCP header: %s\n", libnet_geterror(l));
                libnet_destroy(l);
                exit(EXIT_FAILURE);
        }
        /* build ip header */

        checkerr = libnet_build_ipv4(
                        LIBNET_TCP_H + LIBNET_IPV4_H,   // size of packet
                        0,
                        libnet_get_prand(LIBNET_PRu16), // port?
                        0,
                        libnet_get_prand(LIBNET_PR8),   // ???
                        IPPROTO_TCP,
                        0,
                        src_ip, 
                        dst_ip,
                        NULL,
                        0,
                        l,                              // packet holder
                        0);
        if (checkerr == -1) {
                printf("Error building IP header: %s\n", libnet_geterror(l));
                libnet_destroy(l);
                exit(EXIT_FAILURE);
        }
        
        bytes_written = libnet_write(l);
        if (bytes_written != -1)
                printf("%d bytes written.\n", bytes_written);
        else
                printf("Error writing packet: %s\n", libnet_geterror(l));

        libnet_clear_packet(l);                         // clear out the packet
        
}

Tags: