Skip to content

Instantly share code, notes, and snippets.

@jsumners
Created October 7, 2013 20:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsumners/6874241 to your computer and use it in GitHub Desktop.
Save jsumners/6874241 to your computer and use it in GitHub Desktop.
A simple iptables script usable on any new server. Build from it.
#!/bin/bash
## Initial firewall building script.
## Should be run as root.
it=$(which iptables)
################################################################################
## Use this section to establish prerouted port redirects.
## For example, redirect port "80" to port "8080".
################################################################################
#${it} -t nat -A PREROUTING -d 10.0.0.5 -p tcp -m tcp --dport 80 -j DNAT --to-destination 10.0.0.5:8080
################################################################################
## Use this section to open ports to the server.
################################################################################
${it} -N open_ports
# open the SSH port
${it} -A open_ports -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
# open the default HTTP port
#${it} -A open_ports -p tcp -m tcp --dport 80 -j ACCEPT
# open the default HTTPS port
#${it} -A open_ports -p tcp -m tcp --dport 443 -j ACCEPT
################################################################################
## This section defines the primary rules for incoming packets.
## You shouldn't have to touch this section.
################################################################################
${it} -N input_filter
# Allow all loopback traffic and drop all traffic to 127/8 that use use lo0.
${it} -A input_filter -i lo -j ACCEPT
${it} -A input_filter ! -i lo -d 127.0.0.0/8 -j REJECT
# Accept all inbound connections that were previously accepted.
${it} -A input_filter -m state --state ESTABLISHED,RELATED -j ACCEPT
# Allow the system to be pinged.
${it} -A input_filter -p icmp -m icmp --icmp-type 8 -j ACCEPT
# Log a message about any packet that has reached the end of the filter.
${it} -A input_filter -m limit --limit 5/min -j LOG --log-prefix "iptables denied: " --log-level 7
# Process our open_ports rules before any others
${it} -I input_filter 1 -j open_ports
# Add the input filter to the input chain.
${it} -I INPUT 1 -j input_filter
## Output rules
${it} -A OUTPUT -j ACCEPT
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment