november 28, 2004

This is a good tutorial for iptables. My favorite part is this example: Blocking telnet Connections Now for a slightly more complicated configuration. Let's say, a firewall that automatically blocks ssh connections from outside your internal network, but allows ssh within the network. To preclude users from revealing username and password combinations to the outside world, this firewall will also block anyone inside the network from trying to use telnet outside the network. First, set a rule that allows ssh within the network on the INPUT chain. iptables -A INPUT -s -p tcp --destination-port ssh -j ACCEPT The source (-s) argument tells iptables which network or hosts from which you're willing to accept connections, while --destination-port specifies the type of TCP connection you're willing to accept. Next, block any connections from outside your internal network: iptables -A INPUT -s ! -p tcp --destination-port ssh -j DROP This is almost the same command, except that it blocks all ssh connections from outside networks. You may not want to do this if you plan to connect to internal machines while you're on the road. This also depends on the machine with iptables being the gateway computer for your network. It doesn't work if the computer with iptables never sees the packets! Also, note the space between the "!" and the network. I got some very odd errors before I realized there needed to be a space between the network and "!" character. Finally, to block outgoing telnet connections, apply this rule to the OUTPUT chain: iptables -A OUTPUT -p tcp --destination-port telnet -j DROP Instead of appending (-A) a rule to the INPUT chain, we've added the rule to the OUTPUT chain. If users try to telnet out, they'll be unable to get a connection. However, this might frustrate users who wait indefinitely for the telnet connection to finish. So, let's reject the packets instead of just dropping them. iptables -F OUTPUT iptables -A OUTPUT -p tcp --destination-port telnet -j REJECT After flushing the OUTPUT chain, we use almost the same command as the one used to block outgoing telnet connections, and jump (-j) to rejecting the packets. This will give users a "connection refused" error if they try to telnet out. If you want to allow telnet connections within the internal network, flush the previous rules and use these commands to set rules that allow telnet inside the network, but not outside: iptables -A OUTPUT -p tcp --destination-port telnet -d -j ACCEPT iptables -A OUTPUT -p tcp --destination-port telnet -d ! -j REJECT