LIBNET(3)

πŸ“¦ version 1.0.2a, in fedora 43, fedora 44

πŸ’– LIBNET πŸ’– β€” the libnet manual, part 1 of 5 🫢

okay bestie, buckle UP, because this is the "libpwrite" Network Routine Library and we're doing it in five parts. this is part one, so hydrate, sit pretty, and let's go ✨


🌸 NAME 🌸

libnet β€” the "libpwrite" Network Routine Library πŸ’…


πŸ¦‹ DESCRIPTION πŸ¦‹

The Network Library hands you a simple API for the low-level network functions you keep reaching for (mostly packet injection, ngl). With libnet it is genuinely easy to build and write arbitrary network packets β€” like, arbitrary arbitrary. it gives you a portable framework for low-level network packet writing and handling, and the way that it pairs with libpcap?? you can write some really cool stuff, no cap πŸ”₯

libnet includes packet creation at the IP layer and at the link layer, plus a whole host of supplementary and complementary functionality. it's giving full service πŸ’–

for a much more verbose treatment of libnet, including verbosely commented examples, please see the online web-based documentation at http://www.packetfactory.net/libnet/manual/. it's the director's cut, iykyk πŸ“–

✨ SYNOPSIS ✨

#include <libnet.h>

πŸŽ€ PACKET MEMORY MANAGEMENT ROUTINES πŸŽ€

int libnet_init_packet(size_t p_size, u_char **buf);

int libnet_destroy_packet(u_char **buf);

int libnet_init_packet_arena(struct libnet_arena **arena, int p_size,
            u_short p_num);

u_char *libnet_next_packet_from_arena(struct libnet_arena **arena,
            int p_size);

int libnet_destroy_packet_arena(struct libnet_arena **arena);

🌈 ADDRESS RESOLUTION ROUTINES 🌈

u_char *libnet_host_lookup(u_long in, u_short use_name);

void libnet_host_lookup_r(u_long in, u_short use_name, u_char *buf);

u_long libnet_name_resolve(u_char *hostname, u_short use_name);

u_long libnet_get_ipaddr(struct libnet_link_int *l, const u_char *device,
            const u_char *buf);

struct ether_addr *libnet_get_hwaddr(struct libnet_link_int *l,
            const u_char *device, const u_char *buf);

πŸ‘‘ PACKET INJECTION FRAMEWORK ROUTINES πŸ‘‘

int libnet_open_raw_sock(int protocol);

int libnet_close_raw_sock(int fd);

int libnet_select_device(struct sockaddr_in *sin, u_char **device,
            u_char *ebuf);

struct libnet_link_int *libnet_open_link_interface(char *device, char *ebuf);

int libnet_close_link_interface(struct libnet_link_int *l);

int libnet_write_ip(int sock, u_char *packet, int len);

int libnet_write_link_layer(struct libnet_link_int *l, const u_char *device,
             u_char *buf, int len);

int libnet_do_checksum(u_char *buf, int protocol, int len);

u_short libnet_ip_check(u_short *buf, int len);

🧚 PACKET BUILDER ROUTINES 🧚

int libnet_build_arp(u_short hrd, u_short pro, u_short hln, u_short pln,
            u_short op, u_char *sha, u_char *spa, u_char *tha,
            u_char *tpa, const u_char *payload, int payload_s,
            u_char *buf);

int libnet_build_dns(u_short id, u_short flags, u_short num_q,
            u_short num_anws_rr, u_short num_auth_rr,
            u_short num_addi_rr, const u_char *payload, int payload_s,
            u_char *buf);

int libnet_build_ethernet(u_char *daddr, u_char *saddr, u_short id,
            const u_char *payload, int payload_s, u_char *buf);

int libnet_build_icmp_echo(u_char type, u_char code, u_short id,
            u_short seq, const u_char *payload, int payload_s,
            u_char *buf);

int libnet_build_icmp_mask(u_char type, u_char code, u_short id,
            u_short seq, u_long mask, const u_char *payload,
            int payload_s, u_char *buf);

int libnet_build_icmp_unreach(u_char type, u_char code,
            u_short orig_len, u_char orig_tos, u_short orig_id,
            u_short orig_frag, u_char orig_ttl, u_char orig_prot,
            u_long orig_src, u_long orig_dst, const u_char *orig_payload,
            int payload_s, u_char *buf);

int libnet_build_icmp_timeexceed(u_char type, u_char code,
            u_short orig_len, u_char orig_tos, u_short orig_id,
            u_short orig_frag, u_char orig_ttl, u_char orig_prot,
            u_long orig_src, u_long orig_dst, const u_char *orig_payload,
            int payload_s, u_char *buf);

int libnet_build_icmp_redirect(u_char type, u_char code, u_long gateway
            u_short orig_len, u_char orig_tos, u_short orig_id,
            u_short orig_frag, u_char orig_ttl, u_char orig_prot,
            u_long orig_src, u_long orig_dst, const u_char *orig_payload,
            int payload_s, u_char *buf);

int libnet_build_icmp_timestamp(u_char type, u_char code, u_short id,
            u_short seq, n_time otime, n_time rtime, n_time ttime,
            const u_char *payload, int payload_s, u_char *buf);

int libnet_build_igmp(u_char type, u_char code, u_long ip,
            const u_char *payload, int payload_s, u_char *buf);

int libnet_build_ip(u_short len, u_char tos, u_short id, u_short frag,
            u_char ttl, u_char prot, u_long saddr, u_long daddr,
            const u_char *payload, int payload_s, u_char *buf);

int libnet_build_ospf(u_short len, u_char type, u_long router_id,
            u_long area_id, u_short auth_type, const char *payload,
            int payload_s, u_char *buf);

int libnet_build_ospf_hello(u_long netmask, u_short interval,
            u_char options, u_char priority, u_int dead_interval,
            u_long des_router, u_long backup, u_long neighbor,
            const char *payload, int payload_s, u_char *buf);

int libnet_build_ospf_dbd(u_short len, u_char options, u_char type,
            u_int sequence_num, const char *payload, int payload_s,
            u_char *buf);

int libnet_build_ospf_lsr(u_int type, u_int ls_id, u_long adv_router,
            const char *payload, int payload_s, u_char *buf);

int libnet_build_ospf_lsu(u_int num, const char *payload, int payload_s,
            u_char *buf);

int libnet_build_ospf_lsa(u_short age, u_char options, u_char type,
            u_int ls_id, u_long adv_router, u_int sequence_num,
            u_short len, const char *payload, int payload_s,
            u_char *buf);

int libnet_build_ospf_lsa_rtr(u_short flags, u_short num, u_int id,
            u_int data, u_char type, u_char tos, u_short metric,
            const char *payload, int payload_s, u_char *buf);

int libnet_build_ospf_lsa_net(u_long netmask, u_int router_id,
            const char *payload, int payload_s, u_char *buf);

int libnet_build_ospf_lsa_sum(u_long netmask, u_int metric, u_int tos,
            const char *payload, int payload_s, u_char *buf);

int libnet_build_ospf_lsa_as(u_long netmask, u_int metric,
            u_long fwd_addr, u_int tag, const char *payload,
            int payload_s, u_char *buf);

int libnet_build_rip(u_char command, u_char ver, u_short rd, u_short af,
            u_short rt, u_long addr, u_long mask, u_long next_hop,
            u_long metric, const u_char *payload, int payload_s,
            u_char *buf);

int libnet_build_tcp(u_short sport, u_short dport, u_long seq,
            u_long ack, u_char control, u_short win, u_short urg,
            const u_char *payload, int payload_s, u_char *buf);

int libnet_build_udp(u_short sport, u_short dport,
            const u_char *payload, int payload_s, u_char *buf);

int libnet_build_vrrp(u_char vrouter_id, u_char priority,
            u_char ip_count, u_char auth_type, u_char advert_int,
            const u_char *payload, int payload_s, u_char *buf);

int libnet_insert_ipo(struct ipoption *opt, u_char opt_len, u_char *buf);

int libnet_insert_tcpo(struct tcpoption *opt, u_char opt_len,
            u_char *buf);

πŸ“ MISCELLANEOUS SUPPORT ROUTINES πŸ“

int libnet_seed_prand();

u_long libnet_get_prand(int type);

void libnet_hex_dump(u_char *buf, int len, int swap, FILE *stream);

int libnet_plist_chain_new(struct libnet_plist_chain **head,
            char *tok_list);

int libnet_plist_chain_next_pair(struct libnet_plist_chain *p,
            u_short *bport, u_short *eport);

int libnet_plist_chain_dump(struct libnet_plist_chain *p);

u_char *libnet_plist_chain_dump_string(struct libnet_plist_chain *p);

int libnet_plist_chain_free(struct libnet_plist_chain *p);

void libnet_error(int severity, char *msg, ...);

πŸ’œ ASN.1 BER ROUTINES πŸ’œ

u_char *libnet_build_asn1_int(u_char *data, int *datalen, u_char type,
            long *int_p, int int_s);

u_char *libnet_build_asn1_uint(u_char *data, int *datalen, u_char type,
            u_char *int_p, int int_s);

u_char *libnet_build_asn1_string(u_char *data, int *datalen, u_char type,
            u_long *string, int str_s);

u_char *libnet_build_asn1_header(u_char *data, int *datalen, u_char type,
            int len);

u_char *libnet_build_asn1_length(u_char *data, int *datalen, int len);

u_char *libnet_build_asn1_sequence(u_char *data, int *datalen,
            u_char type, int len);

u_char *libnet_build_asn1_objid(u_char *data, int *datalen, u_char type,
            oid *objid, int oid_s);

u_char *libnet_build_asn1_null(u_char *data, int *datalen, u_char type);

u_char *libnet_build_asn1_bitstring(u_char *data, int *datalen,
            u_char type, u_long *string, int str_s);

🌈 ADDRESS RESOLUTION ROUTINES 🌈

bestie this is the good section, the one where numbers become names and names become numbers ✨

  • libnet_host_lookup() β€” takes the network-ordered (big-endian) IPv4 address you handed it and turns it into its human-readable counterpart. if use_name is 1, libnet_host_lookup() will attempt to resolve that IP address and return a hostname; otherwise (or if the lookup just doesn't work out), the function returns a dotted-decimal ASCII string. heads up though: this function is hopelessly non re-entrant because it uses static data 😭 if re-entrancy is your whole personality, use libnet_host_lookup_r() instead.
  • libnet_host_lookup_r() β€” the (planned) reentrant version of the function above 🫢 as soon as reentrant network resolver libraries become available, this function will likewise be reentrant. you supply one extra argument: a buffer to store the converted (or resolved) IPv4 address. very "bring your own storage" of it.
  • libnet_name_resolve() β€” takes a NULL terminated ASCII string representation of an IPv4 address (dots and decimals, or a canonical hostname if use_name is 1) and converts it into a network-ordered (big-endian) 4-byte value. glow up: name β†’ bytes πŸ’…
  • libnet_get_ipaddr() β€” takes a pointer to a link layer interface struct, a pointer to the network device name, and an empty buffer to be used in case of error. upon success the function returns the IP address of the specified interface in host-byte order, or 0 upon error (and errbuf will contain a reason). so like, 0 means we're crying, and the buffer will tell you why 😭
  • libnet_get_hwaddr() β€” takes a pointer to a link layer interface struct, a pointer to the network device name, and an empty buffer to be used in case of error. the function returns the MAC address of the specified interface upon success, or 0 upon error (and errbuf will contain a reason). same energy, different address πŸŽ€

and that's part 1, bestie β€” the rest is literally right there, keep reading 🌸

🧚 PACKET MEMORY MANAGEMENT ROUTINES πŸ’–

Okay bestie, this is where you actually get your little memory sandbox to build packets in, so listen up πŸ’…

  • libnet_init_packet() β€” this one gets a packet all set up and ready to use. If you skip the size param (or pass something negative), the library is like "girl I got you" and picks a sensible value for you β€” rn that's LIBNET_MAX_PACKET. If the memory allocation actually works, the memory gets zeroed out and you get 1 back. If something goes wrong, you get -1. And lowkey important: since this calls malloc, you will need to call destroy_packet() at some point to match it, or you're just leaking memory like it's a vibe 🌸
  • libnet_destroy_packet() β€” frees the memory that was chillin' with the packet. Cleanup era, we love to see it ✨
  • libnet_init_packet_arena() β€” this allocates AND initializes a whole memory pool. If you're planning on building and sending several different packets, this is genuinely the move, no cap. It grabs a pool of memory that you can then scoop chunks out of to build packets (peep next_packet_from_arena() below πŸ‘€). It takes a pointer to an arena structure pointer (so it can actually modify the struct's elements), plus hints about the possible packet size and how many packets you want. Those last two args get used to compute how big the memory pool is. Returns -1 if malloc fails, or 1 if everything goes ok.
  • libnet_next_packet_from_arena() β€” hands you a chunk of memory from the arena at the size you requested, and decrements the available byte counter. If the arena doesn't have enough memory left for what you asked, you get NULL. Heads up though: nothing is stopping a sloppily-coded app from using more memory than it requested and causing all kinds of chaos. Take heed, fr fr πŸ’€
  • libnet_destroy_packet_arena() β€” frees the memory tied to the arena. Bye bestie 🫢

Okay so here's a lil detail that matters during packet or arena initialization and utilization: if you pass 0 for either of the size values, the functions make a best guess for you. Pass 0 for the packet size and it bumps it up to LIBNET_MAX_PACKET. Pass 0 for the packet number (in the case of libnet_init_packet_arena) and it bumps it up to 3. And just so you're aware β€” that's 196605 bytes of memory. Not a drill 🫣

Also, the number of bytes actually allocated might be a tiiiiny bit more than you asked for, because of alignment constraints (values are aligned on a 4-byte boundry). It's giving "close enough" energy πŸ’…

For the above three functions, it is a checked runtime error for arena to be a NULL pointer. Don't do it. Periodt.

The arena interface also comes with two lil icons: LIBNET_GET_ARENA_SIZE, which returns the total size of an arena, and LIBNET_GET_ARENA_REMAINING_BYTES, which returns the remaining bytes of usable memory from an arena. Very slay, very useful 🌈


πŸ”₯ PACKET INJECTION FRAMEWORK ROUTINES πŸ‘‘

This is the part where we actually get packets OUT there into the world. Main character energy only ✨

  • libnet_open_raw_sock() β€” opens a raw IPv4 socket of the protocol type you supply and sets the IP_HDRINCL socket option. You get back the socket file descriptor, or -1 on error. Simple as πŸŽ€
  • libnet_close_raw_sock() β€” closes an opened raw socket. Returns 1 on success or -1 on error.
  • libnet_select_device() β€” runs through the list of interfaces and picks one for you (ignoring the loopback device, it's not the moment). If device points to NULL, it'll try to fill it in with the first non-loopback device it finds β€” but girl, don't pass in a NULL pointer, the function expects a pointer to a pointer, and C cannot derefence a NULL pointer 😭. Otherwise, it'll try to open the device you specified. If it works, you get 1 back (and if device was NULL, it now holds the device name, which you can use in libnet_*link*() type calls). If something goes wrong, you get -1 and errbuf will contain the reason. Also, errbuf should point to a buffer that's at least as large as LIBNET_ERR_BUF πŸ’œ
  • libnet_open_link_interface() β€” opens a low-level packet interface. This one is required if you wanna write link layer frames. You supply a u_char pointer to the interface device name and a u_char pointer to an error buffer. You get back a filled-in libnet_link_int struct, or NULL on error πŸ¦‹
  • libnet_close_link_interface() β€” closes an opened low-level packet interface. Returns 1 on success or -1 on error.
  • libnet_write_ip() β€” writes an IP packet to the network. First arg is the socket you made with libnet_open_raw_sock(), second is a pointer to a buffer holding a complete IP datagram, and third is the total packet size. Returns the number of bytes written.
  • libnet_write_link_layer() β€” writes a link-layer frame to the network. First arg is a pointer to a filled-in libnet_link_int structure, next is a pointer to the network device, next is the raw packet, and last is the packet size. Returns the number of bytes written, or -1 on error.
  • libnet_do_checksum() β€” calculates the checksum for the packet header. First arg is a pointer to the constructed IPv4 packet buffer, second is the transport protocol used, and third is the packet length (not including the IP header). The function calculates the checksum for the transport protocol and fills it in at the appropriate header location. Only call this after a complete packet has been built, bestie β€” order matters πŸ’…
Ngl here's a spicy little detail: when you're using raw sockets, the IP checksum is always computed by the kernel for you. But when you're using link layer interfaces, you have to explicitly compute the IP checksum yourself. No free rides there, sorry 😭

The function returns 1 upon success, or -1 if an error occurs. Iconic behavior ⭐

πŸ› οΈ PACKET BUILDER ROUTINES πŸ› οΈ

okay so this is the part where you actually make packets, and it's giving main character energy fr. But first, bestie, we gotta talk about the rules of the road, because there are two very different kinds of "oops" here.

For all of the build_* functions: if buf is a NULL pointer, that's a checked runtime error and the function will just return -1 like "nope, not today." But if the optional payload or the packet header itself blows past the allocated memory? That's an unchecked error. Meaning nobody's gonna catch you. Meaning you're on your own. Take heed. πŸ’€


πŸ¦‹ libnet_build_arp()

constructs an ARP (Address Resolution Protocol) packet. You hand it all of this:

  • the hardware address type
  • the protocol address type
  • the hardware address length
  • the protocol address length
  • the ARP packet type
  • the sender hardware address
  • the sender protocol address
  • the target hardware address
  • the target protocol address
  • the packet payload
  • the payload size
  • and finally, a pointer to the packet header memory

Lowkey important: this function only builds ethernet/IP ARP packets, so that first value should be ARPHRD_ETHER, no cap.

And the ARP packet type? Gotta be one of these icons:

  • ARPOP_REQUEST
  • ARPOP_REPLY
  • ARPOP_REVREQUEST
  • ARPOP_REVREPLY
  • ARPOP_INVREQUEST
  • ARPOP_INVREPLY

🌸 libnet_build_dns()

constructs a DNS (Domain Name Service) packet. Supplied are:

  • the DNS packet ID
  • flags
  • number of questions
  • number of answer resource records
  • number of authority resource records
  • number of additional resource records

All of the above are unsigned shorts, bestie. πŸ’…

Now here's the tea: all the interesting fields of the header are variable in content and length, so it's fully up to you, the programmer, to include them at your discretion. We use the standard libnet payload and payload size interface for this. And finally β€” please, please β€” be sure to include a pointer to some preallocated memory. πŸ™ˆ


πŸŽ€ libnet_build_ethernet()

constructs an ethernet packet. Supplied is:

  • the destination address
  • the source address (as arrays of unsigned character bytes)
  • the ethernet frame type
  • a pointer to an optional data payload
  • the payload length
  • a pointer to a pre-allocated block of memory for the packet

The ethernet packet type should be one of these:

  • ETHERTYPE_PUP β€” PUP protocol
  • ETHERTYPE_IP β€” IP protocol
  • ETHERTYPE_ARP β€” ARP protocol
  • ETHERTYPE_REVARP β€” Reverse ARP protocol
  • ETHERTYPE_VLAN β€” IEEE VLAN tagging
  • ETHERTYPE_LOOPBACK β€” Used to test intefaces
⚠️ heads up: some low-level interfaces (bpf in particular) do not allow for the spoofing of ethernet addresses without kernel modification. so don't come crying to me when it doesn't work, i warned you. 😭

🧚 ICMP time, babes 🧚

The following functions construct ICMP (Internet Control Message Protocol) packets.

libnet_build_icmp_echo()

builds an ICMP_ECHO / ICMP_ECHOREPLY packet. Supplied is:

  • a byte for the packet type
  • a byte for the code
  • an unsigned short for the packet id
  • an unsigned short for the packet sequence number
  • a pointer to an optional data payload
  • the payload length
  • a pointer to a pre-allocated block of memory for the packet

The type should be ICMP_ECHOREPLY or ICMP_ECHO, and the code should be 0. periodt.

libnet_build_icmp_mask()

builds an ICMP_MASKREQ / ICMP_MASKREPLY packet. Supplied is:

  • a byte for the packet type
  • a byte for the code
  • an unsigned short for the packet id
  • an unsigned short for the packet sequence number
  • a 32-bit subnet mask
  • a pointer to an optional data payload
  • the payload length
  • a pointer to a pre-allocated block of memory for the packet

The type should be ICMP_MASKREQ or ICMP_MASKREPLY, and the code should be 0. ✨

libnet_build_icmp_unreach()

builds an ICMP_UNREACH packet. Supplied is the normal ICMP stuff β€” a byte for the packet type and a byte for the code. Then next come the values for the IP header that caused the error that necessitated the unreachable. The standard payload arguments to this function actually apply to the original IP packet and will be tacked on there. πŸ‘‘

The type should be ICMP_UNREACH, and the code should be one of these 16 different unreachable codes:

  • 0 β€” ICMP_UNREACH_NET
  • 1 β€” ICMP_UNREACH_HOST
  • 2 β€” ICMP_UNREACH_PROTOCOL
  • 3 β€” ICMP_UNREACH_PORT
  • 4 β€” ICMP_UNREACH_NEEDFRAG
  • 5 β€” ICMP_UNREACH_SRCFAIL
  • 6 β€” ICMP_UNREACH_NET_UNKNOWN
  • 7 β€” ICMP_UNREACH_HOST_UNKNOWN
  • 8 β€” ICMP_UNREACH_ISOLATED
  • 9 β€” ICMP_UNREACH_NET_PROHIB
  • 10 β€” ICMP_UNREACH_HOST_PROHIB
  • 11 β€” ICMP_UNREACH_TOSNET
  • 12 β€” ICMP_UNREACH_TOSHOST
  • 13 β€” ICMP_UNREACH_FILTER_PROHIB
  • 14 β€” ICMP_UNREACH_HOST_PRECEDENCE
  • 15 β€” ICMP_UNREACH_PRECEDENCE_CUTOFF

libnet_build_icmp_timeexceed()

builds an ICMP_TIMEXCEED packet. Supplied is the normal ICMP stuff β€” a byte for the packet type and a byte for the code. Then next come the values for the IP header that caused the error that necessitated the unreachable. The standard payload arguments to this function actually apply to the original IP packet and will be tacked on there.

The type should be ICMP_REDIRECT and the code should be ICMP_TIMXCEED_INTRANS or ICMP_TIMXCEED_REASS.

πŸ’€ yeah bestie that's what it says, i'm just the messenger

libnet_build_icmp_redirect()

builds an ICMP_REDIRECT packet. Supplied is:

  • a byte for the packet type
  • a byte for the code
  • the unsigned long IP address of the gateway that should be used

Then next come the values for the IP header that caused the error that necessitated the redirect. The standard payload arguments to this function actually apply to the original IP packet and will be tacked on there.

The type should be ICMP_REDIRECT, and the code should be one of these:

  • 0 β€” ICMP_UNREACH_NET
  • 1 β€” ICMP_UNREACH_HOST
  • 2 β€” ICMP_UNREACH_PROTOCOL (redirect for type of service and network)
  • 3 β€” ICMP_UNREACH_PORT (redirect for type of service and host)

libnet_build_icmp_timestamp()

builds an ICMP_TSTAMP / ICMP_TSTAMPREPLY packet. Supplied is:

  • a byte for the packet type
  • a byte for the code
  • an unsigned short for the packet id
  • an unsigned short for the packet sequence number
  • the three timestamp values
  • a pointer to an optional data payload
  • the payload length
  • a pointer to a pre-allocated block of memory for the packet

The type should be ICMP_TSTAMP or ICMP_TSTAMPREPLY, and the code should be 0. 🫢


🌈 libnet_build_igmp()

builds an IGMP (Internet Group Membership Protocol) packet. Supplied is:

  • a byte for the packet type
  • a byte for the code
  • an unsigned long for the Class D address
  • and the other usual things

πŸ‘‘ libnet_build_ip()

builds an IP (Internet Protocol) packet. Supplied is:

  • the packet length (not including the IP header)
  • the IP tos bits
  • the IP ID
  • the fragmentation flags and offset
  • the packet TTL
  • the transport protocol
  • the source and destination IP addresses (in network-byte order)
  • a pointer to an optional data payload
  • the payload length
  • a pointer to a pre-allocated block of memory for the packet

If you just wanna build an IP header with no data payload, only IP_H bytes need to be allocated. easy. ✨

But listen closely, bestie: the payload and payload size arguments should not be used to build any of the supported transport protocol-type packets. For those transports, you use the relevant functions instead, okay? The payload arguments should only be used to build an arbitrary IP packet with a payload. that's the vibe check. πŸ’…

πŸ’– OSPF PACKET CREATION ROUTINES πŸ’–

okay bestie, buckle up, we're doing OSPF now and it's giving a lot of letters but it's literally fine, i promise πŸ¦‹

libnet_build_ospf() builds an OSPF (Open Shortest Path First) packet. here's what you hand over: the packet length (not including the OSPF header), the packet type, a 32-bit router ID, a 32-bit area ID, the authentication type, a pointer to an optional data payload, the payload length, and a pointer to a pre-allocated block of memory for the packet. πŸ’…

heads up: that payload should not be used to build the Hello, LSA, LSU, LSR, or DBD packets. like, don't. πŸ™ˆ

these are the variables for the OSPF packet type:

  • OSPF_UMD β€” UMd monitoring packet
  • OSPF_HELLO β€” Hello packet
  • OSPF_DBD β€” Database Desc. packet
  • OSPF_LSR β€” Link State Request packet
  • OSPF_LSU β€” Link State Update packet
  • OSPF_LSA β€” Link State Ack. packet

and these are the possible authentication types:

  • OSPF_AUTH_NULL β€” NULL password
  • OSPF_AUTH_SIMPLE β€” plaintext, 8 char pass.
  • OSPF_AUTH_MD5 β€” MD5

and this right here is the structure used for the 64 bit field when you're using MD5:

struct auth {
    u_short ospf_auth_null;  /* NULL 16 bits */
    u_char ospf_auth_keyid;  /* Key ID */
    u_char ospf_auth_len;    /* Auth data len */
    u_int ospf_auth_seq;     /* Sequence num */
};

libnet_build_ospf_hello() builds an OSPF Hello packet ✨ you pass the netmask for the interface, the number of seconds since the last packet was sent, possible options, the router's priority (if it's 0, it can't be a backup router, soz), the time (in seconds) until a router is deemed down, the networks designated router, the networks backup router, a neighbor, a pointer to an optional data payload, the payload length, and a pointer to a pre-allocated block of memory used for the packet.

if there's more than one neighbor that needs to be in the packet? just allocate enough space for the packet buf and pass the neighbors as the "optional data payload." easy πŸŽ€


libnet_build_ospf_dbd() builds an OSPF DataBase Description (DBD) packet. you pass the maximum length of an IP packet the interface can use, packet options, the type of exchange occuring, a sequence number, a pointer to an optional data payload, the payload length, and a pointer to a pre-allocated block of memory for the packet. the following can be used for the type variable:

  • DBD_IBIT β€” Init bit
  • DBD_MBIT β€” More DBD packets to come
  • DBD_MSBIT β€” sender is the master

libnet_build_ospf_lsr() builds an OSPF Link State Request (LSR) packet. you pass the type of link state packet being requested, the link state ID, the advertising router, a pointer to an optional data payload, the payload length, and a pointer to a pre-allocated block of memory for the packet. πŸ“¨

for more info about the variables, go peek at the libnet_build_ospf_lsa() section, bestie.

libnet_build_ospf_lsu() builds an OSPF Link State Update (LSU) packet. you pass the number of Link State Acknowledgment (LSA) packets that will be in the packet, a pointer to an optional data payload, the payload length, and a pointer to a pre-allocated block of memory for the packet. πŸ”₯


libnet_build_ospf_lsa() builds an OSPF Link State Acknowledgement (LSA) packet. you pass the link state age, packet options, type of LSA, the link state ID, the advertising router, the packet's sequence number, the length of the packet (_not_ including the LSA header length β€” read that twice, i'm serious 😭), a pointer to an optional data payload, the payload length, and a pointer to a pre-allocated block of memory for the packet.

the following variables can be used for the type of LSA:

  • LS_TYPE_RTR β€” Router LSA
  • LS_TYPE_NET β€” Network LSA
  • LS_TYPE_IP β€” Summary LSA (IP Network)
  • LS_TYPE_ASBR β€” Summary LSA (ASBR)
  • LS_TYPE_ASEXT β€” AS-External LSA

libnet_build_ospf_lsa_rtr() builds an OSPF Link State Router packet. you pass the optional packet flags, the number of links within that packet, the link ID (it helps describe the next variable, okay it's a team effort), the info for the specified link ID, the type of router link, the number of TOS metrics for this link, the metric (the cost of using the link), a pointer to an optional data payload, the payload length, and a pointer to a pre-allocated block of memory for the packet. πŸ’œ

the possible flags (not including 0x00, ok) are as follows:

  • RTR_FLAGS_W β€” W bit
  • RTR_FLAGS_E β€” E bit
  • RTR_FLAGS_B β€” B bit

the possible link ID's are as follows:

  • LINK_ID_NBR_ID β€” Neighbors router ID
  • LINK_ID_IP_DES β€” IP addr of router
  • LINK_ID_SUB β€” IP subnet number

the possible values for the router type are as follows:

  • RTR_TYPE_PTP β€” Point-to-point
  • RTR_TYPE_TRANS β€” Connection to a "transit network"
  • RTR_TYPE_STUB β€” Connection to a "stub network"
  • RTR_TYPE_VRTL β€” Connection to a "virtual link"

libnet_build_ospf_lsa_net() builds an OSPF Link Sate Network packet. you pass the interface's netmask, the router ID, a pointer to an optional data payload, the payload length, and a pointer to a pre-allocated block of memory for the packet. 🌸


libnet_build_ospf_lsa_sum() builds an OSPF Link State Summary packet. you pass the interface's netmask, the cost of using the link (metric), the TOS and metric β€” which is passed as a unsigned integer but the first 8 bits are the TOS and the last 24 bits are the TOS metric (yeah it's a little packed in there, she's efficient πŸ’…) β€” a pointer to an optional data payload, the payload length, and a pointer to a pre-allocated block of memory for the packet.


libnet_buils_ospf_lsa_as() builds an OSPF Link State AS External packet. you pass the interface's netmask, the cost of using the link (metric), the forwarding address, the external route tag, a pointer to an optional data payload, the payload length, and a pointer to a pre-allocated block of memory for the packet.

in reality, the metric only uses the last 24 bits of the unsigned int. the first 8 bits are reserved for a possible bit to be set (the E bit, see above for more info, i got you 🫢). the variable AS_E_BIT_ON can be used logically to set the E bit on.


✨ OSPF MACROS ✨

LIBNET_OSPF_AUTHCPY() simply copies, byte for byte, your authentication buf to the pre-allocated block of memory for your packet. that's it. that's the macro. iconic for being simple πŸ’–


🧚 OSPF FUNCTION VARIABLES 🧚

random variables, just vibing:

  • IPPROTO_OSPF β€” 89
  • OSPFVERSION β€” 2

header lengths, the whole lineup:

  • OSPF_H β€” OSPF header
  • HELLO_H β€” Hello header
  • DBD_H β€” DBD header
  • LSR_H β€” LSR header
  • LSU_H β€” LSU header
  • LSA_H β€” LSA header
  • LS_RTR_LEN β€” LS-Router header
  • LS_NET_LEN β€” LS-Network header
  • LS_SUM_LEN β€” LS-Summary header
  • LS_AS_EXT_LEN β€” LS-AS External header

packet options, pick your fighter:

  • OPT_EBIT β€” AS-external-LSAs are flooded
  • OPT_MCBIT β€” IP multicast dgrams are forwarded
  • OPT_NPBIT β€” Handles type-7 LSAs
  • OPT_EABIT β€” Sends/recv's AS-external LSAs
  • OPT_DCBIT β€” Handles demand circuits

libnet_build_rip() constructs a RIP (Routing Information Protocol) packet. the values you supply depend on which version of the RIP packet you're trying to build, so here's the whole breakdown 🌈

  1. first β€” byte β€” RIP v1: command, RIPv2: command
  2. second β€” byte β€” RIP v1: version, RIPv2: version
  3. third β€” ushort β€” RIP v1: zero, RIPv2: routing domain
  4. fourth β€” ushort β€” RIP v1: address family, RIPv2: address family
  5. fifth β€” ushort β€” RIP v1: zero, RIPv2: route tag
  6. sixth β€” ulong β€” RIP v1: IP address, RIPv2: IP address
  7. seventh β€” ulong β€” RIP v1: zero, RIPv2: subnet mask
  8. eighth β€” ulong β€” RIP v1: zero, RIPv2: next hop IP
  9. ninth β€” ulong β€” RIP v1: metric, RIPv2: metric
  10. tenth β€” const u_char * β€” Packet payload
  11. eleventh β€” int β€” Packet payload size
  12. twelfth β€” u_char * β€” Packet header memory

the command should be one of the following: RIPCMD_REQUEST, RIPCMD_RESPONSE, RIPCMD_TRACEON, RIPCMD_TRACEOFF, RIPCMD_POLL, RIPCMD_POLLENTRY, or RIPCMD_MAX. and the version should be RIPVER_1 or RIPVER_2. no cap. πŸ’―


libnet_build_tcp() builds a TCP (Transmission Control Protocol) packet. supplied is the source port, destination port, the sequence and acknowledgement numbers, the control bits (which can be logically OR'd together to set multiple flags β€” see the example below, bestie), the advertised window size, the urgent pointer, a pointer to an optional data payload, the payload size, and lastly, the pointer to a pre-allocated block of memory for the packet.

to just build a TCP header with no data payload, only TCP_H bytes need be allocated. minimal queen behavior πŸ‘‘

libnet_build_udp() builds a UDP (User Datagram Protocol) packet. supplied is the source port, the destination port, a pointer to an optional data payload, the payload size, and lastly, a pointer to a pre-allocated block of memory for the packet.

to just build a UDP header with no data payload, only UDP_H bytes need to be allocated. πŸ“

libnet_vuild_vrrp() builds a VRRP (Virtual Router Redundancy Protocol) packet. supplied is the virtual router ID, the priority, the number of IP addresses in the packet, the authorization type (LIBNET_VRRP_AUTH_NONE, LIBNET_VRRP_AUTH_PASSWD, or LIBNET_VRRP_AUTH_IPAH), the adverstisment interval, a pointer to an optional data payload, the payload size, and lastly, a pointer to a pre-allocated block of memory for the packet. πŸ’«


libnet_insert_ipo() inserts IP options into an already created IP packet. supplied is a pointer to an ip option struct (which must be filled in by the user, no shortcuts), the size of the options list, and a pointer the completed packet.

the function returns -1 if the options would make the packet too large (greater then 65535 bytes) or 1 otherwise.

⚠️ it is an unchecked runtime error for the user to have not allocated enough heap memory for the packet + options. like, that's on you and it will not be caught for you. allocate properly fr fr 😭

libnet_insert_tcpo() inserts TCP options into an already created IP packet. replace the pointer to an IP option struct with one to a TCP option struct and this function is exactly the same as above. copy-paste energy but make it TCP πŸ’…

🌸 MISCELLANEOUS SUPPORT ROUTINES 🌸

okay bestie, this is the grab-bag section and honestly? it's giving utility belt πŸ’… every lil helper that didn't fit anywhere else lives here, and they're all lowkey iconic.

  • libnet_seed_prand() β€” seeds the psuedorandom number generator. returns 1 on success, -1 on failure.
  • libnet_get_prand() β€” hands you back a positive psuedorandom integer of the specified type. it expects type to be one of five symbolics: PR2, PR8, PR16, PRu16, PR32 or PRu32. here's the tea on each one πŸ“
    • PR2 returns a one or a zero
    • PR8 returns a byte
    • PR16 returns up to a signed short (from 0 to 32767)
    • PRu16 returns an unsigned short (from 0 to 65535)
    • PR32 returns a signed long (from 0 to 2147483647)
    • PRu32 returns an unsigned long number (from 0 to 4294967295)
  • libnet_hex_dump() β€” prints a packet out in hex. supplied is the packet and its length, a swap flag, and a pointer to a previously opened stream. the swap flag (1 or 0) specifies whether or not to print the packet as it appears in memory (0) or to swap the bytes into host order (1). yes, that's the whole vibe.
  • libnet_plist_chain_new() β€” builds a new libnet port list chain.

a libnet port list chain is a fast and simple way of implementing port list ranges (useful for applications that employ a list of ports like a port scanner). you'll see naive implementations that allocate an entire array of 65535 bytes and fill in the desired ports one by one. however, we only really need to store the beginning port and the ending port, and we can efficiently store multiple port ranges (delimated by commas) by using a linked list chain with each node holding the beginning and ending port for a particular range.

for example, the port range 1-1024 would occupy one node with the bport being 1 and the eport being 1024. the port range 25,110-161,6000 would result in 3 nodes being allocated. single ports are taken as single ranges (port 25 ends up being 25-25). a port list range without a terminating port (port_num - ) is considered shorthand for (port_num - 65535).

the arguments are a pointer to libnet_plist_chain pointer (which will end up being the head of the linked list) and pointer to the port list itself. the function checks this character port list for valid tokens (1234567890,- ) and returns an error if an unrecognized token is found. upon success the function returns 1, and head points to the newly formed port list (and also contains the number of nodes in the list). if an error occurs (an unrecognized token is found or malloc fails) -1 is returned and head is set to NULL. libnet_plist_chain_next_pair() should be used to extract port list pairs.

  • libnet_plist_chain_next_pair() β€” fetchs the next pair of ports from the list. the function takes a pointer to the head of the prebuilt list and a pointer to a u_short that will contain the beginning port and a pointer to a u_short that will contain the ending port. the function returns 1 and fills in these values if there are nodes remaining, or if the port list chain is exhausted, it returns 0.
  • libnet_plist_chain_dump() β€” prints the list (as lists of integers).
  • libnet_plist_chain_dump_string() β€” returns a string containing the port list chain.
  • libnet_plist_chain_free() β€” frees the entire list. 🫢
  • libnet_error() β€” dumps an error message to stderr. included is the severity of the message (LIBNET_ERR_WARNING, LIBNET_ERR_CRITICAL, or LIBNET_ERR_FATAL) and the message string itself. if the severity is LIBNET_ERR_FATAL, the function will exit the program. this is the only defined exit point in the whole library. πŸ”₯

πŸ¦‹ ASN.1 BER ROUTINES πŸ¦‹

okay so this section is literally just a roll call β€” no descriptions, just the lineup. respect the mystery. πŸ’…

  • libnet_build_asn1_int()
  • libnet_build_asn1_uint()
  • libnet_build_asn1_string()
  • libnet_build_asn1_header()
  • libnet_build_asn1_length()
  • libnet_build_asn1_sequence()
  • libnet_build_asn1_objid()
  • libnet_build_asn1_null()
  • libnet_build_asn1_bitstring()

πŸ’œ SYMBOLIC CONSTANTS πŸ’œ

to make your life and code cleaner, libnet defines symbolic constants to make your life easier. (yes bestie, the manpage really said it twice, and honestly? it ate. πŸ‘‘)

Default packet header sizes πŸŽ€

  • LIBNET_ARP_H β€” ARP
  • LIBNET_DNS_H β€” DNS
  • LIBNET_ETH_H β€” ethernet
  • LIBNET_ICMP_H β€” ICMP header (base)
  • LIBNET_ICMP_ECHO_H β€” ICMP_ECHO / ICMP_ECHOREPLY
  • LIBNET_ICMP_MASK_H β€” ICMP_MASKREQ / ICMP_MASKREPLY
  • LIBNET_ICMP_UNREACH_H β€” ICMP_UNREACHABLE (base)
  • LIBNET_ICMP_REDIRECT_H β€” ICMP_REDIRECT (base)
  • LIBNET_ICMP_TS_H β€” ICMP_TSTAMP (base)
  • LIBNET_ICMP_TIMXCEED_H β€” ICMP_TIMXCEED (base)
  • LIBNET_IGMP_H β€” IGMP
  • LIBNET_IP_H β€” IP
  • LIBNET_RIP_H β€” RIP
  • LIBNET_TCP_H β€” TCP
  • LIBNET_UDP_H β€” UDP
  • LIBNET_VRRP_H β€” VRRP (base)

Standard memory sizes for packets 🧁

  • LIBNET_PACKET β€” Standard packet size (IP_H + TCP_H)
  • LIBNET_OPTS β€” Maximum IP options list
  • LIBNET_MAX_PACKET β€” Maximum IPv4 packet size

Other constants you should know about ⭐

IP Type Of Service constants

  • IPTOS_LOWDELAY β€” Minimize delay
  • IPTOS_THROUGHPUT β€” Maximize throughput
  • IPTOS_RELIABILITY β€” Maximize reliability
  • IPTOS_MINCOST β€” Minimize monetary cost

IP Fragmentation flags

  • IP_DF β€” Don't fragment this datagram
  • IP_MF β€” More fragments en route

TCP control bits

  • TH_URG β€” Urgent flag
  • TH_ACK β€” Acknowledgement field valid
  • TH_PUSH β€” Push this data to application layer
  • TH_RST β€” Reset the referenced connection
  • TH_SYN β€” Synchronize connection state
  • TH_FIN β€” Finished sending data

🧚 COMPLIATION USING THE CONFIGURE SCRIPT 🧚

(keeping the original heading spelling, bestie β€” that's canon πŸ’€)

to properly compile your applications under libnet, you should use the libnet-config script. this script is created during the GNU configure process will ensure that future compilations linked against libnet contain the correct CPP and CFLAG options as well as additional libraries for the targeted architecture. to invoke it simply:

gcc `libnet-config --defines --cflags` foo.c -o foo `libnet-config --libs`

the script handles all libnet dependencies and concessions for the architecture it was compiled on. no cap. ✨


πŸ‘€ SEE ALSO πŸ‘€


πŸ’– AUTHOR πŸ’–

Mike D. Schiffman <mike@infonexus.com> β€” see the online web reference manual for additional contributers.

the current version is always available:

http://www.packetfactory.net/libnet


😭 BUGS 😭

bestie, listen. these are the known Ls. read them, love them, plan around them. πŸ™ˆ
  • Solaris raw sockets are cooked. they do not allow one to set the ip_len, ip_frag or the ip_id (including IP options at the raw socket layer doesn't work either). to work around this, use the link-layer API instead of raw socket functions.
  • The Berkeley Packet Filter alone does not allow for the arbitrary specification of source ethernet addresses. this is not so much a bug as an oversight in the protocol. included with the distribution is lkm code to work around this (FreeBSD has support for an ioctl that works around this).
  • The OSPF functionality has not been extensively tested as yet and is considered to be in beta release. 🫠
  • Please send bug reports to mike@infonexus.com.

and that's a wrap on the whole page, bestie 🫢 this was libnet 1.0.2, dated 01 17 2001 β€” go forth, build packets, and slay πŸ’…βœ¨πŸŒΈ

πŸ“¦ where this page comes from