Traffic Control

Linux Iptables: How to specify a range of IP addresses or ports

Linux Iptables: How to specify a range of IP addresses or ports

Someone recently asked me a question:

How can I save time and script size by specifying a range of IP addresses or ports using iptables?

In old version of iptables IP address ranges are only valid in the nat table (see below for example). However newer version does support option that allows you to specify a range of IP addresses or ports for regular tables such as input.

Iptables set range of IP addresses

You need to use following options with match extensions (-m Ext).

iprange : This matches on a given arbitrary range of IPv4 addresses.

  • [!]--src-range ip-ip: Match source IP in the specified range.
  • [!]--dst-range ip-ip: Match destination IP in the specified range.


-m iprange --src-range IP-IP -j ACTION
-m iprange --dst-range IP-IP -j ACTION

For example, allow incoming request on a port 22 for source IP in the range only. You need to add something as follows to your iptables script:

iptables -A INPUT -p tcp --destination-port 22 -m iprange --src-range -j ACCEPT  

Port range

if --protocol tcp (-p tcp) is specified, you can specify source port range with following syntax:

  • --source-port port:port
  • --sport port:port

And destination port range specification with following option :

  • --destination-port port:port
  • --dport port:port

For example block lock all incoming ssh access at port 22, for source port range 513:65535:

iptables -A INPUT -p tcp -s 0/0 --sport 513:65535 -d --dport 22 -m state --state NEW,ESTABLISHED -j DROP

On the other hand, just allow incoming ssh request with following port range:

iptables -A INPUT -p tcp -s 0/0 -d --sport 513:65535 --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -p tcp -s -d 0/0 --sport 22 --dport 513:65535 -m state --state ESTABLISHED -j ACCEPT

NAT table - range option

If you are using NAT table use options --to-source and --to-destination. For example IP address range:

iptables -t nat -A POSTROUTING -j SNAT --to-source

ALTERNATIVELY, try range of ports:

iptables -t nat -A POSTROUTING -j SNAT --to-source

Read man page of iptables for more information.

Lighttpd Traffic Shaping: Throttle Connections Per Single IP (Rate Limit)

Lighttpd Traffic Shaping: Throttle Connections Per Single IP (Rate Limit)

Lignttpd: Limit All Connections

You can limit the throughput for all connections to the given limit in kbyte/s. Open lighttpd.conf file:
# vi lighttpd.conf
Set limit to 1024 kbyte/s:
Save and close the file. Reload lighttpd server:
# service lighttpd reload

Lighttpd: Limit Throughput For Each Single Connection

Set limit to 64 kbyte/s for each single connection per IP:
Reload lighttpd server:
# service lighttpd reload

How Do I Set a Limit Only For Virtual Host?

You can set limit for virtual host only as follows (limit traffic to to 64 kbyte/s:

$HTTP["host"] == "" {
server.kbytes-per-second = 64

How Do I Limit Connections Per Single IP?

You need to use a firewall such as *BSD PF or Linux netfilter firewall.

*BSD PF Firewall Example - Limit Connections Per Single IP

Add following rules to your /etc/pf.conf file. The following rules will protect the webserver against hosts making more than 100 connections in 10 seconds. Any IP which connects faster than this rate will have its address added to the table and have all states originating from it flushed. Any new packets from same IP to web server will be dropped:

table <abusive_ips> persist
block quick from <abusive_ips>
pass in on $ext_if proto tcp to $webserver_ip port www keep state (max-src-conn-rate 100/10, overload <bad_hosts> flush global)

Another example:

table <abusive_ips> persist
block in quick from <abusive_ips>
pass in on $ext_if proto tcp to $webserver_ip port www flags S/SA keep state (max-src-conn 100, max-src-conn-rate 15/5, overload <abusive_ips> flush)

Here is what it does:

  • Limits the maximum number of connections per source to 100 (some browsers can open 30-40 connections per IP, so keep this to 100)
  • Next, limit the number of connections per second or span of seconds. For e.g. rate limit the number of connections to 15 in a 5 second span.
  • If anyone breaks our rules add them to our abusive_ips table and block them for making any further connections.
  • Finally, flush keyword kills all states created by the matching rule which originate from the host which exceeds these limits.

Feel free to adjust settings as per your setup.

Linux Netfilter (Iptables) Examples To Limit Connections

The following example will drop incoming connections if IP make more than 10 connection attempts to port 80 within 100 seconds (add rules to your iptables shell script)

# Max connection in seconds
# Max connections per IP
# ....
# ..
# default action can be DROP or REJECT 
$IPT -I INPUT -p tcp --dport 80 -i eth0 -m state --state NEW -m recent --set
$IPT -I INPUT -p tcp --dport 80 -i eth0 -m state --state NEW -m recent --update --seconds ${SECONDS} --hitcount ${BLOCKCOUNT} -j ${DACTION}
# ....
# ..

Again, feel free to adjust settings as per your setup.

10 iptables rules to help secure your Linux box

The iptables tool is a magnificent means of securing a Linux box. But it can be rather overwhelming. Even after you gain a solid understanding of the command structure and know what to lock down and how to lock it down, iptables can be confusing. But the nice thing about iptables is that it’s fairly universal in its protection. So having a few iptables rules to put together into a script can make this job much easier.

With that in mind, let’s take a look at 10 such commands. Some of these rules will be more server oriented, whereas some will be more desktop oriented. For the purpose of this article, I’m not going to explain all of the various arguments and flags for iptables. Instead, I’ll just give you the rule and explain what it does. For more information on the specifics of the rule, you can read the man page for iptables, which will outline the arguments and flags for you.

1: iptables -A INPUT -p tcp -syn -j DROP

This is a desktop-centric rule that will do two things: First it will allow you to actually work normally on your desktop. All network traffic going out of your machine will be allowed out, but all TCP/IP traffic coming into your machine will simply be dropped. This makes for a solid Linux desktop that does not need any incoming traffic. What if you want to allow specific networking traffic in — for example, ssh for remote management? To do this, you’ll need to add an iptables rule for the service and make sure that service rule is run before rule to drop all incoming traffic.

2: iptables -A INPUT -p tcp –syn –destination-port 22 -j ACCEPT

Let’s build on our first command. To allow traffic to reach port 22 (secure shell), you will add this line. Understand that this line will allow any incoming traffic into port 22. This is not the most secure setup alone. To make it more secure, you’ll want to limit which machines can actually connect to port 22 on the machine. Fortunately, you can do this with iptables as well. If you know the IP address of the source machine, you can add the -s SOURCE_ADDRESS option (Where SOURCE_ADDRESS is the actual address of the source machine) before the –destination-port portion of the line.

3: /sbin/iptables -A INPUT -m state –state ESTABLISHED,RELATED -j ACCEPT

This will allow all previously initiated and accepted exchanges to bypass rule checking. The ESTABLISHED and RELATED arguments belong to the –state switch. The ESTABLISHED argument says, “Any packet that belongs to an existing connection,” and the RELATED argument says, “Any packet that does not belong to an already existing connection but is related to an existing connection.” The “state machine” of iptables is a means for iptables to track connections with the help of the kernel level “conntrack” module. By tracking connections, iptables knows what connections can be allowed and what can’t. This reduces the amount of work the administrator has to do.

Here’s how state works. If the local user initiates a connection, that packet (to that connection) is set as NEW in the prerouting chain. When the local user gets a return packet, the state is changed to ESTABLISHED in the prerouting chain. So when a state is set as ESTABLISHED, it can be allowed with the right iptables rule.

4: iptables -N LOGDROP

With this handy chain, iptables will log all dropped packets. Of course, this is only part of the chain. To complete it, you need to add the follow two rules: iptables -A logdrop -J LOG and iptables -A logdrop -J DROP. Now all matching packets (in this case, anything that has been dropped) will be added to the logdrop chain which will log them and then drop them.

5: iptables -t nat -A PREROUTING -i WLAN_INTERFACE -p tcp –dportPORTNUMBERS -j DNAT –to-destination DESTINATION_IP

When you need to route packets from external sources to specific ports on specific internal machines, this is what you want to do. This rule takes advantage of network address translation to route packets properly. To suit your needs, the WLAN_INTERFACE must be changed to the WLAN interface that bridges the external network to the internal network, the PORTNUMBERS must be changed, and DESTINATION_IP must be changed to match the IP address of the destination machine.

6: iptables -A INPUT -p tcp –syn –dport 25 -j ACCEPT

This is the beginning of a SYN flood protection rule. This portion of the rule blocks DoS attacks on a mail server port. (You can change this to suit your mail server needs.) There are three more portions of this rule set. The first is to add the same rule but modify the port to whatever is being served up by whatever ports you have open. The next portion is iptables -A INPUT -p tcp –syn -m limit –limit 1/s –limit-burst 4 -j ACCEPT, which is the actual SYN flood protection. Finally, iptables -A INPUT -p tcp –syn -j DROP will drop all SYN flood packets.

7: iptables -A INPUT -p tcp -m tcp -s MALICIOUS_ADDRESS -j DROP

This is where you can take care of malicious source IP addresses. For this to work properly, you must make sure you know the offending source IP address and that, in fact, it’s one you want to block. The biggest problem with this occurs when the offending address has been spoofed. If that’s the case, you can wind up blocking legitimate traffic from reaching your network. Do your research on this address.

8: iptables -N port-scan

This is the beginning of a rule to block furtive port scanning. A furtive port scan is a scan that detects closed ports to deduce open ports. Two more lines are needed to complete this rule:

iptables -A port-scan -p tcp --tcp-flags SYN,ACK,FIN,RST RST -m limit --limit 1/s -j RETURN
iptables -A port-scan -j DROP

Notice that the above rule set is adding a new chain called “port-scan”. You don’t have to name it such; it’s just easier to keep things organized. You can also add timeouts to the above rule set like so:

iptables -A specific-rule-set -p tcp --syn -j syn-flood
iptables -A specific-rule-set -p tcp --tcp-flags SYN,ACK,FIN,RST RST -j port-scan

9: iptables -A INPUT -i eth0 -p tcp -m state –state NEW -m multiport –dports ssh,smtp,http,https -j ACCEPT

What you see here is a chain making use of the multiport argument, which will allow you to set up multiple ports. Using the multiport argument lets you write one chain instead of multiple chains. This single rule saves you from writing out four separate rules, one each for ssh, smtp, http, and https. Naturally, you can apply this to ACCEPT, DENY, REJECT.

10: iptables -A PREROUTING -i eth0 -p tcp –dport 80 -m state –state NEW -m nth –counter 0 –every 4 –packet 0 -j DNAT –to-destination

If you’re looking to load balance between multiple mirrored servers (in the example case, load balancing a Web server at, this rule is what you want. At the heart of this rule is the nth extension, which tells iptables to act on every “nth” packet. In the example, iptables uses counter 0 and acts upon every 4th packet. You can extend this to balance out your mirrored sites this way. Say you have four mirrored servers up and you want to balance the load between them. You could have one line for each server like so:

iptables -A PREROUTING -i eth0 -p tcp --dport 80 -m state --state NEW -m nth --counter 0 --every 4 --packet 0 -j DNAT --to-destination
iptables -A PREROUTING -i eth0 -p tcp --dport 80 -m state --state NEW -m nth --counter 0 --every 4 --packet 1 -j DNAT --to-destination
iptables -A PREROUTING -i eth0 -p tcp --dport 80 -m state --state NEW -m nth --counter 0 --every 4 --packet 2 -j DNAT --to-destination
iptables -A PREROUTING -i eth0 -p tcp --dport 80 -m state --state NEW -m nth --counter 0 --every 4 --packet 3 -j DNAT --to-destination

As you can see the server on .10 will be routed every 0 packet, the server on .20 will be routed every 1st packet, the server on .30 will be routed every 2nd packet, and the server on .40 will be routed every 3rd packet.


Thanks. Ref :

DDoS Protection Script For iptables

  2. #!/bin/sh
  3. #------------------------------------------------------------------------------
  4. #
  5. # File:
  6. #
  7. # Compiler: Ruslan Abuzant <>
  8. #           PS> Collected From Lots Of Sources
  9. #           PS> Credits: Real Authors (no idea)
  10. #
  11. # URL:
  12. #
  13. # License: GNU GPL (version 2, or any later version).
  14. #
  15. # Configuration.
  16. #------------------------------------------------------------------------------
  18. # For debugging use iptables -v.
  19. IPTABLES="/sbin/iptables"
  20. IP6TABLES="/sbin/ip6tables"
  21. MODPROBE="/sbin/modprobe"
  22. RMMOD="/sbin/rmmod"
  23. ARP="/usr/sbin/arp"
  26. # Logging options.
  27. #------------------------------------------------------------------------------
  28. LOG="LOG --log-level debug --log-tcp-sequence --log-tcp-options"
  29. LOG="$LOG --log-ip-options"
  32. # Defaults for rate limiting
  33. #------------------------------------------------------------------------------
  34. RLIMIT="-m limit --limit 3/s --limit-burst 8"
  37. # Unprivileged ports.
  38. #------------------------------------------------------------------------------
  39. PHIGH="1024:65535"
  40. PSSH="1000:1023"
  43. # Load required kernel modules
  44. #------------------------------------------------------------------------------
  45. $MODPROBE ip_conntrack_ftp
  46. $MODPROBE ip_conntrack_irc
  49. # Mitigate ARP spoofing/poisoning and similar attacks.
  50. #------------------------------------------------------------------------------
  51. # Hardcode static ARP cache entries here
  55. # Kernel configuration.
  56. #------------------------------------------------------------------------------
  58. # Disable IP forwarding.
  59. # On => Off = (reset)
  60. echo 1 > /proc/sys/net/ipv4/ip_forward
  61. echo 0 > /proc/sys/net/ipv4/ip_forward
  63. # Enable IP spoofing protection
  64. for i in /proc/sys/net/ipv4/conf/*/rp_filter; do echo 1 > $i; done
  66. # Protect against SYN flood attacks
  67. echo 1 > /proc/sys/net/ipv4/tcp_syncookies
  69. # Ignore all incoming ICMP echo requests
  70. echo 0 > /proc/sys/net/ipv4/icmp_echo_ignore_all
  72. # Ignore ICMP echo requests to broadcast
  73. echo 1 > /proc/sys/net/ipv4/icmp_echo_ignore_broadcasts
  75. # Log packets with impossible addresses.
  76. for i in /proc/sys/net/ipv4/conf/*/log_martians; do echo 1 > $i; done
  78. # Don't log invalid responses to broadcast
  79. echo 1 > /proc/sys/net/ipv4/icmp_ignore_bogus_error_responses
  81. # Don't accept or send ICMP redirects.
  82. for i in /proc/sys/net/ipv4/conf/*/accept_redirects; do echo 0 > $i; done
  83. for i in /proc/sys/net/ipv4/conf/*/send_redirects; do echo 0 > $i; done
  85. # Don't accept source routed packets.
  86. for i in /proc/sys/net/ipv4/conf/*/accept_source_route; do echo 0 > $i; done
  88. # Disable multicast routing
  89. for i in /proc/sys/net/ipv4/conf/*/mc_forwarding; do echo 0 > $i; done
  91. # Disable proxy_arp.
  92. for i in /proc/sys/net/ipv4/conf/*/proxy_arp; do echo 0 > $i; done
  94. # Enable secure redirects, i.e. only accept ICMP redirects for gateways
  95. # Helps against MITM attacks.
  96. for i in /proc/sys/net/ipv4/conf/*/secure_redirects; do echo 1 > $i; done
  98. # Disable bootp_relay
  99. for i in /proc/sys/net/ipv4/conf/*/bootp_relay; do echo 0 > $i; done
  101. # Default policies.
  102. #------------------------------------------------------------------------------
  104. # Drop everything by default.
  109. # Set the nat/mangle/raw tables' chains to ACCEPT
  115. $IPTABLES -t mangle -P INPUT ACCEPT
  116. $IPTABLES -t mangle -P FORWARD ACCEPT
  117. $IPTABLES -t mangle -P OUTPUT ACCEPT
  120. # Cleanup.
  121. #------------------------------------------------------------------------------
  123. # Delete all
  124. $IPTABLES -F
  125. $IPTABLES -t nat -F
  126. $IPTABLES -t mangle -F
  128. # Delete all
  129. $IPTABLES -X
  130. $IPTABLES -t nat -X
  131. $IPTABLES -t mangle -X
  133. # Zero all packets and counters.
  134. $IPTABLES -Z
  135. $IPTABLES -t nat -Z
  136. $IPTABLES -t mangle -Z
  138. # Completely disable IPv6.
  139. #------------------------------------------------------------------------------
  141. # Block all IPv6 traffic
  142. # If the ip6tables command is available, try to block all IPv6 traffic.
  143. if test -x $IP6TABLES; then
  144. # Set the default policies
  145. # drop everything
  146. $IP6TABLES -P INPUT DROP 2>/dev/null
  147. $IP6TABLES -P FORWARD DROP 2>/dev/null
  148. $IP6TABLES -P OUTPUT DROP 2>/dev/null
  150. # The mangle table can pass everything
  151. $IP6TABLES -t mangle -P PREROUTING ACCEPT 2>/dev/null
  152. $IP6TABLES -t mangle -P INPUT ACCEPT 2>/dev/null
  153. $IP6TABLES -t mangle -P FORWARD ACCEPT 2>/dev/null
  154. $IP6TABLES -t mangle -P OUTPUT ACCEPT 2>/dev/null
  155. $IP6TABLES -t mangle -P POSTROUTING ACCEPT 2>/dev/null
  157. # Delete all rules.
  158. $IP6TABLES -F 2>/dev/null
  159. $IP6TABLES -t mangle -F 2>/dev/null
  161. # Delete all chains.
  162. $IP6TABLES -X 2>/dev/null
  163. $IP6TABLES -t mangle -X 2>/dev/null
  165. # Zero all packets and counters.
  166. $IP6TABLES -Z 2>/dev/null
  167. $IP6TABLES -t mangle -Z 2>/dev/null
  168. fi
  170. # Custom user-defined chains.
  171. #------------------------------------------------------------------------------
  173. # LOG packets, then ACCEPT.
  175. $IPTABLES -A ACCEPTLOG -j $LOG $RLIMIT --log-prefix "ACCEPT "
  178. # LOG packets, then DROP.
  180. $IPTABLES -A DROPLOG -j $LOG $RLIMIT --log-prefix "DROP "
  183. # LOG packets, then REJECT.
  184. # TCP packets are rejected with a TCP reset.
  186. $IPTABLES -A REJECTLOG -j $LOG $RLIMIT --log-prefix "REJECT "
  187. $IPTABLES -A REJECTLOG -p tcp -j REJECT --reject-with tcp-reset
  190. # Only allows RELATED ICMP types
  191. # (destination-unreachable, time-exceeded, and parameter-problem).
  192. # TODO: Rate-limit this traffic?
  193. # TODO: Allow fragmentation-needed?
  194. # TODO: Test.
  196. $IPTABLES -A RELATED_ICMP -p icmp --icmp-type destination-unreachable -j ACCEPT
  197. $IPTABLES -A RELATED_ICMP -p icmp --icmp-type time-exceeded -j ACCEPT
  198. $IPTABLES -A RELATED_ICMP -p icmp --icmp-type parameter-problem -j ACCEPT
  201. # Make It Even Harder To Multi-PING
  202. $IPTABLES  -A INPUT -p icmp -m limit --limit 1/s --limit-burst 2 -j ACCEPT
  203. $IPTABLES  -A INPUT -p icmp -m limit --limit 1/s --limit-burst 2 -j LOG --log-prefix PING-DROP:
  204. $IPTABLES  -A INPUT -p icmp -j DROP
  205. $IPTABLES  -A OUTPUT -p icmp -j ACCEPT
  207. # Only allow the minimally required/recommended parts of ICMP. Block the rest.
  208. #------------------------------------------------------------------------------
  210. # TODO: This section needs a lot of testing!
  212. # First, drop all fragmented ICMP packets (almost always malicious).
  213. $IPTABLES -A INPUT -p icmp --fragment -j DROPLOG
  214. $IPTABLES -A OUTPUT -p icmp --fragment -j DROPLOG
  215. $IPTABLES -A FORWARD -p icmp --fragment -j DROPLOG
  217. # Allow all ESTABLISHED ICMP traffic.
  218. $IPTABLES -A INPUT -p icmp -m state --state ESTABLISHED -j ACCEPT $RLIMIT
  219. $IPTABLES -A OUTPUT -p icmp -m state --state ESTABLISHED -j ACCEPT $RLIMIT
  221. # Allow some parts of the RELATED ICMP traffic, block the rest.
  222. $IPTABLES -A INPUT -p icmp -m state --state RELATED -j RELATED_ICMP $RLIMIT
  223. $IPTABLES -A OUTPUT -p icmp -m state --state RELATED -j RELATED_ICMP $RLIMIT
  225. # Allow incoming ICMP echo requests (ping), but only rate-limited.
  226. $IPTABLES -A INPUT -p icmp --icmp-type echo-request -j ACCEPT $RLIMIT
  228. # Allow outgoing ICMP echo requests (ping), but only rate-limited.
  229. $IPTABLES -A OUTPUT -p icmp --icmp-type echo-request -j ACCEPT $RLIMIT
  231. # Drop any other ICMP traffic.
  232. $IPTABLES -A INPUT -p icmp -j DROPLOG
  233. $IPTABLES -A OUTPUT -p icmp -j DROPLOG
  234. $IPTABLES -A FORWARD -p icmp -j DROPLOG
  236. # Selectively allow certain special types of traffic.
  237. #------------------------------------------------------------------------------
  239. # Allow loopback interface to do anything.
  240. $IPTABLES -A INPUT -i lo -j ACCEPT
  241. $IPTABLES -A OUTPUT -o lo -j ACCEPT
  243. # Allow incoming connections related to existing allowed connections.
  246. # Allow outgoing connections EXCEPT invalid
  249. # Miscellaneous.
  250. #------------------------------------------------------------------------------
  252. # We don't care about Milkosoft, Drop SMB/CIFS/etc..
  253. $IPTABLES -A INPUT -p tcp -m multiport --dports 135,137,138,139,445,1433,1434 -j DROP
  254. $IPTABLES -A INPUT -p udp -m multiport --dports 135,137,138,139,445,1433,1434 -j DROP
  256. # Explicitly drop invalid incoming traffic
  257. $IPTABLES -A INPUT -m state --state INVALID -j DROP
  259. # Drop invalid outgoing traffic, too.
  260. $IPTABLES -A OUTPUT -m state --state INVALID -j DROP
  262. # If we would use NAT, INVALID packets would pass - BLOCK them anyways
  263. $IPTABLES -A FORWARD -m state --state INVALID -j DROP
  265. # PORT Scanners (stealth also)
  266. $IPTABLES -A INPUT -m state --state NEW -p tcp --tcp-flags ALL ALL -j DROP
  267. $IPTABLES -A INPUT -m state --state NEW -p tcp --tcp-flags ALL NONE -j DROP
  269. # TODO: Some more anti-spoofing rules? For example:
  270. # $IPTABLES -A INPUT -p tcp --tcp-flags ALL FIN,URG,PSH -j DROP
  271. # $IPTABLES -A INPUT -p tcp --tcp-flags SYN,RST SYN,RST -j DROP
  272. # $IPTABLES -A INPUT -p tcp --tcp-flags SYN,FIN SYN,FIN -j DROP
  274. $IPTABLES -A INPUT -p tcp --syn -j SYN_FLOOD
  275. $IPTABLES -A SYN_FLOOD -m limit --limit 2/s --limit-burst 6 -j RETURN
  278. # TODO: Block known-bad IPs (see
  281. # Drop any traffic from IANA-reserved IPs.
  282. #------------------------------------------------------------------------------
  284. $IPTABLES -A INPUT -s -j DROP
  285. $IPTABLES -A INPUT -s -j DROP
  286. $IPTABLES -A INPUT -s -j DROP
  287. $IPTABLES -A INPUT -s -j DROP
  288. $IPTABLES -A INPUT -s -j DROP
  289. $IPTABLES -A INPUT -s -j DROP
  290. $IPTABLES -A INPUT -s -j DROP
  291. $IPTABLES -A INPUT -s -j DROP
  292. $IPTABLES -A INPUT -s -j DROP
  293. $IPTABLES -A INPUT -s -j DROP
  294. $IPTABLES -A INPUT -s -j DROP
  295. $IPTABLES -A INPUT -s -j DROP
  296. $IPTABLES -A INPUT -s -j DROP
  297. $IPTABLES -A INPUT -s -j DROP
  298. $IPTABLES -A INPUT -s -j DROP
  299. $IPTABLES -A INPUT -s -j DROP
  300. $IPTABLES -A INPUT -s -j DROP
  301. $IPTABLES -A INPUT -s -j DROP
  302. $IPTABLES -A INPUT -s -j DROP
  303. $IPTABLES -A INPUT -s -j DROP
  304. $IPTABLES -A INPUT -s -j DROP
  305. $IPTABLES -A INPUT -s -j DROP
  306. $IPTABLES -A INPUT -s -j DROP
  307. $IPTABLES -A INPUT -s -j DROP
  308. $IPTABLES -A INPUT -s -j DROP
  309. $IPTABLES -A INPUT -s -j DROP
  310. $IPTABLES -A INPUT -s -j DROP
  311. $IPTABLES -A INPUT -s -j DROP
  312. $IPTABLES -A INPUT -s -j DROP
  313. $IPTABLES -A INPUT -s -j DROP
  315. # Selectively allow certain outbound connections, block the rest.
  316. #------------------------------------------------------------------------------
  318. # Allow outgoing DNS requests. Few things will work without this.
  319. $IPTABLES -A OUTPUT -m state --state NEW -p udp --dport 53 -j ACCEPT
  320. $IPTABLES -A OUTPUT -m state --state NEW -p tcp --dport 53 -j ACCEPT
  322. # Allow outgoing HTTP requests. Unencrypted, use with care.
  323. $IPTABLES -A OUTPUT -m state --state NEW -p tcp --dport 80 -j ACCEPT
  325. # Allow outgoing HTTPS requests.
  326. $IPTABLES -A OUTPUT -m state --state NEW -p tcp --dport 443 -j ACCEPT
  328. # Allow outgoing SMTPS requests. Do NOT allow unencrypted SMTP!
  329. # $IPTABLES -A OUTPUT -m state --state NEW -p tcp --dport 465 -j ACCEPT
  331. # Allow outgoing "submission" (RFC 2476) requests.
  332. $IPTABLES -A OUTPUT -m state --state NEW -p tcp --dport 587 -j ACCEPT
  334. # Allow outgoing POP3S requests.
  335. $IPTABLES -A OUTPUT -m state --state NEW -p tcp --dport 995 -j ACCEPT
  337. # Allow outgoing SSH requests.
  338. $IPTABLES -A OUTPUT -m state --state NEW -p tcp --dport 22 -j ACCEPT
  340. # Allow outgoing FTP requests. Unencrypted, use with care.
  341. $IPTABLES -A OUTPUT -m state --state NEW -p tcp --dport 21 -j ACCEPT
  343. # Allow outgoing NNTP requests. Unencrypted, use with care.
  344. # $IPTABLES -A OUTPUT -m state --state NEW -p tcp --dport 119 -j ACCEPT
  346. # Allow outgoing NTP requests. Unencrypted, use with care.
  347. # $IPTABLES -A OUTPUT -m state --state NEW -p udp --dport 123 -j ACCEPT
  349. # Allow outgoing IRC requests. Unencrypted, use with care.
  350. # Note: This usually needs the ip_conntrack_irc kernel module.
  351. # $IPTABLES -A OUTPUT -m state --state NEW -p tcp --dport 6667 -j ACCEPT
  353. # Allow outgoing requests to various proxies. Unencrypted, use with care.
  354. # $IPTABLES -A OUTPUT -m state --state NEW -p tcp --dport 8080 -j ACCEPT
  355. # $IPTABLES -A OUTPUT -m state --state NEW -p tcp --dport 8090 -j ACCEPT
  357. # Allow outgoing DHCP requests. Unencrypted, use with care.
  358. # TODO: This is completely untested, I have no idea whether it works!
  359. # TODO: I think this can be tightened a bit more.
  360. $IPTABLES -A OUTPUT -m state --state NEW -p udp --sport 67:68 --dport 67:68 -j ACCEPT
  362. # Allow outgoing CVS requests. Unencrypted, use with care.
  363. # $IPTABLES -A OUTPUT -m state --state NEW -p tcp --dport 2401 -j ACCEPT
  365. # Allow outgoing MySQL requests. Unencrypted, use with care.
  366. # $IPTABLES -A OUTPUT -m state --state NEW -p tcp --dport 3306 -j ACCEPT
  368. # Allow outgoing SVN requests. Unencrypted, use with care.
  369. # $IPTABLES -A OUTPUT -m state --state NEW -p tcp --dport 3690 -j ACCEPT
  371. # Allow outgoing PLESK requests. Unencrypted, use with care.
  372. # $IPTABLES -A OUTPUT -m state --state NEW -p tcp --dport 8443 -j ACCEPT
  374. # Allow outgoing Tor ( requests.
  375. # Note: Do _not_ use unencrypted protocols over Tor (sniffing is possible)!
  376. # $IPTABLES -A OUTPUT -m state --state NEW -p tcp --dport 9001 -j ACCEPT
  377. # $IPTABLES -A OUTPUT -m state --state NEW -p tcp --dport 9002 -j ACCEPT
  378. # $IPTABLES -A OUTPUT -m state --state NEW -p tcp --dport 9030 -j ACCEPT
  379. # $IPTABLES -A OUTPUT -m state --state NEW -p tcp --dport 9031 -j ACCEPT
  380. # $IPTABLES -A OUTPUT -m state --state NEW -p tcp --dport 9090 -j ACCEPT
  381. # $IPTABLES -A OUTPUT -m state --state NEW -p tcp --dport 9091 -j ACCEPT
  383. # Allow outgoing OpenVPN requests.
  384. $IPTABLES -A OUTPUT -m state --state NEW -p udp --dport 1194 -j ACCEPT
  386. # TODO: ICQ, MSN, GTalk, Skype, Yahoo, etc...
  388. # Selectively allow certain inbound connections, block the rest.
  389. #------------------------------------------------------------------------------
  391. # Allow incoming DNS requests.
  392. $IPTABLES -A INPUT -m state --state NEW -p udp --dport 53 -j ACCEPT
  393. $IPTABLES -A INPUT -m state --state NEW -p tcp --dport 53 -j ACCEPT
  395. # Allow incoming HTTP requests.
  396. $IPTABLES -A INPUT -m state --state NEW -p tcp --dport 80 -j ACCEPT
  398. # Allow incoming HTTPS requests.
  399. $IPTABLES -A INPUT -m state --state NEW -p tcp --dport 443 -j ACCEPT
  401. # Allow incoming POP3 requests.
  402. $IPTABLES -A INPUT -m state --state NEW -p tcp --dport 110 -j ACCEPT
  404. # Allow incoming IMAP4 requests.
  405. $IPTABLES -A INPUT -m state --state NEW -p tcp --dport 143 -j ACCEPT
  407. # Allow incoming POP3S requests.
  408. $IPTABLES -A INPUT -m state --state NEW -p tcp --dport 995 -j ACCEPT
  410. # Allow incoming SMTP requests.
  411. $IPTABLES -A INPUT -m state --state NEW -p tcp --dport 25 -j ACCEPT
  413. # Allow incoming SSH requests.
  414. $IPTABLES -A INPUT -m state --state NEW -p tcp --dport 22 -j ACCEPT
  416. # Allow incoming FTP requests.
  417. $IPTABLES -A INPUT -m state --state NEW -p tcp --dport 21 -j ACCEPT
  419. # Allow incoming NNTP requests.
  420. # $IPTABLES -A INPUT -m state --state NEW -p tcp --dport 119 -j ACCEPT
  422. # Allow incoming MySQL requests.
  423. # $IPTABLES -A INPUT -m state --state NEW -p tcp --dport 3306 -j ACCEPT
  425. # Allow incoming PLESK requests.
  426. # $IPTABLES -A INPUT -m state --state NEW -p tcp --dport 8843 -j ACCEPT
  428. # Allow incoming BitTorrent requests.
  429. # TODO: Are these already handled by ACCEPTing established/related traffic?
  430. # $IPTABLES -A INPUT -m state --state NEW -p tcp --dport 6881 -j ACCEPT
  431. # $IPTABLES -A INPUT -m state --state NEW -p udp --dport 6881 -j ACCEPT
  433. # Allow incoming nc requests.
  434. # $IPTABLES -A INPUT -m state --state NEW -p tcp --dport 2030 -j ACCEPT
  435. # $IPTABLES -A INPUT -m state --state NEW -p udp --dport 2030 -j ACCEPT
  437. # Explicitly log and reject everything else.
  438. #------------------------------------------------------------------------------
  439. # Use REJECT instead of REJECTLOG if you don't need/want logging.
  445. #------------------------------------------------------------------------------
  446. # Testing the firewall.
  447. #------------------------------------------------------------------------------
  449. # You should check/test that the firewall really works, using
  450. # iptables -vnL, nmap, ping, telnet, ...
  452. # Exit gracefully.
  453. #------------------------------------------------------------------------------
  455.     exit 0


Thanks. Ref :


L2TP with IPSec on Mikrotik RoutersOS


L2TP with IPSec on Mikrotik RoutersOS

Mikrotik RB750GL Running Package version 6.0rc11
Apple IPhone 4 with iOS 5.x


NOTE: All the formatting on this page is not done as this was a really long Blog: I am redoing it to have better formatting and better explanations. I added some screen shots but like anything you write yourself after you have gone over and over it I tend to miss grammer or spelling mistakes LOL and that’s with a spell checker. HA HA. Most IT guys I know would rather work on the firewall rules and just gloss over the grammer or spelling. Anyways, on to my blog on Mikrotik and L2TP.




PLEASE NOTE: For any configuration examples please visit the Mikrotik Forums for help and support. There are some really knowledgeable people on the forums who will be able to help you with your individual setups.




PPTP is getting a Bad Rap for being unsecure so I implemented SSTP with an SSL Certificate for my Mikrotik Router. (Check out this blog that talks about the PPTP MS-CHAPv2 findings )


All proud that I got it up and running so that I can securely connect to my Mikrotik from another PC (Note: Mikrotik to Mikrotik you don’t need an SSL Certificate) when I am offsite, I thought why not try connecting with my IPhone. Unfortunately there is only 3 Options with the IPhone 4 at this point in time.


PPTP – Not so secure anymore accoriding to some googling and the blog above
IPSec (only used for CISCO).


So I set out to get my IPhone connected to my Mikrotik using L2TP with IPSec.


Here are the steps to get it setup.


Example Mikrotik Router IPs
Interface : ether1-gateway –
Interface: ether2-master-local –


Setting up L2TP/IPSec on the Mikrotik:


Log into your Mikrotik
Click PPP on the left side menu




Under the Interfaces TAB click on L2TP Server Button
In the L2TP Server pop up windows click the Enabled check box


Now choose the authentication methods that you want to use. I highly recommend using only mschap2.
For windows 7 I chose mschap2.
For IPhone 4 you also only need mschap2 set here.


For Default Profile I created a profile called L2TP-Profile but you can use the default encryption profile if you like.
Note: The default encryption worked for Windows 7 but not for IPhone 4. (In my L2TP Profile under the Protocols TAB I changed Use Encryption to default instead of required and then my IPhone worked as well as windows 7 Pro).


Here is how I setup my L2TP Profile:
Again under the PPP Menu click on the Profiles TAB now
Click + to add profile


Name: Now name your profile whatever you want (Remember I named mine L2TP-Profile)
Local Address: The local address is the IP for the Mikrotik inside private IP address (ether2-master-local – from our example – replace with how you setup your Mikrotik)
Remote Address: The remote address can be static or from an IP POOL. This will be the address that gets assigned to the device you are using to connect to the L2TP VPN Server.
- When you set a static make sure that you don’t use an IP that is already being used on your local LAN!!!!
- If Using a POOL make sure you don’t setup a POOL of IP Addresses that would conflict with any addresses inside your LAN (I Will go over IP Pool setup Below)
DNS: I set the DNS to the inside address I assigned to the Mikrotik or you can use an external DNS like google or OpenDNS.
Change TCP MSS: Set to yes if not already.
Done on the General TAB




Click the Protocols TAB


: set as default
Use Compression: set as default
Use VJ Compression: set as default
Use Encryption: set to required if ONLY using windows 7 clients, (Set to DEFAULT if using an IPhone 4)


Limits TAB – you can set limits on traffic here but we don’t set anything different in this tutorial.
Profile Done




NOTE: If you created this profile or your own named profile you MUST now go change the L2TP Server Profile from earlier from default-encryption now to your L2TP-Profile Name from the drop down list so that your profile will be used instead of the default-encryption profile


Ok. Now we have L2TP turned on. We have a profile setup or have used the default and now we need to setup users to use our L2TP server. To do this we use the SECRET TAB still under the PPP Menu to make users




Click on the Secrets TAB and click the + to start making a new user.


Name: This can be a bit misleading. Name is the Username that you will use to logon to your L2TP server. Enter the username you want to use to logon to your L2TP VPN server
Password: set your password here (make sure it is good and strong)
Service: change to L2TP
Profile: change to the profile you made earlier or leave at default-encryption (Note:default encryption does not work with IPhone 4 as it needs the Use Encryption to be set to default under Protocols like we mentioned earlier.)
Click OK and now you have a new shiny user ready to go
Close the PPP menu






OK Take a Breather stretch grab a drink or whatever you do. The above wasn’t that hard but if your new it may have been a little daunting. Now we get to the good stuff.




Alright. Now things get Interesting. If you have never worked with IPSec before then don’t worry. It can be daunting but I will step you through step by step to get this working.


L2TP does not need IPSec but L2TP by itself does NOT provide any encryption as it is a Tunneling Protocol. Thus we use L2TP tunnels and use IPSec to encrypt the data going over the tunnel.
More Info:


Let’s get started.


Click on the IP Menu on Mikrotiks left side menu and then choose IPSec from the drop down list.


Click on the Peers TAB




Click the + to create a new Peer


Address: Leave this as (Everyone can connect)
Port: 500
Auth. Method: pre shared key
Secret: set a secret(password) for the IPSec secret authentication (Make it good and strong)
Exchange Mode: change to “main l2tp”
Send Initial Contact: Check this box
NAT Traversal: Check this box (Most likely you will have users outside of the organization so they will need this checked. I won’t go into what it is. Google is your best friend!!! Look it up)
Proposal check: obey
Hash Algorithm: sha
Encryption Algorithm: 3des
DH Group: modp 1024
Generate Policy: Check this box
Lifetime: 1d 00:00:00 (1 Day)
DPD Interval: 120
DPD Max Failures: 5
Click the OK button.


Your are now done making your IPSec Peer.




Now onto the Proposals Setup:
Click on Proposals TAB
Double click default Proposal from the list


Name: Leave as default
Auth. Algorithm: sha 1
Encr. Algorithms: 3des
(For IPhone 4 to work it needs Encr. Algorithms to also have aes-256 enabled)
Lifetime: 00:30:00
PFS Group: change to “none”
Click the OK button
You have now setup a IPSec proposal compatible with IPhone 4 using iOS 5.x at the time of this tutrial and Windows 7 Pro 64 bit.




Your Mikrotik is now setup for L2TP for windows 7 and IPhone 4


NOTE: Sometimes I had to reboot my IPhone if it was not connecting. Also checking the firewall I noticed after some times it did not even connect anymore and the Counters on IP Firewall Filters did not increment. A reboot usually cleared what was wrong and then the phone would connect to the Mikrotik again.




Windows 7 Pro 64 bit Setup:
Go to the Control Panel
Network and Sharing Centre
Click Setup a new connection or network


Select Connect to a work place and click Next


Click no to create a new connection if you have previous, if not continue


Choose Use my Internet connection VPN


Internet Address: This is the IP of the LAN or WAN side of the Mikrotik depending on if you are testing from the Inside or connecting from the Internet.
Destination Name: Name this whatever you want as it doesn’t really matter. However a good name will help you remember what it is for later on when you have a whole lot of VPN connections made.
Check don’t connect now and click then NEXT button.


User name:Type in the username you setup for your L2TP secret earlier.
Password: This is the L2TP Secrets password from earlier setup NOT the IPSec secret (password) although you can set them the same.
Remember this password: Click the remember password if you want (I would not if this will pose a security risk)
Show Characters: Check this, type your password, make sure it looks correct and then uncheck if you want.
Click the Create Button


You now have a new VPN connection Client setup but we still need to make a few tweaks to it.


Now to Tweak / finish L2TP setup on Windows 7:
Left click the network icon on bottom panel in your system tray. (The network icon near your time display in the right hand system tray).


Locate new L2TP connection and right click on it
Choose Properties from the pop up menu
Click on the General TAB


Make sure hostname or IP is correct
Click the Security TAB


Type of VPN: choose Layer 2 Tunneling …. L2TP IPsec from drop down list.
Click the Advanced settings button


Type in the IPSec secret (password) you created when making the IPSec secret earlier on.
Click OK
Data Encryption: Make sure Required encryption disconnect if server declines is chosen
Allow These protocols:
Choose MSCHAP v2
Don’t have PAP or CHAP checked
Click OK
Your Windows 7 L2TP Client is now fully configured.


Click the network Icon again in your system tray and now this time choose connect and you should be connected.




IPhone 4 with iOS 5.1.1 Setup:


Got to VPN
Click Add VPN Configuration
Choose L2TP
Description: Call it whatever you want.
Server: Put in the Mikrotik WAN IP or FQDN
Account: Put in the username you setup under Secret TAB setup
RSA Secure ID: OFF
Password: Your password
Secret: Your IPSec Password
Send All Traffic: ON
Proxy: OFF
Click Save and now you should be able to connect with your IPhone 4.




Now if you are going to access your L2TP from the internet then you will need to setup some Firewall Filter Rules to let the traffic in:


For Outside access you need to have Firewall rules for UDP Ports 500, UDP Port 1701, and UDP Port 4500
Other firewall settings I read about were Protocol 50 ipsec-esp and protocol 51 ipsec-ah
For my setup I just setup UDP Ports 500, 1701 and 4500
Ok here we go:


Log in to your Mikrotik router if your still not on it.


Click IP from the left side menu
Click Firewall from the pop up menu
Click the Filter Rules TAB
Click + to add new firewall filter rule.


On the General TAB:


Chain: input
Protocol: 17 UDP
DST Port: 500
In Interface: ether1-gateway (or whatever your WAN interface name is. Choose it from the drop down list)
Connection state: new




Click the Action TAB:


Action: accept
You now have your first Firewall Filter rule setup for UDP port 500
You need to make 2 more. 1 for UDP port 1701 and UDP port 4500


Now once this is done you may want to group these rules in order and then put them high enough in your firewall filter chain so that they get processed before any UDP Drop Firewall filter rules you have or else they wont get processed.


I also added a log rule so I could see connections in my log for debugging:




NOTE: I don’t have the other rules enabled and also you can get away with making one rule that has all three UDP ports in the one rule example:




But for this tutorial practice makes perfect :)




It’s Probably 4 am if your anything like me and you have work in 3 hours. Put in some Visine eye drops and pound back whatever caffeine you can get your hands on… lol


Now go show all your friends how you can logon to your Mikrotik from their house using an L2TP VPN tunnel and the iSSH app on your IPhone or impress them even more when you run a script using iSSH on your IPhone to wakeup your home station using (Script Clue: “tool wol interface=ether2-master-local mac=InsertMACaddressofyourstation-here” without the quotes)


You can make this script in your Mikrotik under System | Scripts


I called mine wakemyws for Wake My Workstation and then in the source I put in the “tool wol interface=ether2-master-local mac=InsertMACaddressofyourstation-here” without quotes


Now I can wake my Workstation right from my Mikrotik when I’m out of the office using my IPhone if I am not sitting at a station.






AS THIS IS A REALLY LONG POST please comment on grammer or mistakes so I can fix it. I have read it so many times I probably just gloss over now and don’t notice anything. Also if you think I should make an addition or made a mistake please leave a comment. Constructive Criticism is good. We should never stop learning and growing.


Thanks, Ref #