Wednesday, July 17, 2013

CentOS 6.2 Minimal Setup - Part 3 - IPTables

The next step is to lock down which protocols and ports can access our machine.

See http://wiki.centos.org/HowTos/Network/IPTables for a great explanation of IPTables.

So to do this we create a script that will alter IPTables. We create the script as root user and save it in the /root folder. We will call it myfirewall. Once run chmod 700 mfirewall.

The contents of our myfirewall will be the following.


#!/bin/bash
#
# iptables example configuration script
#
# Flush all current rules from iptables
#
 iptables -F
#
# Allow SSH connections on tcp port 2022
# This is essential when working on remote servers via SSH to prevent locking yourself out of the system
#
 iptables -A INPUT -p tcp --dport 2022 -j ACCEPT


# port 8080 allow
 iptables -A INPUT -p tcp --dport 8080 -j ACCEPT
# port 80 allow
 iptables -A INPUT -p tcp --dport 80 -j ACCEPT
# port 443 allow
iptables -A INPUT -p tcp --dport 443 -j ACCEPT
# port 8443 allow
iptables -A INPUT -p tcp --dport 8443 -j ACCEPT
# forward from port 80 to 8080
 iptables -t nat -A PREROUTING -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 8080    
 iptables -t nat -A PREROUTING -p udp -m udp --dport 80 -j REDIRECT --to-ports 8080 
# forward from port 443 to 8443
iptables -t nat -A PREROUTING -p tcp -m tcp --dport 443 -j REDIRECT --to-ports 8443
iptables -t nat -A PREROUTING -p udp -m udp --dport 443 -j REDIRECT --to-ports 8443
 iptables -A INPUT -p icmp -j ACCEPT

#
# Set default policies for INPUT, FORWARD and OUTPUT chains
# 
 iptables -P INPUT DROP
 iptables -P FORWARD DROP
 iptables -P OUTPUT ACCEPT
#
# Set access for localhost
#
 iptables -A INPUT -i lo -j ACCEPT
#
# Accept packets belonging to established and related connections
#
 iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
#
# Save settings
#
 /sbin/service iptables save
#
# List rules
#
 iptables -L -v


Important points to note:
1) We have the SSH port set to 2022. This is normally 22 so make sure your script has the correct port. This will be set in /etc/ssh/sshd_config.
2) This firewall configured for tomcat running standalone, ie without apache in front. Therefore traffic will come to the machine via ports 80 (http) or 443 (https) and will be re-routed to 8080 and 8443.
3) By default we will drop any input or forward traffic. By default we will allow any outbound traffic.



No comments:

Post a Comment