Firewall in Linux (IPTABLES)


cat > /etc/rc.firewall

#!/bin/sh

# Variables
FW="/sbin/iptables"
IF1="eth0"
IF1_IP=`/sbin/ifconfig ${IF1}|grep -w inet|awk -F: '{print $2}'|awk '{print $1}'`
IF1_MASK=`/sbin/ifconfig ${IF1}|grep -w inet|awk '{print $4}'|awk -F: '{print $2}'`
IF1_NET="${IF1_IP}/${IF1_MASK}"

# Temporarily Change the Default Policy to Accept
${FW} -P INPUT ACCEPT
${FW} -P OUTPUT ACCEPT
${FW} -P FORWARD ACCEPT

# Flush and Delete Chains
${FW} -X
${FW} -F
${FW} -F -t nat
${FW} -F -t mangle

# Allow packets in/out from Loopback Device
${FW} -A INPUT -i lo -j ACCEPT
${FW} -A OUTPUT -o lo -j ACCEPT

# Allow Outgoing Packets from this host
${FW} -A OUTPUT -j ACCEPT

# Use Stateful Firewall for Incoming Packets
${FW} -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# Allow Incoming ssh connection from Local Network
${FW} -A INPUT -p tcp -s ${IF1_NET} --dport 22 -j ACCEPT

# Allow Incoming icmp from Local Network
${FW} -A INPUT -p icmp -s ${IF1_NET} -j ACCEPT

# Allow icmp packets that are not of type echo-request
${FW} -A INPUT -p icmp --icmp-type ! 8 -j ACCEPT

# Change the Default Policy to DROP/REJECT
${FW} -P INPUT DROP
${FW} -P OUTPUT DROP
${FW} -P FORWARD DROP

OR

# Variables
FW="/sbin/iptables" # Tool
IF1="eth0" # Device
IF1_IP=`/sbin/ifconfig ${IF1}|grep -w inet | awk -F: '{ print $2 }' | awk ' { print $1 } '` # Get IP Address
IF1_MASK=`/sbin/ifconfig ${IF1}|grep -w inet | awk ' { print $4 } ' | awk -F: ' { print $2 } '` # Get NetMask
IF1_NET="${IF1_IP}/${IF1_MASK}"

# Temporarily Change the Default Policy to Accept
${FW} -P INPUT ACCEPT
${FW} -P OUTPUT ACCEPT
${FW} -P FORWARD ACCEPT

# Flush and Delete Chains
${FW} -X
${FW} -F
${FW} -F -t nat
${FW} -F -t mangle

# Allow packets in/out from Loopback Device
${FW} -A INPUT -i lo -j ACCEPT
${FW} -A OUTPUT -o lo -j ACCEPT

# Allow Outgoing Packets from this host
${FW} -A OUTPUT -j ACCEPT

# Use Stateful Firewall for Incoming Packets
${FW} -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# Allow Incoming ssh connection from Local Network
${FW} -A INPUT -p tcp -s ${IF1_NET} --dport 22 -j ACCEPT

# Allow Incoming icmp from Local Network
${FW} -A INPUT -p icmp -s ${IF1_NET} -j ACCEPT

# Allow Incoming ssh connection from other Network
${FW} -A INPUT -p tcp -s xxx.xxx.xxx.0/24 --dport 22 -j ACCEPT

#Allow Incoming ftp connection
${FW} -A INPUT -p tcp -s xxx.xxx.xxx.0/24 --dport 20:21 -j ACCEPT

#Allow Incoming http connection
${FW} -A INPUT -p tcp -s xxx.xxx.xxx.0/24 --dport 80 -j ACCEPT

# Allow icmp packets that are not of type echo-request
${FW} -A INPUT -p icmp --icmp-type ! 8 -j ACCEPT

# Change the Default Policy to DROP/REJECT
${FW} -P INPUT DROP
${FW} -P OUTPUT DROP
${FW} -P FORWARD DROP

Redhat
echo "/etc/rc.firewall" >> /etc/rc.d/rc.local

Gentoo
echo "/etc/rc.firewall" >>/etc/conf.d/local.start

Enable Firewall in startup
chmod 755 /etc/rc.firewall

, ,

Comments are closed.