At a frist glance,iptables rules might look cryptic.
In this article,I will show you some examples which can be a basic templates for you to tweak to suit your specific requirement.
iptables -L -n -v-L, --list [chain]
List all rules in the selected chain.If no chain is selected,all chains are listed.Like every other iptables command,it applies to the specified table(filter is the default),so NAT rules get listed by
iptables -L -t nat -n
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
-n, --numeric
Numeric output.IP addresses and port numbers will be printed in numeric format.By default,the program wil l try to display them as host names,network names,or services(whenever appllicalbe).
As you can see above,-v show more information about the tables.
-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.-v may be specified multiple times to possibly emit more detailed debug statements.
-S, --list-rules [chain]
Print all rules in the selected chain.If no chain is selected,all chains are printed like iptables-save. Like every other iptables command,it applies to the specified table (filter is the default).
Before you start building new set of rules,you might want to clean-up all the default rules,and existing rules.Use the iptables flush command as shown below to do this.
iptables -F (or) iptables --flush
-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.
-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.The chain must be empty,i.e. not contain any rules.If no argument is given,it will attempt to delete every non-builtin chain in the table.
-D, --delete chain rulenum
-D, --delete chain rule-specification
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.
-Z, --zero [chain [rulenum]]
Zero the packet and byte counters in all chains ,or only the given chain, or only the given rule in a chain.It is legal to specify the -L, --list(list) option as well,to see the counters immediately before they are cleared.
As you can see above,-Z and -v can show you the detailed process.
-P, --policy chain target
Set the policy for the chain to the given target.See the section TARGETS for the local targets.Only built-in (non-user-defined) chains can have policies,and neither built-in nor user-defined chains can be policy targets.
The default chain policy is ACCEPT.Change this to DROP for all INPUT,FORWARD,and OUTPUT chains as shown below.
iptables -P INPUT DROP iptables -P FORWARD DROP iptables -P OUTPUT DROP
iptables -n -L -v --line-numbers--line-numbers
when listing rules,add line numbers to the beginning of each rule,corresponding to that rule's position in the chain.
You can use line numbers to delete or insert new rules into the firewall.
Before you insert a rule into a chain,you always should know whether the rule matching the specification exist in the chain or not.
-C, --check chain rule-specification
Check whether a rule matching the specification does exist in the selected chain.This command uses the same logic as -D to find a matching entry,but does not alter the existing iptables configuration and uses its exit code to indicate success or failure.
To insert one or more rules in the selected chain as the given rule number use the following syntax.
First find out line numbers
iptables -L INPUT -n --line-numbersTo insert rule between 1 and 2,namely,the insert position is before the number given in the command.
iptables -I INPUT 2 -s 202.54.1.2 -j DROP
-A, --append chain rule-sepcification
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.
-R, --replace chain rulenum rule-specification
Replace a rule in the selected chain.If the source and/or destination name resolve to multiple addresses,the command will fail.Rules are numbered starting at 1.
-N, --new-chain [chain]
Create a new user-defined chain by the given name.There must be no target of the name already.
You can create a new chain called NEWCHAIN by typing followed command:
iptables -N NEWCHAINYou can use the new chain as followed:
iptables -A INPUT -j NEWCHAIN
-E, --rename-chain
Rename the user specified chain to the user supplied name.This is cosmetic,and has no effect on the structure of the table.
iptables-save > rules iptable-restore < rules
A rule specification is made up by some parameters as shown below.
Note:rule specification can be used in the add,delete,insert,replace,append commands.
The protocol of the rule or of the packet to check.The specified protocol can be one of tcp,udp,udplite,icmp,esp,ah,sctp or the special keyword "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."all" will match with all protocols and is taken as default when this option is omitted.
Source specification.Address can be either a network name,a hostname,a network IP address (with /mask), or a plain IP address.Hostnames will be resolved once only,before the rule is submitted to the kernel.Please note that specifying any name to be resolved with a remote query such as DNS is a really bad idea.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 isequivalent 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.Multiple addresses can be specified,but this will expand to multiple rules(when adding with -A),or will cause multiple rules to be deleted (with -D).
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.
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.If this option is omitted in a rule(and -g is not used),then matching the rule will have no effect on the packet's fate,but the counters on rule will be incremented.
This specifies that the processing should continue in a user specified chain.Unlike the --jump option return will not continue processing in this chain but instead in the chain that called us via --jump.
Name of an interface via which a packet was 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 "+",the any interface which begins with this name will match.If this option is omitted,any interface name will match.
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 ommitted,any interface name will match.
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 port sof such a packet (or ICMP type),such a pakcet will not match any rules which specify them.Whe nthe "!" argument preceeds the "-f" flag,the rule will only match head fragments,or unfragmented packets.
This enables the administrator to initialize the packet and byte counters or a rule(during INSERT,APPEND,REPLACE operations).
When adding or inserting rules into a chain,use command to load any necessary modules(targets,match extensions,etc).
To drop all incoming/forwarded packets,but allow outgoing traffic
iptables -P INPUT DROP iptables -P FORWARD DROP iptables -P OUTPUT ACCEPT iptables -A INPUT -m state --state NEW,ESTABLISHED -j ACCEPT-m state(module name)
iptables can use extended packet matching modules 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.
--state state
where state is a comma separated list of the connection states to match.
Possible states:
INVALID meaning that the packet could not be identified for some reason which includes running out of memory and ICMP errors which don't correspond to any 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
RELATED meaning that the packet is starting a new connection,but is associated with an existing connecton,such as an FTP data transfer,or an ICMP error
UNTRACKED meaning that the packet is not tracked at all,which happens if you use the NOTRACK target in raw table
IP spoofing is nothing but to stop the following IPV4 address ranges for private networks on your public interfaces.Packets with non-routable source address 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 iptables -A INPUT -i eth1 -s 172.16.0.0/16 -j DROP iptables -A INPUT -i eth1 -s 224.0.0.0/4 -j DROP iptables -A INPUT -i eth1 -s 240.0.0.5/8 -j DROP iptables -A INPUT -i eth1 -s 127.0.0.0/8 -j DROP
To block an attacker ip address called 1.2.3.4
iptables -A INPUT -s 1.2.3.4 -j DROP
To block all requests from any interfaces on port 80
iptables -A INPUT -p tcp --dport 80 -j DROP
To block outgoing traffic to a particular host or domain such as www.baidu.com
host -t a www.cyberciti.biz www.cyberciti.biz has address 75.126.153.206
Note down its ip address and type the following to block all outgoing traffic to75.126.153.206
iptables -A OUTPUT -d 75.126.153.206 -j DROPAlso you can block an IP range
iptables -A OUTPUT -d 10.0.0.0/8 -j DROP
Type the following to log and block IP spoofing on public interface called eth1
iptables -A INPUT -i eth1 -s 192.168.2.0/24 -j LOG --log-prefix "IP_SPOOF A: " iptables -A INPUT -i eth1 -s 192.168.2.0/24 -j DROPBy default everything is logged to /var/log/messages file.
tail -f /var/log/messages grep --color 'IP SPOOF' /var/log/messages
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: "--limit rate[/second|/minute|/hour|/day]
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.
Use the following syntax:
iptables -A INPUT -m mac --mac-source 00:0F:EA:91:04:08 -j DROP iptables -A INPUT -p tcp --destination-port 22 -m mac --mac-source 00:0F:EA:91:04:07 -j ACCEPT
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
iptables -A INPUT -p icmp --icmp-type echo-request -s 192.168.2.0/24 -j DROPThe 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
Use the following syntax to open a range of ports:
iptables -A INPUT -m state --state NEW -m tcp -p tcp --dport 7000:7100 -j ACCEPT
Use the following syntax to open a range of IP addresses:
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
You can use connlimit module to put such restrictions.To allow 3 connections to tcp port 111 per host.
iptables -A INPUT -p tcp --syn --dport 111 -m connlimit --connlimit-above 3 -j REJECTSet HTTP requests to 20
iptables -A INPUT -p tcp --syn --dport 80 -m connlimit --connlimit-above 20 --connlimit-mask 24 -j DROP--connlimit-above
Match if the number of existing connections is above n.
--connlimit-mask
Group hosts using the prefix length.For IPV4,this must be a number between (including)0 and 32.For IPV6,between 0 and 128.If not specified,the maximum prefix length for the applicable protocol is used.
When you are allowing incoming connections from outside world to multiple ports,instead of writing individual rules for each and every port,you can combine them together using multiport extension as shown below.
The following example allows all incoming HTTP,HTTPS and SSH traffic.
iptables -A INPUT -i eth0 -p tcp -m multiport --dports 22,80,443 -m state --state NEW,ESTABLISHED -j ACCEPT iptables -A OUPUT -o eth0 -p tcp -m multiport --sports 22,80,443 -m state --state ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT iptables -A INPUT -i eth0 -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT
You can also load balance your incoming web traffic using iptables firewall rules.
This use the iptables nth extension.The following example load balances the HTTPS traffic to three different ip-address.For every 3th packet,it is load balanced to the appropriate server(using the counter 0).
iptables -A PREROUTING -i eth0 -p tcp --dport 443 -m state --state NEW -m nth --counter 0 --every 3 --packet 0 -j DNAT --to-destination 192.168.1.101:443 iptables -A PREROUTING -i eth0 -p tcp --dport 443 -m state --state NEW -m nth --counter 0 --every 3 --packet 1 -j DNAT --to-destination 192.168.1.102:443 iptables -A PREROUTING -i eth0 -p tcp --dport 443 -m state --state NEW -m nth --counter 0 --every 3 --packet 2 -j DNAT --to-destination 192.168.1.103:443