### Install Netfilter Development Components Source: https://www.netfilter.org/documentation/FAQ/netfilter-faq-4.html Command to build and install the necessary development components for working with libipq. ```bash make install-devel ``` -------------------------------- ### Patch-O-Matic HOPLIMIT Example Source: https://www.netfilter.org/documentation/HOWTO/netfilter-extensions-HOWTO-2.html Example of using the HOPLIMIT patch to manipulate IPv6 Hop Limit values. This demonstrates setting, incrementing, and decrementing the hop limit for different traffic directions. ```bash # ip6tables -t mangle -A OUTPUT -j HOPLIMIT --hl-inc 1 # ip6tables -t mangle -A INPUT -j HOPLIMIT --hl-eq 64 # ip6tables -t mangle -A OUTPUT -j HOPLIMIT --hl-dec 2 ``` -------------------------------- ### Configure eui64 match Source: https://www.netfilter.org/documentation/HOWTO/netfilter-extensions-HOWTO-6.html Example of redirecting packets based on EUI-64 addressing parameters. ```bash # ip6tables -N ipv6ok # ip6tables -A INPUT -m eui64 -j ipv6ok # ip6tables -A INPUT -s ! 3FFE:2F00:A0::/64 -j ipv6ok # ip6tables -A INPUT -j LOG # ip6tables -A ipv6ok -j ACCEPT # ip6tables --list Chain INPUT (policy ACCEPT) target prot opt source destination ipv6ok all anywhere anywhere eui64 ipv6ok all !3ffe:2f00:a0::/64 anywhere LOG all anywhere anywhere LOG level warning Chain ipv6ok (2 references) target prot opt source destination ACCEPT all anywhere anywhere ``` -------------------------------- ### Get help for a protocol extension Source: https://www.netfilter.org/documentation/HOWTO/packet-filtering-HOWTO-7.html Use the -h or --help flag after specifying a protocol or module to view available options. ```bash # iptables -p tcp --help # ``` -------------------------------- ### Configure ipv6header match Source: https://www.netfilter.org/documentation/HOWTO/netfilter-extensions-HOWTO-6.html Example of filtering packets based on the presence of specific extension headers. ```bash # ip6tables -A INPUT -m ipv6header --header hop-by-hop,ipv6-route,protocol -j DROP ``` -------------------------------- ### Compile and Install iptables Source: https://www.netfilter.org/documentation/HOWTO/netfilter-extensions-HOWTO-2.html Run these commands from the 'iptables/' directory after applying patches and recompiling the kernel. Ensure your kernel is configured with the necessary Netfilter options. ```bash # make && make install ``` -------------------------------- ### Linux 2.2 ipmasqadm Port Forwarding Example Source: https://www.netfilter.org/documentation/HOWTO/NAT-HOWTO-4.html This is an example of how to configure TCP port forwarding using the older `ipmasqadm` tool on Linux kernel 2.2. It forwards incoming TCP traffic on port 8080 of a specific IP to a different IP and port on the internal network. ```bash # Linux 2.2 # Forward TCP packets going to port 8080 on 1.2.3.4 to 192.168.1.1's port 80 ipmasqadm portfw -a -P tcp -L 1.2.3.4 8080 -R 192.168.1.1 80 ``` -------------------------------- ### Get Help on TCP Extension Source: https://www.netfilter.org/documentation/HOWTO/packet-filtering-HOWTO.txt To understand the available options for the TCP protocol extension, use the `-p tcp --help` command. This loads the extension and displays its specific help information. ```bash # iptables -p tcp --help ``` -------------------------------- ### Checkout Netfilter SVN Repositories Source: https://www.netfilter.org/documentation/HOWTO/netfilter-extensions-HOWTO-2.html Use SVN to checkout the latest iptables package and the patch-o-matic-ng repository. Ensure you have the necessary SVN client installed. ```bash # mkdir netfilter_svn # cd netfilter_svn # svn co https://svn.netfilter.org/netfilter/trunk/iptables # svn co https://svn.netfilter.org/netfilter/trunk/patch-o-matic-ng ``` -------------------------------- ### Implement print function for iptables match Source: https://www.netfilter.org/documentation/HOWTO/netfilter-extensions-HOWTO-3.html Example of an empty print function for an iptables match module. ```c /* Prints out the union ipt_matchinfo. */ static void print(const struct ipt_ip *ip, const struct ipt_entry_match *match, int numeric) { } ``` -------------------------------- ### Linux 2.4 iptables Port Forwarding Example Source: https://www.netfilter.org/documentation/HOWTO/NAT-HOWTO-4.html This snippet demonstrates how to achieve the same port forwarding functionality as the `ipmasqadm` example but using the `iptables` command on Linux kernel 2.4. It configures destination NAT (DNAT) for TCP packets. ```bash # Linux 2.4 # Append a rule before routing (-A PREROUTING) to the NAT table (-t nat) that # TCP packets (-p tcp) going to 1.2.3.4 (-d 1.2.3.4) port 8080 (--dport 8080) # have their destination mapped (-j DNAT) to 192.168.1.1, port 80 # (--to 192.168.1.1:80). iptables -A PREROUTING -t nat -p tcp -d 1.2.3.4 --dport 8080 \ -j DNAT --to 192.168.1.1:80 ``` -------------------------------- ### iptables actions for u32 matches Source: https://www.netfilter.org/documentation/HOWTO/netfilter-extensions-HOWTO.sgml Examples of actions that can be appended to u32 matches, such as logging or dropping packets. ```bash -j LOG --log-prefix "ID-in-2-256 " ``` ```bash -j DROP ``` -------------------------------- ### iptables TTL Match Example Source: https://www.netfilter.org/documentation/HOWTO/netfilter-extensions-HOWTO.sgml This example logs packets with a TTL less than 5. The --ttl-lt option specifies 'less than'. ```bash # iptables -A INPUT -m ttl --ttl-lt 5 -j LOG ``` -------------------------------- ### Configure frag match Source: https://www.netfilter.org/documentation/HOWTO/netfilter-extensions-HOWTO-6.html Example of filtering packets based on fragmentation header ID and fragment status. ```bash # ip6tables -A INPUT -m frag --fragid 100:200 --fragfirst -j DROP # ip6tables --list Chain INPUT (policy ACCEPT) target prot opt source destination DROP all anywhere anywhere frag ids:100:200 first ``` -------------------------------- ### iptables Time Match Configuration Source: https://www.netfilter.org/documentation/HOWTO/netfilter-extensions-HOWTO.sgml This example accepts packets only during specific hours on weekdays. Ensure the --days argument uses the correct case-sensitive abbreviations. ```bash # iptables -A INPUT -m time --timestart 8:00 --timestop 18:00 --days Mon,Tue,Wed,Thu,Fri -j ACCEPT # iptables --list Chain INPUT (policy ACCEPT) target prot opt source destination ACCEPT all -- anywhere anywhere TIME from 8:00 to 18:00 on Mon,Tue,Wed,Thu,Fri ``` -------------------------------- ### Configure ah and esp header matches Source: https://www.netfilter.org/documentation/HOWTO/netfilter-extensions-HOWTO-6.html Examples for filtering packets based on AH and ESP header SPI values and reserved fields. ```bash # ip6tables -A INPUT -m ah --ahspi 500 --ahres -j DROP # ip6tables --list Chain INPUT (policy ACCEPT) target prot opt source destination DROP all anywhere anywhere ah spi:500 reserved ``` ```bash # ip6tables -A INPUT -m esp --espspi 500 -j DROP # iptables --list Chain INPUT (policy ACCEPT) target prot opt source destination DROP all anywhere anywhere esp spi:500 ``` ```bash # ip6tables -A INPUT -m ah --ahspi 500 --ahres --ahlen ! 40 -m esp --espspi 500 -j DROP # iptables --list Chain INPUT (policy ACCEPT) target prot opt source destination DROP all anywhere anywhere ah spi:500 length:!40 reserved esp spi:500 ``` -------------------------------- ### Rate-Limited Logging Example Source: https://www.netfilter.org/documentation/HOWTO/packet-filtering-HOWTO-7.html This rule logs packets with the default limit parameters, effectively rate-limiting log messages. ```bash iptables -A FORWARD -m limit --limit 1/hour -j LOG --log-prefix "iptables denied: " ``` -------------------------------- ### iptables u32 module syntax for matching fields Source: https://www.netfilter.org/documentation/HOWTO/netfilter-extensions-HOWTO.sgml The basic syntax for the u32 module, specifying the start byte, mask, and range for matching. ```bash iptables -m u32 --u32 "Start&Mask=Range" ``` -------------------------------- ### Run Patch-O-Matic NG Source: https://www.netfilter.org/documentation/HOWTO/netfilter-extensions-HOWTO-2.html Execute the 'runme' script from the patch-o-matic-ng directory to start the patching process. The 'extra' argument applies patches from the extra suite. ```bash # ./runme extra ``` -------------------------------- ### New IPv6 Netfilter Targets Source: https://www.netfilter.org/documentation/HOWTO/netfilter-extensions-HOWTO.sgml Explains how to get help for new netfilter targets and introduces the LOG and REJECT targets. ```APIDOC ## New IPv6 Netfilter Targets ### Description Information on using new netfilter targets for IPv6, including how to get help and details on LOG and REJECT targets. ### Method N/A (Command-line utility) ### Endpoint N/A (Command-line utility) ### Parameters N/A ### Request Example ```bash # ip6tables -j THE_TARGET_YOU_WANT --help ``` ### Response #### Success Response (Help Output) - **LOG**: A target that allows logging packets, similar to IPv4 iptables. - **REJECT**: A target that allows rejecting packets, similar to IPv4 iptables. #### Response Example (Help output will vary based on the specific target. For LOG and REJECT, examples are similar to IPv4 iptables. See man page for details.) ``` -------------------------------- ### Match TTL using iptables u32 module Source: https://www.netfilter.org/documentation/HOWTO/netfilter-extensions-HOWTO.sgml This example shows how to match the Time To Live (TTL) field using the u32 module. It's equivalent to `iptables -m ttl --ttl-lt 4` or the bpf filter `ip[8] <= 3`. ```bash iptables -m u32 --u32 "5&0xFF=0:3" ``` -------------------------------- ### Use recent patch to drop packets from recent connections Source: https://www.netfilter.org/documentation/HOWTO/netfilter-extensions-HOWTO.sgml This example demonstrates using the 'recent' match to drop packets from IP addresses that have recently attempted to connect to a specific port. It first checks if an IP is in the 'badguy' list and has been seen in the last 60 seconds, dropping the packet if true. If not, it checks for TCP connections to port 139, adds the source IP to the 'badguy' list, and then drops the packet. ```bash # iptables -A FORWARD -m recent --name badguy --rcheck --seconds 60 -j DROP # iptables -A FORWARD -p tcp -i eth0 --dport 139 -m recent --name badguy --set -j DROP ``` ```bash # iptables --list Chain FORWARD (policy ACCEPT) target prot opt source destination DROP all -- anywhere anywhere recent: CHECK seconds: 60 DROP tcp -- anywhere anywhere tcp dpt:netbios-ssn recent: SET ``` -------------------------------- ### Display iptables match help Source: https://www.netfilter.org/documentation/HOWTO/netfilter-extensions-HOWTO-3.html Use this command to view specific help documentation for a chosen netfilter match module. ```bash # iptables -m the_match_you_want --help ``` -------------------------------- ### Display Patch-o-matic Help Source: https://www.netfilter.org/documentation/HOWTO/netfilter-extensions-HOWTO.sgml View the command-line options and usage instructions for the runme script. ```bash # ./runme --help ``` -------------------------------- ### Insert Connection-Tracking Modules Source: https://www.netfilter.org/documentation/HOWTO/packet-filtering-HOWTO.txt Load the necessary kernel modules for connection tracking if they are not already built into the kernel. ```bash ## Insert connection-tracking modules (not needed if built into kernel). # insmod ip_conntrack # insmod ip_conntrack_ftp ``` -------------------------------- ### Configure TEQL Scheduler and Routing Source: https://www.netfilter.org/documentation/HOWTO/netfilter-extensions-HOWTO-4.html This script sets up the TEQL (Time-Equal-Link) scheduler for per-packet round-robin scheduling across multiple WAN interfaces. It configures interfaces, sysctl settings, and IP routing. ```bash modprobe sch_teql for i in 0 1 2 3 ip link set dev hdlc${i} up sysctl -w net.ipv4.conf.hdlc${i}.rp_filter=0 tc qdisc add dev hdlc${i} root teql0 done ip link set dev teql0 up sysctl -w net.ipv4.conf.teql0.rp_filter=0 ip address add $IPADDR peer $REMIP dev teql0 ip route add default via $REMIP dev teql0 ``` -------------------------------- ### List Available IP Tables Source: https://www.netfilter.org/documentation/FAQ/netfilter-faq-3.html List all available IP tables by reading the ip_tables_names file in the proc filesystem. ```bash cat /proc/net/ip_tables_names ``` -------------------------------- ### Double NAT Network Topology Diagram Source: https://www.netfilter.org/documentation/HOWTO/netfilter-double-nat-HOWTO-4.html Visual representation of the network architecture required for a Double NAT setup. ```text ASCII Art 3: Attempt 2 Network 1 192.168.150.0 (Corp) | Network 2 | 192.168.180.0 (Intermediate) | NAT BOX 1 | eth0 192.168.180.180 eth1 10.15.15.1 | NAT BOX 2 | eth0 10.15.15.2 eth1 192.168.150.252 | Newtwork 3 | 192.168.150.0 (Untrusted Network) ``` -------------------------------- ### Configure SAME Target Source: https://www.netfilter.org/documentation/HOWTO/netfilter-extensions-HOWTO.sgml Maps source addresses to a specific range for outgoing connections. ```bash # iptables -t nat -A POSTROUTING -j SAME --to 1.2.3.4-1.2.3.7 # iptables -t nat --list Chain POSTROUTING (policy ACCEPT) target prot opt source destination SAME all -- anywhere anywhere same:1.2.3.4-1.2.3.7 ``` -------------------------------- ### Check 2-Byte Field Value Source: https://www.netfilter.org/documentation/HOWTO/netfilter-extensions-HOWTO-3.html Examples of checking 2-byte fields like IPID or total length using masks. ```bash iptables -m u32 --u32 "2&0xFFFF=0x2:0x0100" ``` ```bash -j LOG --log-prefix "ID-in-2-256 " -j DROP ``` ```bash iptables -m u32 --u32 "0&0xFFFF=0x100:0xFFFF" ``` ```bash iptables -m length --length 256:65535 or the bpf filter "len >= 256" ``` -------------------------------- ### Create a new chain Source: https://www.netfilter.org/documentation/HOWTO/packet-filtering-HOWTO-7.html Create a user-defined chain named 'test'. ```bash # iptables -N test # ``` -------------------------------- ### Filter IPv6 packets by extension headers Source: https://www.netfilter.org/documentation/HOWTO/netfilter-extensions-HOWTO.sgml Examples of dropping packets based on specific IPv6 extension headers using the ipv6header module. ```bash # ip6tables -A INPUT -m ipv6header --header hop-by-hop,ipv6-route,protocol -j DROP # ip6tables --list Chain INPUT (policy ACCEPT) target prot opt source destination DROP all anywhere anywhere ipv6header flags:hop-by-hop,ipv6-route,protocol ``` ```bash # ip6tables -A INPUT -m ipv6header --header ipv6-route --soft -j DROP # ip6ptables --list Chain INPUT (policy ACCEPT) target prot opt source destination DROP all anywhere anywhere ipv6header flags:ipv6-route soft ``` -------------------------------- ### List ip6tables fragment match Source: https://www.netfilter.org/documentation/HOWTO/netfilter-extensions-HOWTO.sgml Displays the current ip6tables configuration showing a fragment match rule. ```bash # ip6tables --list Chain INPUT (policy ACCEPT) target prot opt source destination DROP all anywhere anywhere frag ids:100:200 first ``` -------------------------------- ### Display Target Help Source: https://www.netfilter.org/documentation/HOWTO/netfilter-extensions-HOWTO-4.html Retrieve help information for a specific netfilter target module. ```bash # iptables -j THE_TARGET_YOU_WANT --help ``` -------------------------------- ### Display help for a netfilter match Source: https://www.netfilter.org/documentation/HOWTO/netfilter-extensions-HOWTO-6.html Use this command to view the help message for a specific netfilter module. ```bash # ip6tables -m the_match_you_want --help ``` -------------------------------- ### Configure NETMAP target Source: https://www.netfilter.org/documentation/HOWTO/netfilter-extensions-HOWTO.sgml Creates a static 1:1 network address mapping for incoming connections in the NAT table. ```bash # iptables -t nat -A PREROUTING -d 1.2.3.0/24 -j NETMAP --to 5.6.7.0/24 ``` -------------------------------- ### Inspect Early Header Bytes with Bit Shifting Source: https://www.netfilter.org/documentation/HOWTO/netfilter-extensions-HOWTO-3.html Using bitwise masks and right-shift operations to inspect fields located at the start of the header. ```bash iptables -m u32 --u32 "0&0x00FF0000>>16=0x08" ``` ```bash iptables -m ttl --tos 8 ``` -------------------------------- ### Configure NETMAP Target Source: https://www.netfilter.org/documentation/HOWTO/netfilter-extensions-HOWTO-4.html Perform static 1:1 network address mapping while preserving host addresses. ```bash # iptables -t nat -A PREROUTING -d 1.2.3.0/24 -j NETMAP --to 5.6.7.0/24 # iptables -t nat --list Chain PREROUTING (policy ACCEPT) target prot opt source destination NETMAP all -- anywhere 1.2.3.0/24 5.6.7.0/24 ``` -------------------------------- ### Log Packets with Realm 10 Source: https://www.netfilter.org/documentation/HOWTO/netfilter-extensions-HOWTO-3.html The realm match allows filtering based on the routing realm. This example logs outgoing packets with a realm of 10. ```bash # iptables -A OUTPUT -m realm --realm 10 -j LOG ``` ```bash # iptables --list Chain OUTPUT (policy ACCEPT) prot opt source destination LOG all -- anywhere anywhere REALM match 0xa LOG level warning ``` -------------------------------- ### List Checked Out Directories Source: https://www.netfilter.org/documentation/HOWTO/netfilter-extensions-HOWTO-2.html Verify that the iptables and patch-o-matic-ng directories have been successfully checked out. ```bash # ls -l netfilter_svn/ total 3 drwxr-xr-x 9 root root 864 Nov 7 14:48 iptables/ drwxr-xr-x 13 root root 488 Nov 7 14:54 patch-o-matic-ng/ ``` -------------------------------- ### Configure Connection Tracking Rules Source: https://www.netfilter.org/documentation/HOWTO/packet-filtering-HOWTO-11.html Sets up a custom chain to manage connection states and log suspicious packets from a specific interface. ```bash # iptables -N no-conns-from-ppp0 # iptables -A no-conns-from-ppp0 -m state --state ESTABLISHED,RELATED -j ACCEPT # iptables -A no-conns-from-ppp0 -m state --state NEW -i ! ppp0 -j ACCEPT # iptables -A no-conns-from-ppp0 -i ppp0 -m limit -j LOG --log-prefix "Bad packet from ppp0:" # iptables -A no-conns-from-ppp0 -i ! ppp0 -m limit -j LOG --log-prefix "Bad packet not from ppp0:" # iptables -A no-conns-from-ppp0 -j DROP # iptables -A INPUT -j no-conns-from-ppp0 # iptables -A FORWARD -j no-conns-from-ppp0 ``` -------------------------------- ### Conntrack Helper Module Skeleton Source: https://www.netfilter.org/documentation/HOWTO/netfilter-hacking-HOWTO.txt Example skeleton for a conntrack helper module. It defines callbacks for expected connections and packet analysis, and registers the helper with Netfilter. ```c #define FOO_PORT 111 static int foo_expectfn(struct ip_conntrack *new) { /* called when the first packet of an expected connection arrives */ return 0; } static int foo_help(const struct iphdr *iph, size_t len, struct ip_conntrack *ct, enum ip_conntrack_info ctinfo) { /* analyze the data passed on this connection and decide how related packets will look like */ /* update per master-connection private data (session state, ...) */ ct->help.ct_foo_info = ... if (there_will_be_new_packets_related_to_this_connection) { struct ip_conntrack_expect exp; memset(&exp, 0, sizeof(exp)); exp.t = tuple_specifying_related_packets; exp.mask = mask_for_above_tuple; exp.expectfn = foo_expectfn; exp.seq = tcp_sequence_number_of_expectation_cause; /* per slave-connection private data */ exp.help.exp_foo_info = ... ip_conntrack_expect_related(ct, &exp); } return NF_ACCEPT; } static struct ip_conntrack_helper foo; static int __init init(void) { memset(&foo, 0, sizeof(struct ip_conntrack_helper); foo.name = "foo"; foo.flags = IP_CT_HELPER_F_REUSE_EXPECT; foo.me = THIS_MODULE; foo.max_expected = 1; /* one expectation at a time */ foo.timeout = 0; /* expectation never expires */ /* we are interested in all TCP packets with destport 111 */ foo.tuple.dst.protonum = IPPROTO_TCP; foo.tuple.dst.u.tcp.port = htons(FOO_PORT); foo.mask.dst.protonum = 0xFFFF; foo.mask.dst.u.tcp.port = 0xFFFF; foo.help = foo_help; return ip_conntrack_helper_register(&foo); } static void __exit fini(void) { ip_conntrack_helper_unregister(&foo); } ``` -------------------------------- ### List iptables rules Source: https://www.netfilter.org/documentation/HOWTO/netfilter-extensions-HOWTO.sgml Displays the current iptables configuration for the FORWARD chain. ```bash iptables --list Chain FORWARD (policy ACCEPT) target prot opt source destination ACCEPT all -- anywhere anywhere ctstate RELATED ``` -------------------------------- ### Patch-O-Matic NG Help Source: https://www.netfilter.org/documentation/HOWTO/netfilter-extensions-HOWTO-2.html Display the help message for the patch-o-matic-ng 'runme' script. This shows available options for batch mode, reverse patching, excluding patches, and more. ```bash # ./runme --help Usage: ./runme [--batch] [--reverse] [--exclude suite/patch-dir ] suite|suite/patch-dir Options: --batch batch mode, automatically applying patches. --test test mode, automatically test patches. --check check mode, automatically checks if patches are alreay applied. produces a logfile: rune.out-check --reverse back out the selected patches. --exclude suite/patch-dir excludes the named patch. can be used multiple times. --help print a help message --man print the whole manpage ``` -------------------------------- ### Drop 50% of ICMP Echo Requests Randomly Source: https://www.netfilter.org/documentation/HOWTO/netfilter-extensions-HOWTO-3.html Use the random match to probabilistically drop packets. This example drops 50% of incoming ICMP echo requests. ```bash # iptables -A INPUT -p icmp --icmp-type echo-request -m random --average 50 -j DROP ``` ```bash # iptables --list Chain INPUT (policy ACCEPT) prot opt source destination DROP icmp -- anywhere anywhere icmp echo-request random 50% ``` -------------------------------- ### Initialize the me field for ip_conntrack_helper Source: https://www.netfilter.org/documentation/HOWTO/netfilter-hacking-HOWTO-4.html The me field should be initialized using this macro to point to the module structure. ```c THIS_MODULE ``` -------------------------------- ### Netfilter Socket Options Structure Source: https://www.netfilter.org/documentation/HOWTO/netfilter-hacking-HOWTO-4.html Define the structure for Netfilter socket option operations, including protocol family, option ranges, and handler functions for setting and getting options. ```c struct nf_sockopt_ops { struct list_head list; int pf; int set_optmin, set_optmax; int (*set) (struct sock *, struct sk_buff *, struct tlv_opt *, int); int get_optmin, get_optmax; int (*get) (struct sock *, struct sk_buff *, struct tlv_opt *, int); }; ``` -------------------------------- ### ip6tables --list Source: https://www.netfilter.org/documentation/HOWTO/netfilter-extensions-HOWTO.sgml Lists the current ip6tables rules for the INPUT chain, showing the policy and configured rules with target, protocol, options, source, and destination. ```APIDOC ## ip6tables --list ### Description Lists the current ip6tables rules for the INPUT chain. ### Method N/A (Command-line utility) ### Endpoint N/A (Command-line utility) ### Parameters N/A ### Request Example ```bash # ip6tables --list ``` ### Response #### Success Response (Output) - **Chain INPUT**: Policy and rules for the INPUT chain. - **target**: The action to take (e.g., DROP, ACCEPT). - **prot**: Protocol (e.g., all, tcp, udp). - **opt**: Options for the rule. - **source**: Source IP address or range. - **destination**: Destination IP address or range. #### Response Example ``` Chain INPUT (policy ACCEPT) target prot opt source destination DROP all anywhere anywhere rt type:0 segslefts:0:2 0-addrs ::1,::2 0-not-strict ``` ``` -------------------------------- ### Userspace Shared Library Initialization Source: https://www.netfilter.org/documentation/HOWTO/netfilter-hacking-HOWTO-4.html The `_init()` function in a userspace shared library is called upon loading. It should register new matches or targets using `register_match()` or `register_target()`. ```c extern int register_match(struct ipt_match *match); extern int register_target(struct ipt_target *target); int _init(void) { // ... registration logic ... return 0; } ``` -------------------------------- ### Manage Recent IP List for Dropping Packets Source: https://www.netfilter.org/documentation/HOWTO/netfilter-extensions-HOWTO-3.html The recent match module allows creating and checking lists of IP addresses. This example drops packets from IPs that have recently connected to port 139. ```bash # iptables -A FORWARD -m recent --name badguy --rcheck --seconds 60 -j DROP # iptables -A FORWARD -p tcp -i eth0 --dport 139 -m recent --name badguy --set -j DROP ``` ```bash # iptables --list Chain FORWARD (policy ACCEPT) target prot opt source destination DROP all -- anywhere anywhere recent: CHECK seconds: 60 DROP tcp -- anywhere anywhere tcp dpt:netbios-ssn recent: SET ``` -------------------------------- ### Match packets containing a specific string Source: https://www.netfilter.org/documentation/HOWTO/netfilter-extensions-HOWTO.sgml This example demonstrates using the 'string' match to find packets containing the string 'badstring' and queueing them for userland processing. This is useful for integrating with Intrusion Detection Systems (IDS). ```bash # iptables -A INPUT -m string --string 'badstring' -j QUEUE ``` -------------------------------- ### Ensure Kernel Dependencies Source: https://www.netfilter.org/documentation/HOWTO/netfilter-extensions-HOWTO-2.html Navigate to your kernel source directory and run 'make dep' to ensure all necessary kernel dependencies are met before applying patches. ```bash # cd /usr/src/linux/ # make dep ``` -------------------------------- ### Match Packet Length (Length Patch) Source: https://www.netfilter.org/documentation/HOWTO/netfilter-extensions-HOWTO-3.html Use the length match to filter packets based on their size. Specify a length or a range using the --length option. For example, to drop pings larger than 85 bytes. ```bash # iptables -A INPUT -p icmp --icmp-type echo-request -m length --length 86:0xffff -j DROP # iptables --list Chain INPUT (policy ACCEPT) target prot opt source destination DROP icmp -- anywhere anywhere icmp echo-request length 86:65535 ``` -------------------------------- ### iptables String Match Example Source: https://www.netfilter.org/documentation/HOWTO/netfilter-extensions-HOWTO.sgml Use the string match with caution. It is designed for queuing packets for analysis, not for blocking content like HTTP POST requests, which is better handled by a proxy. Blocking based on strings can be easily bypassed. ```bash # iptables --list Chain INPUT (policy ACCEPT) target prot opt source destination QUEUE all -- anywhere anywhere STRING match badstring ``` -------------------------------- ### Match total packet length using iptables u32 module Source: https://www.netfilter.org/documentation/HOWTO/netfilter-extensions-HOWTO.sgml This example matches packets with a total length greater than or equal to 256 bytes. It is equivalent to `iptables -m length --length 256:65535` or the bpf filter `len >= 256`. ```bash iptables -m u32 --u32 "0&0xFFFF=0x100:0xFFFF" ``` -------------------------------- ### Configure Squid for Transparent Proxy Source: https://www.netfilter.org/documentation/FAQ/netfilter-faq-3.html Basic configuration settings for squid.conf to enable transparent proxying. ```text http_port 3128 httpd_accel_host virtual httpd_accel_port 80 httpd_accel_with_proxy on httpd_accel_uses_host_header on ``` ```text httpd_accel_single_host off ``` -------------------------------- ### Netfilter NAT Helper Module Example Source: https://www.netfilter.org/documentation/HOWTO/netfilter-hacking-HOWTO-4.html This C code defines a Netfilter NAT helper module. It includes functions for handling expected connections (`foo_nat_expected`) and packets (`foo_help`), and registers the helper with the Netfilter framework using `ip_nat_helper_register`. Ensure the necessary Netfilter headers are included. ```c #define FOO_PORT 111 static int foo_nat_expected(struct sk_buff **pksb, unsigned int hooknum, struct ip_conntrack *ct, struct ip_nat_info *info) /* called whenever the first packet of a related connection arrives. params: pksb packet buffer hooknum HOOK the call comes from (POST_ROUTING, PRE_ROUTING) ct information about this (the related) connection info &ct->nat.info return value: Verdict (NF_ACCEPT, ...) { /* Change ip/port of the packet to the masqueraded values (read from master->tuplehash), to map it the same way, call ip_nat_setup_info, return NF_ACCEPT. */ } static int foo_help(struct ip_conntrack *ct, struct ip_conntrack_expect *exp, struct ip_nat_info *info, enum ip_conntrack_info ctinfo, unsigned int hooknum, struct sk_buff **pksb) /* called for every packet where conntrack detected an expectation-cause params: ct struct ip_conntrack of the master connection exp struct ip_conntrack_expect of the expectation caused by the conntrack helper for this protocol info (STATE: related, new, established, ... ) hooknum HOOK the call comes from (POST_ROUTING, PRE_ROUTING) pksb packet buffer */ { /* extract information about future related packets (you can share information with the connection tracking's foo_help). Exchange address/port with masqueraded values, insert tuple about related packets */ } static struct ip_nat_helper hlpr; static int __init(void) { int ret; memset(&hlpr, 0, sizeof(struct ip_nat_helper)); hlpr.list = { NULL, NULL }; hlpr.tuple.dst.protonum = IPPROTO_TCP; hlpr.tuple.dst.u.tcp.port = htons(FOO_PORT); hlpr.mask.dst.protonum = 0xFFFF; hlpr.mask.dst.u.tcp.port = 0xFFFF; hlpr.help = foo_help; hlpr.expect = foo_nat_expect; ret = ip_nat_helper_register(hlpr); return ret; } static void __exit(void) { ip_nat_helper_unregister(&hlpr); } ``` -------------------------------- ### Configure IPV4OPTSSTRIP Target Source: https://www.netfilter.org/documentation/HOWTO/netfilter-extensions-HOWTO-4.html Strip all IP options from IPv4 packets in the PREROUTING chain. ```bash # iptables -t mangle -A PREROUTING -j IPV4OPTSSTRIP # iptables -t mangle --list Chain PREROUTING (policy ACCEPT) target prot opt source destination IPV4OPTSSTRIP all -- anywhere anywhere ``` -------------------------------- ### Checkout Netfilter Userspace Code Source: https://www.netfilter.org/documentation/HOWTO/netfilter-hacking-HOWTO-2.html Command to download the netfilter/userspace repository. ```bash # cvs -d :pserver:cvs@pserver.netfilter.org:/cvspublic co netfilter/userspace ``` -------------------------------- ### Configure Masquerading and Filter Incoming Connections Source: https://www.netfilter.org/documentation/HOWTO/packet-filtering-HOWTO-9.html Sets up masquerading on the ppp0 interface while blocking new or invalid incoming and forwarded packets. Requires IP forwarding to be enabled. ```bash # Masquerade out ppp0 iptables -t nat -A POSTROUTING -o ppp0 -j MASQUERADE # Disallow NEW and INVALID incoming or forwarded packets from ppp0. iptables -A INPUT -i ppp0 -m state --state NEW,INVALID -j DROP iptables -A FORWARD -i ppp0 -m state --state NEW,INVALID -j DROP # Turn on IP forwarding echo 1 > /proc/sys/net/ipv4/ip_forward ``` -------------------------------- ### Enable Route Verification for All Interfaces Source: https://www.netfilter.org/documentation/HOWTO/packet-filtering-HOWTO.txt Iterates through all existing and future network interfaces to enable reverse path filtering. ```bash # for f in /proc/sys/net/ipv4/conf/*/rp_filter; do # echo 1 > $f # done # ```