Every self-respecting Linux guru should be familiar with firewalls and how to install and configure them. With this in mind, Linux gurus also should be curious about how firewalls function and how to build a firewall of his or her own. Explaining exactly these two things is the goal of this article. Here, we attempt to write a firewall in less than 60 lines of C code. As impossible as this may sound, it actually is quite simple to do using the power of Linux kernel modules and Netfilter. Netfilter is a packet filtering subsystem in the Linux kernel stack and has been there since kernel 2.4.x. Netfilter's core consists of five hook functions declared in linux/netfilter_ipv4.h. Although these functions are for IPv4, they aren't much different from those used in the IPv6 counterpart. The hooks are used to analyze packets in various locations on the network stack. This situation is depicted below: [INPUT]--->[1]--->[ROUTE]--->[3]--->[4]--->[OUTPUT] | ^ | | | [ROUTE] v | [2] [5] | ^ | | v | [INPUT*] [OUTPUT*] [1] NF_IP_PRE_ROUTING [2] NF_IP_LOCAL_IN [3] NF_IP_FORWARD [4] NF_IP_POST_ROUTING [5] NF_IP_LOCAL_OUT [*] Network Stack NF_IP_PRE_ROUTING is called right after the packet has been received. This is the hook we are most interested in for our micro-firewall. NF_IP_LOCAL_IN is used for packets that are destined for the network stack and thus has not been forwarded. NF_IP_FORWARD is for packets not addressed to us but that should be forwarded. NF_IP_POST_ROUTING is for packets that have been routed and are ready to leave, and NF_IP_LOCAL_OUT is for packets sent out from our own network stack. Each function has a chance to mangle or do what it wishes with the packets, but it eventually has to return a Netfilter code. Here are the codes that can be returned and what they mean: NF_ACCEPT: accept the packet (continue network stack trip) NF_DROP: drop the packet (don't continue trip) NF_REPEAT: repeat the hook function NF_STOLEN: hook steals the packet (don't continue trip) NF_QUEUE: queue the packet to userspace