About Contact us Forums Home Linux How-to & Tutorials Shell Scripts RSS/Feed nixCraft Linux: 20 Iptables Examples For New SysAdmins by NIX Craft on December 13, 2011 · 65 comments· LAST UPDATED March 20, 2012 in Iptables, Linux, Linux distribution Linux comes with a host based firewall called Netfilter. According to the official project site: netfilter is a set of hooks inside the Linux kernel that allows kernel modules to register callback functions with the network stack. A registered callback function is then called back for every packet that traverses the respective hook within the network stack. This Linux based firewall is controlled by the program called iptables to handles filtering for IPv4, and ip6tables handles filtering for IPv6. I strongly recommend that you first read our quick tutorial that explains how to configure a host-based firewall called Netfilter (iptables) under CentOS / RHEL / Fedora / Redhat Enterprise Linux. This post list most common iptables solutions required by a new Linux user to secure his or her Linux operating system from intruders. IPTABLES Rules Example Most of the actions listed in this post are written with the assumption that they will be executed by the root user running the bash or any other modern shell. Do not type commands on remote system as it will disconnect your access. For demonstration purpose I've used RHEL 6.x, but the following command should work with any modern Linux distro. This is NOT a tutorial on how to set iptables. See tutorial here. It is a quick cheat sheet to common iptables commands. #1: Displaying the Status of Your Firewall Type the following command as root: # iptables -L -n -v Sample outputs: Chain INPUT (policy ACCEPT 0 packets, 0 bytes) pkts bytes target prot opt in out source destination Chain FORWARD (policy ACCEPT 0 packets, 0 bytes) pkts bytes target prot opt in out source destination Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes) pkts bytes target prot opt in out source destination Above output indicates that the firewall is not active. The following sample shows an active firewall: # iptables -L -n -v Sample outputs: Chain INPUT (policy DROP 0 packets, 0 bytes) pkts bytes target prot opt in out destination 0 0 DROP all -- * * state INVALID 394 43586 ACCEPT all -- * * state RELATED,ESTABLISHED 93 17292 ACCEPT all -- br0 * 1 142 ACCEPT all -- lo * Chain FORWARD (policy DROP 0 packets, 0 bytes) source 0.0.0.0/0 0.0.0.0/0 0.0.0.0/0 0.0.0.0/0 0.0.0.0/0 0.0.0.0/0 0.0.0.0/0 0.0.0.0/0 pkts bytes target prot opt in out source destination 0 0 ACCEPT all -- br0 br0 0.0.0.0/0 0 0 DROP all -- * * 0.0.0.0/0 state INVALID 0 0 TCPMSS tcp -- * * 0.0.0.0/0 tcp flags:0x06/0x02 TCPMSS clamp to PMTU 0 0 ACCEPT all -- * * 0.0.0.0/0 state RELATED,ESTABLISHED 0 0 wanin all -- vlan2 * 0.0.0.0/0 0 0 wanout all -- * vlan2 0.0.0.0/0 0 0 ACCEPT all -- br0 * 0.0.0.0/0 Chain OUTPUT (policy ACCEPT 425 packets, 113K bytes) pkts bytes target prot opt in out source destination Chain wanin (1 references) pkts bytes target prot opt in out source destination Chain wanout (1 references) pkts bytes target prot opt in out source destination 0.0.0.0/0 0.0.0.0/0 0.0.0.0/0 0.0.0.0/0 0.0.0.0/0 0.0.0.0/0 0.0.0.0/0 Where, -L : List rules. -v : Display detailed information. This option makes the list command show the interface name, the rule options, and the TOS masks. The packet and byte counters are also listed, with the suffix 'K', 'M' or 'G' for 1000, 1,000,000 and 1,000,000,000 multipliers respectively. -n : Display IP address and port in numeric format. Do not use DNS to resolve names. This will speed up listing. #1.1: To inspect firewall with line numbers, enter: # iptables -n -L -v --line-numbers Sample outputs: Chain INPUT (policy DROP) num target prot opt source 1 DROP all -- 0.0.0.0/0 INVALID 2 ACCEPT all -- 0.0.0.0/0 RELATED,ESTABLISHED 3 ACCEPT all -- 0.0.0.0/0 4 ACCEPT all -- 0.0.0.0/0 Chain FORWARD (policy DROP) num target prot opt source 1 ACCEPT all -- 0.0.0.0/0 2 DROP all -- 0.0.0.0/0 INVALID 3 TCPMSS tcp -- 0.0.0.0/0 flags:0x06/0x02 TCPMSS clamp to PMTU destination 0.0.0.0/0 state 0.0.0.0/0 state 0.0.0.0/0 0.0.0.0/0 destination 0.0.0.0/0 0.0.0.0/0 state 0.0.0.0/0 tcp 4 ACCEPT all -- 0.0.0.0/0 RELATED,ESTABLISHED 5 wanin all -- 0.0.0.0/0 6 wanout all -- 0.0.0.0/0 7 ACCEPT all -- 0.0.0.0/0 Chain OUTPUT (policy ACCEPT) num target prot opt source Chain wanin (1 references) num target prot opt source Chain wanout (1 references) num target prot opt source 0.0.0.0/0 state 0.0.0.0/0 0.0.0.0/0 0.0.0.0/0 destination destination destination You can use line numbers to delete or insert new rules into the firewall. #1.2: To display INPUT or OUTPUT chain rules, enter: # iptables -L INPUT -n -v # iptables -L OUTPUT -n -v --line-numbers #2: Stop / Start / Restart the Firewall If you are using CentOS / RHEL / Fedora Linux, enter: # service iptables stop # service iptables start # service iptables restart You can use the iptables command itself to stop the firewall and delete all rules: # # # # # # # # # iptables iptables iptables iptables iptables iptables iptables iptables iptables -F -X -t -t -t -t -P -P -P nat -F nat -X mangle -F mangle -X INPUT ACCEPT OUTPUT ACCEPT FORWARD ACCEPT Where, -F : Deleting (flushing) all the rules. -X : Delete chain. -t table_name : Select table (called nat or mangle) and delete/flush rules. -P : Set the default policy (such as DROP, REJECT, or ACCEPT). #3: Delete Firewall Rules To display line number along with other information for existing rules, enter: # # # # iptables iptables iptables iptables -L -L -L -L INPUT -n --line-numbers OUTPUT -n --line-numbers OUTPUT -n --line-numbers | less OUTPUT -n --line-numbers | grep 202.54.1.1 You will get the list of IP. Look at the number on the left, then use number to delete it. For example delete line number 4, enter: # iptables -D INPUT 4 OR find source IP 202.54.1.1 and delete from rule: # iptables -D INPUT -s 202.54.1.1 -j DROP Where, -D : Delete one or more rules from the selected chain #4: Insert Firewall Rules To insert one or more rules in the selected chain as the given rule number use the following syntax. First find out line numbers, enter: # iptables -L INPUT -n --line-numbers Sample outputs: Chain INPUT (policy DROP) num target prot opt source 1 DROP all -- 202.54.1.1 2 ACCEPT all -- 0.0.0.0/0 NEW,ESTABLISHED destination 0.0.0.0/0 0.0.0.0/0 state destination 0.0.0.0/0 0.0.0.0/0 0.0.0.0/0 state To insert rule between 1 and 2, enter: # iptables -I INPUT 2 -s 202.54.1.2 -j DROP To view updated rules, enter: # iptables -L INPUT -n --line-numbers Sample outputs: Chain INPUT (policy DROP) num target prot opt source 1 DROP all -- 202.54.1.1 2 DROP all -- 202.54.1.2 3 ACCEPT all -- 0.0.0.0/0 NEW,ESTABLISHED #5: Save Firewall Rules To save firewall rules under CentOS / RHEL / Fedora Linux, enter: # service iptables save In this example, drop an IP and save firewall rules: # iptables -A INPUT -s 202.5.4.1 -j DROP # service iptables save For all other distros use the iptables-save command: # iptables-save > /root/my.active.firewall.rules # cat /root/my.active.firewall.rules #6: Restore Firewall Rules To restore firewall rules form a file called /root/my.active.firewall.rules, enter: # iptables-restore < /root/my.active.firewall.rules To restore firewall rules under CentOS / RHEL / Fedora Linux, enter: # service iptables restart #7: Set the Default Firewall Policies To drop all traffic: # iptables -P INPUT DROP # iptables -P OUTPUT DROP # iptables -P FORWARD DROP # iptables -L -v -n #### you will not able to connect anywhere as all traffic is dropped ### # ping cyberciti.biz # wget http://www.kernel.org/pub/linux/kernel/v3.0/testing/linux-3.2rc5.tar.bz2 #7.1: Only Block Incoming Traffic To drop all incoming / forwarded packets, but allow outgoing traffic, enter: # iptables -P INPUT DROP # iptables -P FORWARD DROP # iptables -P OUTPUT ACCEPT # iptables -A INPUT -m state --state NEW,ESTABLISHED -j ACCEPT # iptables -L -v -n ### *** now ping and wget should work *** ### # ping cyberciti.biz # wget http://www.kernel.org/pub/linux/kernel/v3.0/testing/linux-3.2rc5.tar.bz2 #8:Drop Private Network Address On Public Interface IP spoofing is nothing but to stop the following IPv4 address ranges for private networks on your public interfaces. Packets with non-routable source addresses should be rejected using the following syntax: # iptables -A INPUT -i eth1 -s 192.168.0.0/24 -j DROP # iptables -A INPUT -i eth1 -s 10.0.0.0/8 -j DROP #8.1: IPv4 Address Ranges For Private Networks (make sure you block them on public interface) 10.0.0.0/8 -j (A) 172.16.0.0/12 (B) 192.168.0.0/16 (C) 224.0.0.0/4 (MULTICAST D) 240.0.0.0/5 (E) 127.0.0.0/8 (LOOPBACK) #9: Blocking an IP Address (BLOCK IP) To block an attackers ip address called 1.2.3.4, enter: # iptables -A INPUT -s 1.2.3.4 -j DROP # iptables -A INPUT -s 192.168.0.0/24 -j DROP #10: Block Incoming Port Requests (BLOCK PORT) To block all service requests on port 80, enter: # iptables -A INPUT -p tcp --dport 80 -j DROP # iptables -A INPUT -i eth1 -p tcp --dport 80 -j DROP To block port 80 only for an ip address 1.2.3.4, enter: # iptables -A INPUT -p tcp -s 1.2.3.4 --dport 80 -j DROP # iptables -A INPUT -i eth1 -p tcp -s 192.168.1.0/24 --dport 80 -j DROP #11: Block Outgoing IP Address To block outgoing traffic to a particular host or domain such as cyberciti.biz, enter: # host -t a cyberciti.biz Sample outputs: cyberciti.biz has address 75.126.153.206 Note down its ip address and type the following to block all outgoing traffic to 75.126.153.206: # iptables -A OUTPUT -d 75.126.153.206 -j DROP You can use a subnet as follows: # iptables -A OUTPUT -d 192.168.1.0/24 -j DROP # iptables -A OUTPUT -o eth1 -d 192.168.1.0/24 -j DROP #11.1: Example - Block Facebook.com Domain First, find out all ip address of facebook.com, enter: # host -t a www.facebook.com Sample outputs: www.facebook.com has address 69.171.228.40 Find CIDR for 69.171.228.40, enter: # whois 69.171.228.40 | grep CIDR Sample outputs: CIDR: 69.171.224.0/19 To prevent outgoing access to www.facebook.com, enter: # iptables -A OUTPUT -p tcp -d 69.171.224.0/19 -j DROP You can also use domain name, enter: # iptables -A OUTPUT -p tcp -d www.facebook.com -j DROP # iptables -A OUTPUT -p tcp -d facebook.com -j DROP From the iptables man page: ... specifying any name to be resolved with a remote query such as DNS (e.g., facebook.com is a really bad idea), a network IP address (with /mask), or a plain IP address ... #12: Log and Drop Packets Type the following to log and block IP spoofing on public interface called eth1 # iptables -A INPUT -i eth1 -s 10.0.0.0/8 -j LOG --log-prefix "IP_SPOOF A: " # iptables -A INPUT -i eth1 -s 10.0.0.0/8 -j DROP By default everything is logged to /var/log/messages file. # tail -f /var/log/messages # grep --color 'IP SPOOF' /var/log/messages #13: Log and Drop Packets with Limited Number of Log Entries The -m limit module can limit the number of log entries created per time. This is used to prevent flooding your log file. To log and drop spoofing per 5 minutes, in bursts of at most 7 entries . # iptables -A INPUT -i eth1 -s 10.0.0.0/8 -m limit --limit 5/m --limit-burst 7 -j LOG --log-prefix "IP_SPOOF A: " # iptables -A INPUT -i eth1 -s 10.0.0.0/8 -j DROP #14: Drop or Accept Traffic From Mac Address Use the following syntax: # iptables -A INPUT -m mac --mac-source 00:0F:EA:91:04:08 -j DROP ## *only accept traffic for TCP port # 8080 from mac 00:0F:EA:91:04:07 * ## # iptables -A INPUT -p tcp --destination-port 22 -m mac --mac-source 00:0F:EA:91:04:07 -j ACCEPT #15: Block or Allow ICMP Ping Request Type the following command to block ICMP ping requests: # iptables -A INPUT -p icmp --icmp-type echo-request -j DROP # iptables -A INPUT -i eth1 -p icmp --icmp-type echo-request -j DROP Ping responses can also be limited to certain networks or hosts: # iptables -A INPUT -s 192.168.1.0/24 -p icmp --icmp-type echo-request -j ACCEPT The following only accepts limited type of ICMP requests: ### ** assumed that default INPUT policy set to DROP ** ############# iptables -A INPUT -p icmp --icmp-type echo-reply -j ACCEPT iptables -A INPUT -p icmp --icmp-type destination-unreachable -j ACCEPT iptables -A INPUT -p icmp --icmp-type time-exceeded -j ACCEPT ## ** all our server to respond to pings ** ## iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT #16: Open Range of Ports Use the following syntax to open a range of ports: iptables -A INPUT -m state --state NEW -m tcp -p tcp --dport 7000:7010 -j ACCEPT #17: Open Range of IP Addresses Use the following syntax to open a range of IP address: ## only accept connection to tcp port 80 (Apache) if ip is between 192.168.1.100 and 192.168.1.200 ## iptables -A INPUT -p tcp --destination-port 80 -m iprange --src-range 192.168.1.100-192.168.1.200 -j ACCEPT ## nat example ## iptables -t nat -A POSTROUTING -j SNAT --to-source 192.168.1.20-192.168.1.25 #18: Established Connections and Restaring The Firewall When you restart the iptables service it will drop established connections as it unload modules from the system under RHEL / Fedora / CentOS Linux. Edit, /etc/sysconfig/iptables-config and set IPTABLES_MODULES_UNLOAD as follows: IPTABLES_MODULES_UNLOAD = no #19: Help Iptables Flooding My Server Screen Use the crit log level to send messages to a log file instead of console: iptables -A INPUT -s 1.2.3.4 -p tcp --destination-port 80 -j LOG --log-level crit #20: Block or Open Common Ports The following shows syntax for opening and closing common TCP and UDP ports: Replace ACCEPT with DROP to block port: ## open port ssh tcp port 22 ## iptables -A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT iptables -A INPUT -s 192.168.1.0/24 -m state --state NEW -p tcp --dport 22 -j ACCEPT ## open cups (printing service) udp/tcp port 631 for LAN users ## iptables -A INPUT -s 192.168.1.0/24 -p udp -m udp --dport 631 -j ACCEPT iptables -A INPUT -s 192.168.1.0/24 -p tcp -m tcp --dport 631 -j ACCEPT ## allow time sync via NTP for lan users (open udp port 123) ## iptables -A INPUT -s 192.168.1.0/24 -m state --state NEW -p udp --dport 123 j ACCEPT ## open tcp port 25 (smtp) for all ## iptables -A INPUT -m state --state NEW -p tcp --dport 25 -j ACCEPT # open dns server ports for all ## iptables -A INPUT -m state --state NEW -p udp --dport 53 -j ACCEPT iptables -A INPUT -m state --state NEW -p tcp --dport 53 -j ACCEPT ## open http/https (Apache) server port to all ## iptables -A INPUT -m state --state NEW -p tcp --dport 80 -j ACCEPT iptables -A INPUT -m state --state NEW -p tcp --dport 443 -j ACCEPT ## open tcp port 110 (pop3) for all ## iptables -A INPUT -m state --state NEW -p tcp --dport 110 -j ACCEPT ## open tcp port 143 (imap) for all ## iptables -A INPUT -m state --state NEW -p tcp --dport 143 -j ACCEPT ## open access to iptables -A INPUT j ACCEPT iptables -A INPUT j ACCEPT iptables -A INPUT j ACCEPT iptables -A INPUT j ACCEPT Samba file server for lan users only ## -s 192.168.1.0/24 -m state --state NEW -p tcp --dport 137 -s 192.168.1.0/24 -m state --state NEW -p tcp --dport 138 -s 192.168.1.0/24 -m state --state NEW -p tcp --dport 139 -s 192.168.1.0/24 -m state --state NEW -p tcp --dport 445 - ## open access to proxy server for lan users only ## iptables -A INPUT -s 192.168.1.0/24 -m state --state NEW -p tcp --dport 3128 -j ACCEPT ## open access to mysql server for lan users only ## iptables -I INPUT -p tcp --dport 3306 -j ACCEPT #21: Restrict the Number of Parallel Connections To a Server Per Client IP You can use connlimit module to put such restrictions. To allow 3 ssh connections per client host, enter: # iptables -A INPUT -p tcp --syn --dport 22 -m connlimit --connlimit-above 3 -j REJECT Set HTTP requests to 20: # iptables -p tcp --syn --dport 80 -m connlimit --connlimit-above 20 -connlimit-mask 24 -j DROP Where, 1. --connlimit-above 3 : Match if the number of existing connections is above 3. 2. --connlimit-mask 24 : Group hosts using the prefix length. For IPv4, this must be a number between (including) 0 and 32. #22: HowTO: Use iptables Like a Pro For more information about iptables, please see the manual page by typing man iptables from the command line: $ man iptables You can see the help using the following syntax too: # iptables -h To see help with specific commands and targets, enter: # iptables -j DROP -h #22.1: Testing Your Firewall Find out if ports are open or not, enter: # netstat -tulpn Find out if tcp port 80 open or not, enter: # netstat -tulpn | grep :80 If port 80 is not open, start the Apache, enter: # service httpd start Make sure iptables allowing access to the port 80: # iptables -L INPUT -v -n | grep 80 Otherwise open port 80 using the iptables for all users: # iptables -A INPUT -m state --state NEW -p tcp --dport 80 -j ACCEPT # service iptables save Use the telnet command to see if firewall allows to connect to port 80: $ telnet www.cyberciti.biz 80 Sample outputs: Trying 75.126.153.206... Connected to www.cyberciti.biz. Escape character is '^]'. ^] telnet> quit Connection closed. You can use nmap to probe your own server using the following syntax: $ nmap -sS -p 80 www.cyberciti.biz Sample outputs: Starting Nmap 5.00 ( http://nmap.org ) at 2011-12-13 13:19 IST Interesting ports on www.cyberciti.biz (75.126.153.206): PORT STATE SERVICE 80/tcp open http Nmap done: 1 IP address (1 host up) scanned in 1.00 seconds I also recommend you install and use sniffer such as tcpdupm and ngrep to test your firewall settings. Conclusion: This post only list basic rules for new Linux users. You can create and build more complex rules. This requires good understanding of TCP/IP, Linux kernel tuning via sysctl.conf, and good knowledge of your own setup. Stay tuned for next topics: Stateful packet inspection. Using connection tracking helpers. Network address translation. Layer 2 filtering. Firewall testing tools. Dealing with VPNs, DNS, Web, Proxy, and other protocols. TwitterFacebookGoogle+PDF versionFound an error/typo on this page? Help us! Featured Articles: 30 Cool Open Source Software I Discovered in 2013 30 Handy Bash Shell Aliases For Linux / Unix / Mac OS X Top 30 Nmap Command Examples For Sys/Network Admins 25 PHP Security Best Practices For Sys Admins 20 Linux System Monitoring Tools Every SysAdmin Should Know 20 Linux Server Hardening Security Tips Linux: 20 Iptables Examples For New SysAdmins Top 20 OpenSSH Server Best Security Practices Top 20 Nginx WebServer Best Security Practices 20 Examples: Make Sure Unix / Linux Configuration Files Are Free From Syntax Errors 15 Greatest Open Source Terminal Applications Of 2012 My 10 UNIX Command Line Mistakes Top 10 Open Source Web-Based Project Management Software Top 5 Email Client For Linux, Mac OS X, and Windows Users The Novice Guide To Buying A Linux Laptop { 65 comments… read them below or add one } 1 Happysysadm December 13, 2011 at 10:10 am This is a nice breakdown of IPTABLES indeed! Thank you for taking the time for such a comprehensive explaination… I shall bookmark this! Reply 2 logicos December 13, 2011 at 11:56 am Try ferm, “for Easy Rule Making” . In file like “ferm.conf” : chain ( INPUT OUTPUT FORWARD ) policy DROP; chain INPUT proto tcp dport ssh ACCEPT; And next: ferm -i ferm.conf Source: http://ferm.foo-projects.org/ Reply 3 LeftMeAlone December 13, 2011 at 1:58 pm Can any one tell me the difference between the DROP vs REJECT? Which one is recommended for my mail server? Reply 4 Worked December 13, 2011 at 2:59 pm LeftMeAlone, “drop” does not send anything to the remote socket while “reject” sending the following message to the remote socket: (icmp destination port unrechable). Make clean… “drop” maybe the service does not exists. “reject” you can not access to the service. Reply 5 Joeman1 December 13, 2011 at 3:07 pm @LeftMeAlone DROP will silently drop a packet, not notifying the remote host of any problems, just won’t be available. This way, they will no know if the port is active and prohibited or just not used. REJECT will send an ICMP packet back to the remote host explaining (For the lack of better words) that the host is administratively denied. The former is preferred as a remote host will not be able to determine if the port is even up. The latter is not recommended unless software requires the ICMP message for what ever reason. Its not recommended because the remote host will know that the port is in use, but will not be able to connect to it. This way, they can still try to hack the port and get into the system, Hope this helps! Joe Reply 6 Prabal Mishra December 13, 2011 at 3:36 pm thanks ! help for Iptables………….. Reply 7 smilyface December 13, 2011 at 4:11 pm Thankssss.. Reply 8 noone December 13, 2011 at 7:28 pm how about you try host -t a http://www.facebook.com a few times, just to see how dns round-rbin works… Reply 9 noone December 13, 2011 at 7:37 pm also, you can try this #!/bin/bash # Clear any previous rules. /sbin/iptables -F # Default drop policy. /sbin/iptables -P INPUT DROP /sbin/iptables -P OUTPUT ACCEPT # Allow anything over loopback and vpn. /sbin/iptables -A INPUT -i lo -s 127.0.0.1 -d 127.0.0.1 -j ACCEPT /sbin/iptables -A OUTPUT -o lo -s 127.0.0.1 -d 127.0.0.1 -j ACCEPT /sbin/iptables -A INPUT -i tun0 -j ACCEPT /sbin/iptables -A OUTPUT -o tun0 -j ACCEPT /sbin/iptables -A INPUT -p esp -j ACCEPT /sbin/iptables -A OUTPUT -p esp -j ACCEPT # Drop any tcp packet that does not start a connection with a syn flag. /sbin/iptables -A INPUT -p tcp ! --syn -m state --state NEW -j DROP # Drop any invalid packet that could not be identified. /sbin/iptables -A INPUT -m state --state INVALID -j DROP # Drop invalid packets. /sbin/iptables -A INPUT -p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -j DROP /sbin/iptables -A INPUT -p tcp -m tcp --tcp-flags SYN,FIN SYN,FIN -j DROP /sbin/iptables -A INPUT -p tcp -m tcp --tcp-flags SYN,RST SYN,RST -j DROP /sbin/iptables -A INPUT -p tcp -m tcp --tcp-flags FIN,RST FIN,RST -j DROP /sbin/iptables -A INPUT -p tcp -m tcp --tcp-flags ACK,FIN FIN -j DROP /sbin/iptables -A INPUT -p tcp -m tcp --tcp-flags ACK,URG URG -j DROP # Reject broadcasts to 224.0.0.1 /sbin/iptables -A INPUT -s 224.0.0.0/4 -j DROP /sbin/iptables -A INPUT -d 224.0.0.0/4 -j DROP /sbin/iptables -A INPUT -s 240.0.0.0/5 -j DROP # Blocked ports /sbin/iptables -A INPUT -p tcp -m state --state NEW,ESTABLISHED,RELATED --dport 8010 -j DROP # Allow TCP/UDP connections out. Keep state so conns out are allowed back in. /sbin/iptables -A INPUT -p tcp -m state --state ESTABLISHED -j ACCEPT /sbin/iptables -A OUTPUT -p tcp -m state --state NEW,ESTABLISHED -j ACCEPT /sbin/iptables -A INPUT -p udp -m state --state ESTABLISHED -j ACCEPT /sbin/iptables -A OUTPUT -p udp -m state --state NEW,ESTABLISHED -j ACCEPT # Allow only ICMP echo requests (ping) in. Limit rate in. Uncomment if needed. /sbin/iptables -A INPUT -p icmp -m state --state NEW,ESTABLISHED -icmp-type echo-reply -j ACCEPT /sbin/iptables -A OUTPUT -p icmp -m state --state NEW,ESTABLISHED -icmp-type echo-request -j ACCEPT # or block ICMP allow only ping out /sbin/iptables -A INPUT -p icmp -m state --state NEW -j DROP /sbin/iptables -A INPUT -p icmp -m state --state ESTABLISHED -j ACCEPT /sbin/iptables -A OUTPUT -p icmp -m state --state NEW,ESTABLISHED -j ACCEPT # Allow ssh connections in. #/sbin/iptables -A INPUT -p tcp -s 1.2.3.4 -m tcp --dport 22 -m state -state NEW,ESTABLISHED,RELATED -m limit --limit 2/m -j ACCEPT # Drop everything that did not match above or drop and log it. #/sbin/iptables -A INPUT -j LOG --log-level 4 --log-prefix "IPTABLES_INPUT: " /sbin/iptables -A INPUT -j DROP #/sbin/iptables -A FORWARD -j LOG --log-level 4 --log-prefix "IPTABLES_FORWARD: " /sbin/iptables -A FORWARD -j DROP #/sbin/iptables -A OUTPUT -j LOG --log-level 4 --log-prefix "IPTABLES_OUTPUT: " /sbin/iptables -A OUTPUT -j ACCEPT iptables-save > /dev/null 2>&1 Reply 10 Coolm@x December 13, 2011 at 7:38 pm Nice examples, but missing one. Commonly searched rule is one for masquerade. Reply 11 Roy December 13, 2011 at 10:19 pm This is extremely useful, somekind of magic and quick recipe… (Of course now i can’t send mail on my remote server (to strict rate limit …)) Reply 12 3y3lop December 14, 2011 at 3:00 am Nice examples & thanks. Reply 13 Jani December 15, 2011 at 9:00 am .. I’m anxiously awaiting similar translated to ip6tables. :-) Reply 14 Howard December 22, 2011 at 3:24 am A most excellent presentation of iptables setup and use. Really Superior work. Thanks kindly. Reply 15 Linus Gasser December 22, 2011 at 7:32 pm Point 8: And for the private address ranges to block on public interfaces, you’ll also want to block 169.254/16 – zeroconf Reply 16 Pieter December 23, 2011 at 5:44 pm Nice post, thanks! In example #19 there is an error in the last line: ## open access to mysql server for lan users only ## iptables -I INPUT -p tcp --dport 3306 -j ACCEPT Should probably be: ## open access to mysql server for lan users only ## iptables -I INPUT -p tcp -s 192.168.1.0/24 --dport 3306 -j ACCEPT Reply 17 shawn cao February 24, 2012 at 4:33 am that is right. Reply 18 Alejandro December 23, 2011 at 11:15 pm Thanks for this post, I hope you don’t mind if I translate this to spanish and post it on my blog, Mentioning the original source, of course. Regards Reply 19 strangr December 24, 2011 at 12:41 am Simple rules to share your connection to internet (interface IFNAME) with other hosts on your local LAN (NATTED_SUBNET). In other words how to do NAT and MASQEURADEing. IFNAME=ppp0 NATTED_SUBNET=192.168.2.0/24 # 1) load appropriate kernel module modprobe iptable_nat # 2) make sure IPv4 forwarding is enabled echo 1 > /proc/sys/net/ipv4/ip_forward # 3) the appropriate rules iptables -A POSTROUTING -t nat -o $IFNAME -s $NATTED_SUBNET -d 0/0 \ -j MASQUERADE iptables -A FORWARD -t filter -o $IFNAME -s $NATTED_SUBNET -m state \ --state NEW,ESTABLISHED,RELATED -j ACCEPT iptables -A FORWARD -t filter -i $IFNAME -d $NATTED_SUBNET -m state \ --state ESTABLISHED,RELATED -j ACCEPT Reply 20 liRONux July 8, 2013 at 12:50 pm THANKS for this. How about blocking a website while having those rules? Reply 21 JD December 31, 2011 at 2:27 am ## open access to mysql server for lan users only ## iptables -I INPUT -p tcp -s 192.168.1.0/24 –dport 3306 -j ACCEPT This should be like this: -s 192.168.1.0/24 -d 192.168.2.2 -i eth0 -p tcp -m state –state NEW -m tcp –dport 3306 -j ACCEPT a rule like this should go under RELATED,ESTABLISHED in the INPUT chain Reply 22 JD December 31, 2011 at 2:39 am For email servers, I have rate limiting rules in place for all service ports. In the INPUT chain I have the spam firewall ip(s), allowed via port 25. Then for the email ports, I impose a hit count of 10 in 60 seconds, smart phones, email clients do not poll every second. Anything more than this is dropped and they can continue on a rampage with no affect on the server(s). It took me a while to come up with the rate-limiting chains to work with the email server. Since the Watch Guard XCS devices needed to be exempt from the rules. They have rate-limits on incoming connections as well, a lot better than Barracuda. I always specify the source/destination interface, state then the port. Reply 23 MB January 3, 2012 at 8:17 am How do i open the port 25 on a public ip (eg. 1.2.3.4) because it is close, I can only send email but can’t receive email? But on my localhost it’s open, when I test I able to send and receive only on 127.0.0.1. This is my rule iptables -A INPUT -p tcp -m tcp –dport 25 -j ACCEPT when i check netstat -tulpn | grep :25 tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN 2671/exim4 tcp6 0 0 ::1:25 :::* LISTEN 2671/exim4 Hope you can help me on this matter. I really confused on this one. Reply 24 Badr Najah January 2, 2012 at 6:55 pm Very useful. Thanks Reply 25 dilip January 5, 2012 at 7:36 am Wooooooooooowwwwww. thats coooool… very usefull link…. Thanks yar…. Reply 26 nbasileu January 9, 2012 at 10:19 am Rule #14 ## *only accept traffic for TCP port # 8080 from mac 00:0F:EA:91:04:07 * ## # iptables -A INPUT -p tcp –destination-port 22 -m mac –mac-source 00:0F:EA:91:04:07 -j ACCEPT –destination-port 8080 not 22 Anyway, this is a fu**** good website with fully nice articles. Very big thx dudes. Happy new year everyone. Reply 27 Atul Modi March 11, 2012 at 10:16 am Excellent Stuff Guys!!! Everyone is putting their part. Great to see this kind of community flourish further. I am thankful to the ppl who started this website. Reply 28 Daniel Vieceli March 13, 2012 at 2:38 pm Excellent thanks. Reply 29 jm April 1, 2012 at 3:48 am Good info and well written.Easy to understand for everyone… I will be back to learn more needed security rules.. Oh and yes I’m a human but I hate to say the definition of human is ( MONSTER) don’t believe me ? Look it up on the net ! Ha ha ha ha Thank you for this page…. Reply 30 rw1 April 5, 2012 at 7:45 am thank you! for the information on how to delete a firewall rule! priceless! thanks! Reply 31 Eli May 11, 2012 at 12:19 am How can i use iptable rules to use multiple internet connections for the same bit torrent download? Actually, i have two broadband connections. I want to combine them. I am told to get load balancing hardware and i cant afford that. So, i did some experimenting. On first DSL modem, i set its IP to be 192.168.1.1 On second modem, i set its IP to be 192.168.2.1 Then in windows network adapter settings, i set Metric value of each adapter to 1. Thats about it. My bit torrent downloads/uploads use both my internet connections at the same time which gives effect of combined speed. Can i do something like that in Linux? Or, how can i combine two internet connections by using iptables? I dont want any hardware changes. All i have is two DSL modems and two network interface cards. Precise help would be greatly appreciated. Reply 32 kolya May 13, 2012 at 6:55 pm Hi, got a question to the author of the article. I have tried different kind of commands from the command line, edited the file /etc/sysconfig/iptables directly with following saving and restarting iptables/rebooting system. Nothing helps, my rules get overwritten by the system flushing my new rules or editing them. I tried to open ports (22,21 etc). The goal why I edit my firewall is to get connected to ftp server via FileZilla. Would you recommend me how to open ports? Tell me please if you need any system outputs or something. Cheers Reply 33 nixCraft May 13, 2012 at 8:35 pm > my rules get overwritten by the system flushing my new rules or editing them I think you got some sort of script or other firewall product running that is overwriting your rules. Check your cron job and you find the source for the same. If you need further assistance head over to the nixcraft Linux Support forum. Reply 34 kolya May 14, 2012 at 12:21 pm thanks for your respond, as I am not a specialist I didn’t any changes to my crontab yet, anyway I checked it, also /cron.d and everything connected to cron in /var/spool/…. Nothing about iptables or something. What I noticed there are several iptables files in /etc/sysconfig/: iptables.old written by system-config-firewall, iptables generated by iptables-save with some changes what I didn’t entered. Here is what I entered from wiki.centos.org/HowTos/Network/IPTables: # iptables -P INPUT ACCEPT # iptables -F # iptables -A INPUT -i lo -j ACCEPT # iptables -A INPUT -m state –state ESTABLISHED,RELATED -j ACCEPT # iptables -A INPUT -p tcp –dport 22 -j ACCEPT # iptables -P INPUT DROP # iptables -P FORWARD DROP # iptables -P OUTPUT ACCEPT # iptables -L -v Here is what I got in the iptables’s file: :INPUT DROP [1:40] :FORWARD DROP [0:0] :OUTPUT ACCEPT [526:43673] -A INPUT -i lo -j ACCEPT -A INPUT -m state –state RELATED,ESTABLISHED -j ACCEPT -A INPUT -p tcp -m tcp –dport 22 -j ACCEPT COMMIT Don’t know why it changes, probably it is aplying kind of default settings, but analyzing this settings the port 22 should be open. Nmap says it is closed, telnet outputs connection refused. Was trying to set samba server with the same result due to my firewall. What to do? Reply 35 Sigma May 25, 2012 at 6:53 am Thanks a lot for this article, which is extremely easy to understand and follow for beginners as me! Reply 36 dima June 9, 2012 at 10:38 am Hi Regarding the block #7.1: Only Block Incoming Traffic The rule # iptables -A INPUT -m state –state NEW,ESTABLISHED -j ACCEPT looks dubious to me Why would you want to allow NEW connections? In my view it should read # iptables -A INPUT -m state –state RELATED,ESTABLISHED -j ACCEPT Reply 37 qubits4all February 2, 2013 at 8:08 am I noticed this as well. The rule as given is not right. I’ve been using iptables for a couple of years now, and the INPUT rule here should read: iptables -A INPUT -m state –state ESTABLISHED,RELATED (actually the above order is equivalent), because one clearly wouldn’t want to match the NEW state here. Doing so would open up the door to TCP connects (i.e., TCP SYN packets) to any listening TCP services, as well as to UDP datagrams. Cheers to the author(s) of nixCraft for a nice article & a useful collection of iptables rules. This has become one of my favorite Linux/Unix blogs, so please keep the articles coming. Reply 38 BiBi June 21, 2012 at 3:24 am Thank you very much, this site is very useful. I love all of you. Reply 39 Juan July 14, 2012 at 1:53 pm Hi. Excellent tutorial. My desire is to block social networking in my job, I did it with squid in transparent mode but skipped to enter https. I did the tests on a virtual pc and it worked fine. The issue is that I is working on the production server. This has two network cards, eth0 traffic where it enters the Internet and eth1 to connect to the network. For the case of Facebook do the following: # We block Facebook iptables-A OUTPUT-p tcp-d 69.63.176.0/20-dport 443-j DROP iptables-A OUTPUT-p tcp-d 66.220.144.0/20-dport 443-j DROP iptables-A OUTPUT-p tcp-d 69.171.224.0/19-dport 443-j DROP iptables-A OUTPUT-p tcp-d http://www.facebook.com-dport 443-j DROP iptables-A OUTPUT-p tcp-d facebook.com-dport 443-j DROP Any suggestions?. Greetings. Reply 40 jaydatt August 30, 2012 at 10:47 am really helpful article Reply 41 Borislav Bozhanov September 11, 2012 at 11:13 pm Hi, Here is how to BLOCK FACEBOOK with single line command and iptables: for i in $(nslookup facebook.com|grep Address|grep -v “#53″|awk ‘{print $2}’); do iptables -I FORWARD -m tcp -p tcp -d $i/24 –dport 443 -j DROP; done You can replace the website with any other secure (https) you want. For http websites (non-secure) – use the following line, replacing yahoo.com with the desired domain name: for i in $(nslookup yahoo.com|grep Address|grep -v “#53″|awk ‘{print $2}’); do iptables I FORWARD -m tcp -p tcp -d $i/24 –dport 80 -j DROP; done Don’t forget to save your iptables configuration. Regards, Borislav Bozhanov Reply 42 Łukasz Bodziony September 13, 2012 at 7:37 pm Thank you!!! Reply 43 Gus September 29, 2012 at 6:51 pm Hello. I’m working with virtual machines. and would like to make a firewall and rootin bash. My question is this I have several public ip — IP1 = (200.45.xx.xxx) IP2 (=200.xx), IP3 = · The issue is that one of them use to Wan IP1. Now I want to direct traffic from outside to inside. But I also want to redirect the traffic that comes to public ip 2 ( IP2 to the local machine in lan ( 192.168.1.2) and what comes to public ip 3 (IP3) to the local machine (192.168.1.3) I can not find examples of how to redirect traffic coming to a specific public IP to a particular LAN private IP. If you can ask to help me. #!/bin/sh ## SCRIPT de IPTABLES ## Pello Xabier Altadill Izura echo -n Aplicando Reglas de Firewall... ## Paramos el ipchains y quitamos el modulo /etc/rc.d/init.d/firewall stop rmmod ipchains ## Instalando modulos modprobe ip_tables modprobe ip_nat_ftp modprobe ip_conntrack_ftp ## Variables IPTABLES=iptables EXTIF="eth1" INTIF="eth0" ## En este caso, ## la tarjeta eth1 es la que va al ROUTER y la eth0 la de la LAN ## Primeras reglas /sbin/iptables -P INPUT DROP /sbin/iptables -F INPUT /sbin/iptables -P OUTPUT ACCEPT /sbin/iptables -F OUTPUT /sbin/iptables -P FORWARD ACCEPT /sbin/iptables -F FORWARD /sbin/iptables -t nat -F ### En principio, si las reglas INPUT por defecto hacen DROP, no haria falta ### meter mas reglas, pero si temporalmente se pasa a ACCEPT no esta de mas. ## Todo lo que viene de cierta IP se deja pasar (administradores remotos…) /sbin/iptables -A INPUT -i $EXTIF -s 203.175.34.0/24 -d 0.0.0.0/0 -j ACCEPT ## El localhost se deja /sbin/iptables -A INPUT -i lo -j ACCEPT /sbin/iptables -A OUTPUT -o lo -j ACCEPT ## Aceptar al exterior al 80 y al 443 # Permitir salida al 80 /sbin/iptables -A INPUT -i $EXTIF -p tcp --sport 80 -j ACCEPT /sbin/iptables -A OUTPUT -o $EXTIF -p tcp --dport 80 -j ACCEPT # Permitir salida al 443 /sbin/iptables -A INPUT -i $EXTIF -p tcp --sport 443 -j ACCEPT /sbin/iptables -A OUTPUT -o $EXTIF -p tcp --dport 443 -j ACCEPT ## SALIDA SMTP - Para que el servidor se pueda conectar a otros MTA # Permitir salida SMTP /sbin/iptables -A INPUT -i $EXTIF -p tcp --sport 25 -j ACCEPT /sbin/iptables -A OUTPUT -o $EXTIF -p tcp --dport 25 -j ACCEPT ## SALIDA FTP - Para que el servidor se pueda conectar a FTPs /sbin/iptables -A INPUT -i $EXTIF -p tcp --sport 21 -m state --state ESTABLISHED -j ACCEPT /sbin/iptables -A OUTPUT -o $EXTIF -p tcp --dport 21 -m state --state NEW,ESTABLISHED -j ACCEPT # ftp activo /sbin/iptables -A INPUT -i $EXTIF -p tcp --sport 20 -m state --state ESTABLISHED,RELATED -j ACCEPT /sbin/iptables -A OUTPUT -o $EXTIF -p tcp --dport 20 -m state --state ESTABLISHED -j ACCEPT # ftp pasivo /sbin/iptables -A INPUT -i $EXTIF -p tcp --sport 1024:65535 --dport 1024:65535 -m state --state ESTABLISHED -j ACCEPT /sbin/iptables -A OUTPUT -o $EXTIF -p tcp --sport 1024:65535 --dport 1024:65535 -m state --state ESTABLISHED,RELATED -j ACCEPT Reply 44 Rogier October 23, 2012 at 5:48 am Hi, I have two interfaces: eth0 (for internal network) and eth1 (WAN). The server does the routing to the clients with the following IPtables: # Generated by iptables-save v1.4.12 on Fri Oct 19 21:14:26 2012 *nat :PREROUTING ACCEPT [14:1149] :INPUT ACCEPT [6:625] :OUTPUT ACCEPT [4:313] :POSTROUTING ACCEPT [0:0] -A POSTROUTING -o eth1 -j MASQUERADE COMMIT # Completed on Fri Oct 19 21:14:26 2012 # Generated by iptables-save v1.4.12 on Fri Oct 19 21:14:26 2012 *filter :INPUT ACCEPT [505:53082] :FORWARD ACCEPT [0:0] :OUTPUT ACCEPT [247:29622] -A FORWARD -s 192.168.1.0/24 -i eth0 -o eth1 -m conntrack --ctstate NEW -j ACCEPT -A FORWARD -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT COMMIT # Completed on Fri Oct 19 21:14:26 2012 This works fine, however I have no other rules set up. Can anyone help me in deciding what rules I need? the server (who does the NAT) is also running a webserver on port 80, SSH server on 22. All other ports can may be blocked.. how can I achieve this? Reply 45 Jorge Robles October 24, 2012 at 2:37 pm I use fwbuilder to create my rules, this interface “looks like” checkpoint’s fw1 client to edit rules. Very graphical, and good to work with. Reply 46 sahil November 8, 2012 at 10:14 am very nice and informative article it really helped to work for my VPS server Reply 47 bussy November 9, 2012 at 8:09 pm how i do give access ip ex 192.168.0.2 only for facebook . Reply 48 Sayajin December 19, 2012 at 7:27 am fb_address=$(dig facebook.com +tcp +short); iptables -A OUTPUT -p tcp -s !192.168.0.2/32 -d $fb_address -j DROP; Reply 49 bahathir November 25, 2012 at 3:17 am For tip #2, it is advisable to run the -P chain ACCEPt first, before flushing it. Exampes # iptables -P INPUT ACCEPT # iptables -P OUTPUT ACCEPT # iptables -P FORWARD ACCEPT # iptables -F # iptables -t nat -F # iptables -X #iptables -t nat -X Why? If the current chain’s policy is DROP, and you are remotely accessing to the server via SSH, and the rule “-A INPUT -p tcp –dport 22 -j ACCEPT” is still opens the “-P INPUT DROP”. you may disconnected as soon as you flush *-F* the rules, and the default policy “-P INPUT DROP” kicks in. :) If you are working on the local console, it is fine. Thank you. Reply 50 qubits4all February 2, 2013 at 8:34 am This is a valid point. Another way to avoid locking oneself out, which I have found very useful for testing firewall changes over an SSH session, is the iptables-apply command (incl. with the Ubuntu iptables package for e.g.). It functions essentially the same as the iptables command, but when applying a rule change it prompts w/ a timeout for a confirmation after making the change. If no response is received (in 30 secs. by default), then it rolls back the change (i.e., add, modify, delete or otherwise). Once rules have been tested, I save them with iptables-save, and load the stable configuration with an init.d script at system startup (and including support for a ‘restart’ command here, for a clean flush, delete & reapply rules cycle). Reply 51 levi November 27, 2012 at 4:24 am Could it be you are using iptables save after directly editing? This will overwrite your work. Do a restart to load your newly edited table. Reply 52 KeepEnEmUp December 8, 2012 at 2:32 am Great Thx for awesome site and for awesome reading,tutos. Respect And KeepUp dude! Reply 53 rashid Iqbal December 13, 2012 at 11:43 am from graphical user and groups If I add or delete any user I can’t see any reference log nor in messages or in /var/log/secure file, Kindly please advise on this that from GUI if we run/execute any command where does the log message will go. Reply 54 Gangadhar February 27, 2013 at 2:50 pm thank you very much for such a wonderful explanation….. very clear and had nice experience with iptables… Reply 55 haidt March 10, 2013 at 9:04 am Hi there, i have a problem, i have got a server and LAN network, and this’s feature internet (eth0) server (eth1) clients -> 10.0.0.2 -> 10.0.0.3 now, i can config to iptables accept all client connect internet, but in this situation, i want to allow only one client (assume: 10.0.0.3), i try but not completed. pls help me :) Thanks Reply 56 Manish Narnaware April 24, 2013 at 5:33 am Thanks a lot. Reply 57 Orange April 25, 2013 at 11:08 pm Thank you very much. Coincidentally, I just discovered an hour ago that I need to use iptables to allow a tablet computer to talk through my laptop, using the same internet connection. And then I discovered that I can’t remember any of it. I was using IP tables and IP nat 15 years ago, back when it was Darrin Reed’s project (name???), but that was too long ago for my memory. This article will get me back on track fast. Thanks again. Reply 58 Le Vu May 29, 2013 at 8:23 am Module xt_connlimit was disabled. How to limit number of connection per IP, can you module limit and recent. Please help me. :) Reply 59 abedatwa June 13, 2013 at 7:08 am thank you Reply 60 abedatwa June 13, 2013 at 7:09 am thank you for you ivitation Reply 61 Mark August 1, 2013 at 1:33 pm Thank you for this example. I don’t remember the command line off the top of my head and this gives me enough information to do what I need to do without having to read 30 man pages. If only proper support (support.oracle.com) would be so efficient. Reply 62 paul August 3, 2013 at 1:29 am Enjoyed and appreciated the article and the comments particularly from noone (13 December 2011). I’ve added some of the suggestions to my firewalls. The first lines in every INPUT are always -A INPUT -s 123.123.123.123/32 -j ACCEPT -A INPUT -s 124.124.124.124/32 -j ACCEPT 123 & 124 represent my external IPs including home and office backup connections. These entries ensure that whatever errors I make in IPTables I can never lock myself out of my remote servers. Best regards to all, Paul. Reply 63 John August 21, 2013 at 2:40 am In 7.1, the example provided does not block all incoming traffic like it claims. If you don’t add more parameters, the rule will apply to both directions. The example rule: iptables -I INPUT -m state –state NEW,ESTABLISHED -j ACCEPT This would not only allow for NEW outgoing requests but also NEW incoming requests. The DROP policy for the INPUT chain can’t do it’s job to block incoming connections since it is applied after the rule which allows both NEW incoming and outgoing connections. Reply 64 sophea October 30, 2013 at 8:53 am I have problem when i add by manually (ex: #iptables -A INPUT -s 192.168.0.1 -p tcp – dport 53 -j ACCEP) but when i restart iptables by service iptables restart it not work because : 1- when i view in /etc/sysconfig/iptables the IP address will be 192.168.0.1/32 but my land /24 2- problem when i start or stop by system-config-firewall Can u help me pls? Reply 65 Mohammad February 27, 2014 at 3:38 pm Hi, I have a question. Could we log packets which are dropped because of forwarding queue is filled (e.g in congestion time)? How do I perform this work? Regards Mohammad. Reply Leave a Comment Name * E-mail * Notify me of followup comments via e-mail. 1. Technology Linux Linux Get Started Explore Linux Become a Guru Share Print Ads: Port Scan Linux Download Linux PC FTP Command Linux Desktop Linux / Unix Command: iptables Command Library Ads Used Cars from Be Forwardbeforward.jpStart From $499, Stock Daily 15000+ No1 UsedCars Exporter Best UsedCars NAME iptables - administration tool for IPv4 packet filtering and NAT SYNOPSIS iptables [-t table] -[ADC] chain rule-specification [options] iptables [-t table] -I chain [rulenum] rule-specification [options] iptables [-t table] -R chain rulenum rule-specification [options] iptables [-t table] -D chain rulenum [options] iptables [-t table] -[LFZ] [chain] [options] iptables [-t table] -N chain iptables [-t table] -X [chain] iptables [-t table] -P chain target [options] iptables [-t table] -E old-chain-name new-chain-name DESCRIPTION Iptables is used to set up, maintain, and inspect the tables of IP packet filter rules in the Linux kernel. Several different tables may be defined. Each table contains a number of built-in chains and may also contain user-defined chains. Each chain is a list of rules which can match a set of packets. Each rule specifies what to do with a packet that matches. This is called a `target', which may be a jump to a user-defined chain in the same table. TARGETS A firewall rule specifies criteria for a packet, and a target. If the packet does not match, the next rule in the chain is the examined; if it does match, then the next rule is specified by the value of the target, which can be the name of a user-defined chain or one of the special values ACCEPT, DROP, QUEUE, or RETURN. ACCEPT means to let the packet through. DROP means to drop the packet on the floor. QUEUE means to pass the packet to userspace (if supported by the kernel). RETURN means stop traversing this chain and resume at the next rule in the previous (calling) chain. If the end of a built-in chain is reached or a rule in a built-in chain with target RETURN is matched, the target specified by the chain policy determines the fate of the packet. TABLES There are currently three independent tables (which tables are present at any time depends on the kernel configuration options and which modules are present). -t, --table table This option specifies the packet matching table which the command should operate on. If the kernel is configured with automatic module loading, an attempt will be made to load the appropriate module for that table if it is not already there. The tables are as follows: filter This is the default table (if no -t option is passed). It contains the built-in chains INPUT (for packets coming into the box itself), FORWARD (for packets being routed through the box), and OUTPUT (for locally-generated packets). nat This table is consulted when a packet that creates a new connection is encountered. It consists of three built-ins: PREROUTING (for altering packets as soon as they come in), OUTPUT (for altering locally-generated packets before routing), and POSTROUTING (for altering packets as they are about to go out). mangle This table is used for specialized packet alteration. Until kernel 2.4.17 it had two built-in chains: PREROUTING (for altering incoming packets before routing) and OUTPUT (for altering locallygenerated packets before routing). Since kernel 2.4.18, three other built-in chains are also supported: INPUT (for packets coming into the box itself), FORWARD (for altering packets being routed through the box), and POSTROUTING (for altering packets as they are about to go out). OPTIONS The options that are recognized by iptables can be divided into several different groups. COMMANDS These options specify the specific action to perform. Only one of them can be specified on the command line unless otherwise specified below. For all the long versions of the command and option names, you need to use only enough letters to ensure that iptables can differentiate it from all other options. -A, --append chain rule-specification Append one or more rules to the end of the selected chain. When the source and/or destination names resolve to more than one address, a rule will be added for each possible address combination. -D, --delete chain rule-specification -D, --delete chain rulenum Delete one or more rules from the selected chain. There are two versions of this command: the rule can be specified as a number in the chain (starting at 1 for the first rule) or a rule to match. -I, --insert chain [rulenum] rule-specification Insert one or more rules in the selected chain as the given rule number. So, if the rule number is 1, the rule or rules are inserted at the head of the chain. This is also the default if no rule number is specified. -R, --replace chain rulenum rule-specification Replace a rule in the selected chain. If the source and/or destination names resolve to multiple addresses, the command will fail. Rules are numbered starting at 1. -L, --list [chain] List all rules in the selected chain. If no chain is selected, all chains are listed. As every other iptables command, it applies to the specified table (filter is the default), so NAT rules get listed by iptables -t nat -n -L Please note that it is often used with the -n option, in order to avoid long reverse DNS lookups. It is legal to specify the -Z (zero) option as well, in which case the chain(s) will be atomically listed and zeroed. The exact output is affected by the other arguments given. The exact rules are suppressed until you use iptables -L -v -F, --flush [chain] Flush the selected chain (all the chains in the table if none is given). This is equivalent to deleting all the rules one by one. -Z, --zero [chain] Zero the packet and byte counters in all chains. It is legal to specify the -L, --list (list) option as well, to see the counters immediately before they are cleared. (See above.) -N, --new-chain chain Create a new user-defined chain by the given name. There must be no target of that name already. -X, --delete-chain [chain] Delete the optional user-defined chain specified. There must be no references to the chain. If there are, you must delete or replace the referring rules before the chain can be deleted. If no argument is given, it will attempt to delete every non-builtin chain in the table. -P, --policy chain target Set the policy for the chain to the given target. See the section TARGETS for the legal targets. Only built-in (non-user-defined) chains can have policies, and neither built-in nor user-defined chains can be policy targets. -E, --rename-chain old-chain new-chain Rename the user specified chain to the user supplied name. This is cosmetic, and has no effect on the structure of the table. -h Help. Give a (currently very brief) description of the command syntax. PARAMETERS The following parameters make up a rule specification (as used in the add, delete, insert, replace and append commands). -p, --protocol [!] protocol The protocol of the rule or of the packet to check. The specified protocol can be one of tcp, udp, icmp, or all, or it can be a numeric value, representing one of these protocols or a different one. A protocol name from /etc/protocols is also allowed. A "!" argument before the protocol inverts the test. The number zero is equivalent to all. Protocol all will match with all protocols and is taken as default when this option is omitted. -s, --source [!] address[/mask] Source specification. Address can be either a network name, a hostname (please note that specifying any name to be resolved with a remote query such as DNS is a really bad idea), a network IP address (with /mask), or a plain IP address. The mask can be either a network mask or a plain number, specifying the number of 1's at the left side of the network mask. Thus, a mask of 24 is equivalent to 255.255.255.0. A "!" argument before the address specification inverts the sense of the address. The flag --src is an alias for this option. -d, --destination [!] address[/mask] Destination specification. See the description of the -s (source) flag for a detailed description of the syntax. The flag --dst is an alias for this option. -j, --jump target This specifies the target of the rule; i.e., what to do if the packet matches it. The target can be a user-defined chain (other than the one this rule is in), one of the special builtin targets which decide the fate of the packet immediately, or an extension (see EXTENSIONS below). If this option is omitted in a rule, then matching the rule will have no effect on the packet's fate, but the counters on the rule will be incremented. -i, --in-interface [!] name Name of an interface via which a packet is going to be received (only for packets entering the INPUT, FORWARD and PREROUTING chains). When the "!" argument is used before the interface name, the sense is inverted. If the interface name ends in a "+", then any interface which begins with this name will match. If this option is omitted, any interface name will match. -o, --out-interface [!] name Name of an interface via which a packet is going to be sent (for packets entering the FORWARD, OUTPUT and POSTROUTING chains). When the "!" argument is used before the interface name, the sense is inverted. If the interface name ends in a "+", then any interface which begins with this name will match. If this option is omitted, any interface name will match. [!] -f, --fragment This means that the rule only refers to second and further fragments of fragmented packets. Since there is no way to tell the source or destination ports of such a packet (or ICMP type), such a packet will not match any rules which specify them. When the "!" argument precedes the "-f" flag, the rule will only match head fragments, or unfragmented packets. -c, --set-counters PKTS BYTES This enables the administrator to initialize the packet and byte counters of a rule (during INSERT, APPEND, REPLACE operations). OTHER OPTIONS The following additional options can be specified: -v, --verbose Verbose output. This option makes the list command show the interface name, the rule options (if any), and the TOS masks. The packet and byte counters are also listed, with the suffix 'K', 'M' or 'G' for 1000, 1,000,000 and 1,000,000,000 multipliers respectively (but see the -x flag to change this). For appending, insertion, deletion and replacement, this causes detailed information on the rule or rules to be printed. -n, --numeric Numeric output. IP addresses and port numbers will be printed in numeric format. By default, the program will try to display them as host names, network names, or services (whenever applicable). -x, --exact Expand numbers. Display the exact value of the packet and byte counters, instead of only the rounded number in K's (multiples of 1000) M's (multiples of 1000K) or G's (multiples of 1000M). This option is only relevant for the -L command. --line-numbers When listing rules, add line numbers to the beginning of each rule, corresponding to that rule's position in the chain. --modprobe=command When adding or inserting rules into a chain, use command to load any necessary modules (targets, match extensions, etc). MATCH EXTENSIONS iptables can use extended packet matching modules. These are loaded in two ways: implicitly, when -p or --protocol is specified, or with the -m or --match options, followed by the matching module name; after these, various extra command line options become available, depending on the specific module. You can specify multiple extended match modules in one line, and you can use the -h or --help options after the module has been specified to receive help specific to that module. The following are included in the base package, and most of these can be preceded by a ! to invert the sense of the match. tcp These extensions are loaded if `--protocol tcp' is specified. It provides the following options: --source-port [!] port[:port] Source port or port range specification. This can either be a service name or a port number. An inclusive range can also be specified, using the format port:port. If the first port is omitted, "0" is assumed; if the last is omitted, "65535" is assumed. If the second port greater then the first they will be swapped. The flag --sport is a convenient alias for this option. --destination-port [!] port[:port] Destination port or port range specification. The flag --dport is a convenient alias for this option. --tcp-flags [!] mask comp Match when the TCP flags are as specified. The first argument is the flags which we should examine, written as a comma-separated list, and the second argument is a comma-separated list of flags which must be set. Flags are: SYN ACK FIN RST URG PSH ALL NONE. Hence the command iptables -A FORWARD -p tcp --tcp-flags SYN,ACK,FIN,RST SYN will only match packets with the SYN flag set, and the ACK, FIN and RST flags unset. [!] --syn Only match TCP packets with the SYN bit set and the ACK and FIN bits cleared. Such packets are used to request TCP connection initiation; for example, blocking such packets coming in an interface will prevent incoming TCP connections, but outgoing TCP connections will be unaffected. It is equivalent to --tcp-flags SYN,RST,ACK SYN. If the "!" flag precedes the "--syn", the sense of the option is inverted. --tcp-option [!] number Match if TCP option set. --mss value[:value] Match TCP SYN or SYN/ACK packets with the specified MSS value (or range), which control the maximum packet size for that connection. udp These extensions are loaded if `--protocol udp' is specified. It provides the following options: --source-port [!] port[:port] Source port or port range specification. See the description of the --source-port option of the TCP extension for details. --destination-port [!] port[:port] Destination port or port range specification. See the description of the --destination-port option of the TCP extension for details. icmp This extension is loaded if `--protocol icmp' is specified. It provides the following option: --icmp-type [!] typename This allows specification of the ICMP type, which can be a numeric ICMP type, or one of the ICMP type names shown by the command iptables -p icmp -h mac --mac-source [!] address Match source MAC address. It must be of the form XX:XX:XX:XX:XX:XX. Note that this only makes sense for packets coming from an Ethernet device and entering the PREROUTING, FORWARD or INPUT chains. limit This module matches at a limited rate using a token bucket filter. A rule using this extension will match until this limit is reached (unless the `!' flag is used). It can be used in combination with the LOG target to give limited logging, for example. --limit rate Maximum average matching rate: specified as a number, with an optional `/second', `/minute', `/hour', or `/day' suffix; the default is 3/hour. --limit-burst number Maximum initial number of packets to match: this number gets recharged by one every time the limit specified above is not reached, up to this number; the default is 5. multiport This module matches a set of source or destination ports. Up to 15 ports can be specified. It can only be used in conjunction with -p tcp or -p udp. --source-ports port[,port[,port...]] Match if the source port is one of the given ports. The flag --sports is a convenient alias for this option. --destination-ports port[,port[,port...]] Match if the destination port is one of the given ports. The flag --dports is a convenient alias for this option. --ports port[,port[,port...]] Match if the both the source and destination ports are equal to each other and to one of the given ports. mark This module matches the netfilter mark field associated with a packet (which can be set using the MARK target below). --mark value[/mask] Matches packets with the given unsigned mark value (if a mask is specified, this is logically ANDed with the mask before the comparison). owner This module attempts to match various characteristics of the packet creator, for locally-generated packets. It is only valid in the OUTPUT chain, and even this some packets (such as ICMP ping responses) may have no owner, and hence never match. --uid-owner userid Matches if the packet was created by a process with the given effective user id. --gid-owner groupid Matches if the packet was created by a process with the given effective group id. --pid-owner processid Matches if the packet was created by a process with the given process id. --sid-owner sessionid Matches if the packet was created by a process in the given session group. --cmd-owner name Matches if the packet was created by a process with the given command name. (this option is present only if iptables was compiled under a kernel supporting this feature) state This module, when combined with connection tracking, allows access to the connection tracking state for this packet. --state state Where state is a comma separated list of the connection states to match. Possible states are INVALID meaning that the packet is associated with no known connection, ESTABLISHED meaning that the packet is associated with a connection which has seen packets in both directions, NEW meaning that the packet has started a new connection, or otherwise associated with a connection which has not seen packets in both directions, and RELATED meaning that the packet is starting a new connection, but is associated with an existing connection, such as an FTP data transfer, or an ICMP error. conntrack This module, when combined with connection tracking, allows access to more connection tracking information than the "state" match. (this module is present only if iptables was compiled under a kernel supporting this feature) --ctstate state Where state is a comma separated list of the connection states to match. Possible states are INVALID meaning that the packet is associated with no known connection, ESTABLISHED meaning that the packet is associated with a connection which has seen packets in both directions, NEW meaning that the packet has started a new connection, or otherwise associated with a connection which has not seen packets in both directions, and RELATED meaning that the packet is starting a new connection, but is associated with an existing connection, such as an FTP data transfer, or an ICMP error. SNAT A virtual state, matching if the original source address differs from the reply destination. DNAT A virtual state, matching if the original destination differs from the reply source. --ctproto proto Protocol to match (by number or name) --ctorigsrc [!] address[/mask] Match against original source address --ctorigdst [!] address[/mask] Match against original destination address --ctreplsrc [!] address[/mask] Match against reply source address --ctrepldst [!] address[/mask] Match against reply destination address --ctstatus [NONE|EXPECTED|SEEN_REPLY|ASSURED][,...] Match against internal conntrack states --ctexpire time[:time] Match remaining lifetime in seconds against given value or range of values (inclusive) dscp This module matches the 6 bit DSCP field within the TOS field in the IP header. DSCP has superseded TOS within the IETF. --dscp value Match against a numeric (decimal or hex) value [0-32]. --dscp-class DiffServ Class Match the DiffServ class. This value may be any of the BE, EF, AFxx or CSx classes. It will then be converted into it's according numeric value. pkttype This module matches the link-layer packet type. --pkt-type [unicast|broadcast|multicast] tos This module matches the 8 bits of Type of Service field in the IP header (ie. including the precedence bits). --tos tos The argument is either a standard name, (use iptables -m tos -h to see the list), or a numeric value to match. ah This module matches the SPIs in AH header of IPSec packets. --ahspi [!] spi[:spi] esp This module matches the SPIs in ESP header of IPSec packets. --espspi [!] spi[:spi] length This module matches the length of a packet against a specific value or range of values. --length length[:length] ttl This module matches the time to live field in the IP header. --ttl ttl Matches the given TTL value. unclean This module takes no options, but attempts to match packets which seem malformed or unusual. This is regarded as experimental. TARGET EXTENSIONS iptables can use extended target modules: the following are included in the standard distribution. LOG Turn on kernel logging of matching packets. When this option is set for a rule, the Linux kernel will print some information on all matching packets (like most IP header fields) via the kernel log (where it can be read with dmesg or syslogd(8)). This is a "non-terminating target", i.e. rule traversal continues at the next rule. So if you want to LOG the packets you refuse, use two separate rules with the same matching criteria, first using target LOG then DROP (or REJECT). --log-level level Level of logging (numeric or see syslog.conf(5)). --log-prefix prefix Prefix log messages with the specified prefix; up to 29 letters long, and useful for distinguishing messages in the logs. --log-tcp-sequence Log TCP sequence numbers. This is a security risk if the log is readable by users. --log-tcp-options Log options from the TCP packet header. --log-ip-options Log options from the IP packet header. MARK This is used to set the netfilter mark value associated with the packet. It is only valid in the mangle table. It can for example be used in conjunction with iproute2. --set-mark mark REJECT This is used to send back an error packet in response to the matched packet: otherwise it is equivalent to DROP so it is a terminating TARGET, ending rule traversal. This target is only valid in the INPUT, FORWARD and OUTPUT chains, and user-defined chains which are only called from those chains. The following option controls the nature of the error packet returned: --reject-with type The type given can be icmp-net-unreachable, icmp-host-unreachable, icmp-port-unreachable, icmp-proto-unreachable, icmp-net-prohibited or icmp-host-prohibited, which return the appropriate ICMP error message (port-unreachable is the default). The option tcp-reset can be used on rules which only match the TCP protocol: this causes a TCP RST packet to be sent back. This is mainly useful for blocking ident (113/tcp) probes which frequently occur when sending mail to broken mail hosts (which won't accept your mail otherwise). TOS This is used to set the 8-bit Type of Service field in the IP header. It is only valid in the mangle table. --set-tos tos You can use a numeric TOS values, or use iptables -j TOS -h to see the list of valid TOS names. MIRROR This is an experimental demonstration target which inverts the source and destination fields in the IP header and retransmits the packet. It is only valid in the INPUT, FORWARD and PREROUTING chains, and user-defined chains which are only called from those chains. Note that the outgoing packets are NOT seen by any packet filtering chains, connection tracking or NAT, to avoid loops and other problems. SNAT This target is only valid in the nat table, in the POSTROUTING chain. It specifies that the source address of the packet should be modified (and all future packets in this connection will also be mangled), and rules should cease being examined. It takes one type of option: --to-source ipaddr[-ipaddr][:port-port] which can specify a single new source IP address, an inclusive range of IP addresses, and optionally, a port range (which is only valid if the rule also specifies -p tcp or -p udp). If no port range is specified, then source ports below 512 will be mapped to other ports below 512: those between 512 and 1023 inclusive will be mapped to ports below 1024, and other ports will be mapped to 1024 or above. Where possible, no port alteration will occur. You can add several --to-source options. If you specify more than one source address, either via an address range or multiple --to-source options, a simple round-robin (one after another in cycle) takes place between these adresses. DNAT This target is only valid in the nat table, in the PREROUTING and OUTPUT chains, and user-defined chains which are only called from those chains. It specifies that the destination address of the packet should be modified (and all future packets in this connection will also be mangled), and rules should cease being examined. It takes one type of option: --to-destination ipaddr[-ipaddr][:port-port] which can specify a single new destination IP address, an inclusive range of IP addresses, and optionally, a port range (which is only valid if the rule also specifies -p tcp or -p udp). If no port range is specified, then the destination port will never be modified. You can add several --to-destination options. If you specify more than one destination address, either via an address range or multiple --to-destination options, a simple round-robin (one after another in cycle) load balancing takes place between these adresses. MASQUERADE This target is only valid in the nat table, in the POSTROUTING chain. It should only be used with dynamically assigned IP (dialup) connections: if you have a static IP address, you should use the SNAT target. Masquerading is equivalent to specifying a mapping to the IP address of the interface the packet is going out, but also has the effect that connections are forgotten when the interface goes down. This is the correct behavior when the next dialup is unlikely to have the same interface address (and hence any established connections are lost anyway). It takes one option: --to-ports port[-port] This specifies a range of source ports to use, overriding the default SNAT source port-selection heuristics (see above). This is only valid if the rule also specifies -p tcp or -p udp. REDIRECT This target is only valid in the nat table, in the PREROUTING and OUTPUT chains, and user-defined chains which are only called from those chains. It alters the destination IP address to send the packet to the machine itself (locally-generated packets are mapped to the 127.0.0.1 address). It takes one option: --to-ports port[-port] This specifies a destination port or range of ports to use: without this, the destination port is never altered. This is only valid if the rule also specifies -p tcp or -p udp. ULOG This target provides userspace logging of matching packets. When this target is set for a rule, the Linux kernel will multicast this packet through a netlink socket. One or more userspace processes may then subscribe to various multicast groups and receive the packets. Like LOG, this is a "non-terminating target", i.e. rule traversal continues at the next rule. --ulog-nlgroup nlgroup This specifies the netlink group (1-32) to which the packet is sent. Default value is 1. --ulog-prefix prefix Prefix log messages with the specified prefix; up to 32 characters long, and useful for distinguishing messages in the logs. --ulog-cprange size Number of bytes to be copied to userspace. A value of 0 always copies the entire packet, regardless of its size. Default is 0. --ulog-qthreshold size Number of packet to queue inside kernel. Setting this value to, e.g. 10 accumulates ten packets inside the kernel and transmits them as one netlink multipart message to userspace. Default is 1 (for backwards compatibility). TCPMSS This target allows to alter the MSS value of TCP SYN packets, to control the maximum size for that connection (usually limiting it to your outgoing interface's MTU minus 40). Of course, it can only be used in conjunction with -p tcp. This target is used to overcome criminally braindead ISPs or servers which block ICMP Fragmentation Needed packets. The symptoms of this problem are that everything works fine from your Linux firewall/router, but machines behind it can never exchange large packets: 1) Web browsers connect, then hang with no data received. 2) Small mail works fine, but large emails hang. 3) ssh works fine, but scp hangs after initial handshaking. Workaround: activate this option and add a rule to your firewall configuration like: iptables -A FORWARD -p tcp --tcp-flags SYN,RST SYN \ -j TCPMSS --clamp-mss-to-pmtu --set-mss value Explicitly set MSS option to specified value. --clamp-mss-to-pmtu Automatically clamp MSS value to (path_MTU - 40). These options are mutually exclusive. DSCP This target allows to alter the value of the DSCP bits within the TOS header of the IPv4 packet. As this manipulates a packet, it can only be used in the mangle table. --set-dscp value Set the DSCP field to a numerical value (can be decimal or hex) --set-dscp-class class Set the DSCP field to a DiffServ class. ECN This target allows to selectively work around known ECN blackholes. It can only be used in the mangle table. --ecn-tcp-remove Remove all ECN bits from the TCP header. Of course, it can only be used in conjunction with -p tcp. SEE ALSO iptables-save(8), iptables-restore(8), ip6tables(8), ip6tables-save(8), ip6tables-restore(8). The packetfiltering-HOWTO details iptables usage for packet filtering, the NAT-HOWTO details NAT, the netfilterextensions-HOWTO details the extensions that are not in the standard distribution, and the netfilterhacking-HOWTO details the netfilter internals. See http://www.netfilter.org/. Important: Use the man command (% man) to see how a command is used on your particular computer. >> Linux/Unix Command Library >> Shell Command Library Related Articles tcpdump - Linux Command - Unix Command Linux Network Administrators Guide - 9.8.2. Using iptables Linux Network Administrators Guide - 9.7.2. ipchains Command Syntax Linux Network Administrators Guide - 9.7.5. Making Good Use of Chains Linux Network Administrators Guide - 9.7.5. Making Good Use of Chains Juergen Haas About.com Linux Sign up for My Newsletter Headlines Forum Free Linux Newsletter! Discuss in my forum Advertisement More from the WebSponsored Content by nRelate 3 Breast Cancer Signs You Didnt Know Existed Newsmax Health 12 Ways You Can Use the Bible as ... Money News are made: the ... Lexus International Unix Linux Log Free Linux Iptables Packet Explore Linux Must Reads Linux Desktop 101 Linux Glossary Linux Commands Shell Commands Linux Games Most Popular Enter the factory where Lexus dream cars Arthritis & Home Care Grisworld Homecare Ads: Top Investor Reveals unzip - Linux Command - Unix Command Example uses of the Linux Command zip top - Linux Command - Unix Command ls - Linux Command - Unix Command sudo - Linux Command - Unix Command Free Linux Newsletter! By Category Linux 101 Glossaries Linux HowTos Linux / Shell Commands Linux Distributions Linux Documentation Embedded Linux Linux Software Open Source Issues Linux / Tech News Linux Online Courses Linux 1. About.com 2. Technology 3. Linux Advertise on About.com Our Story News SiteMap All Topics Reprints Help Write for About Careers at About User Agreement Ethics Policy Patent Info. Privacy Policy Your Ad Choices and Cookie Policy ©2014 About.com. All rights reserved.