Skip to content

Instantly share code, notes, and snippets.

@p-hennessy
Created May 8, 2015 08:49
Show Gist options
  • Save p-hennessy/5a3b60e41022748f5f68 to your computer and use it in GitHub Desktop.
Save p-hennessy/5a3b60e41022748f5f68 to your computer and use it in GitHub Desktop.
#!/bin/bash
IPTABLES=/sbin/iptables
LOG_LEVEL="notice"
# Flush Existing Rules
echo 'Flushing current ruleset...'
$IPTABLES -F
$IPTABLES -F INPUT
$IPTABLES -F OUTPUT
$IPTABLES -F FORWARD
# Default Policies
echo "Setting default policies..."
$IPTABLES -P INPUT DROP # By default, drop all input
$IPTABLES -P OUTPUT ACCEPT # By default, accept all output
$IPTABLES -P FORWARD DROP # By default, dont forward
$IPTABLES -A INPUT -i lo -j ACCEPT
$IPTABLES -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT # Sets established connections to accept all.
# Create new chains -N makes a new chain
$IPTABLES -N SERVICES
$IPTABLES -N DENY_PORTS
$IPTABLES -N DENY_HOSTS
$IPTABLES -N MANUAL_HOSTS
$IPTABLES -N MANUAL_PORTS
# Allow input on chains. Specify which to accept or deny below...
$IPTABLES -A INPUT -j SERVICES
$IPTABLES -A INPUT -j DENY_PORTS
$IPTABLES -A INPUT -j DENY_HOSTS
$IPTABLES -A INPUT -j MANUAL_HOSTS
$IPTABLES -A INPUT -j MANUAL_PORTS
# Denied ports
DENIED_PORTS=""
for PORT in $DENIED_PORTS; do
echo "Adding rule: log and deny port \"$PORT\""
$IPTABLES -A DENY_PORTS -p tcp --dport $PORT -m limit --limit 5/minute -j LOG --log-level $LOG_LEVEL --log-prefix "DENIED PORT:"
$IPTABLES -A DENY_PORTS -p tcp --dport $PORT -j DROP
done
# Denied Hosts
DENIED_HOSTS=""
for HOST in $DENIED_HOSTS; do
echo "Adding rule: log and deny host \"$HOST\""
$IPTABLES -A DENY_HOSTS -s $HOST -j LOG --log-level $LOG_LEVEL --log-prefix "DENIED HOST:"
$IPTABLES -A DENY_HOSTS -s $HOST -j DROP
done
# Allowed Services
SERVICE_PORTS_TCP="22"
SERVICE_PORTS_UDP=""
for PORT in $SERVICE_PORTS_TCP; do
echo "Adding rule: allow TCP service on port \"$PORT\""
$IPTABLES -A SERVICES -m state --state NEW -p tcp --dport $PORT -j ACCEPT
done
for PORT in $SERVICE_PORTS_UDP; do
echo "Adding rule: allow UDP service on port \"$PORT\""
$IPTABLES -A SERVICES -m state --state NEW -p udp --dport $PORT -j ACCEPT
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment