Created
April 4, 2013 17:55
-
-
Save StanAngeloff/5312554 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# If the script fails at any point, don't continue. | |
set -e | |
# The `iptables` command. Use 'sudo' if you are running as a non-privileged User. | |
iptables='sudo /sbin/iptables' | |
# {{{ Configuration | |
# Get a list of all internal IPs, | |
ifconfig_ip_list=( $( ifconfig | grep 'inet addr' | cut -d ':' -f 2 | cut -d ' ' -f 1 ) ) | |
# DNS nameservers, | |
resolv_ip_list=( $( cat '/etc/resolv.conf' | grep 'nameserver' | grep -v '^\s*#' | sed -e 's/^\s\+|\s\+$//g' -e 's/\s\+/ /g' | cut -d ' ' -f 2 ) ) | |
# NTP pool servers. | |
ntpd_ip_list=( $( cat '/etc/ntp.conf' | grep 'restrict' | grep -v '^\s*#' | sed -e 's/^\s\+|\s\+$//g' -e 's/\s\+/ /g' | cut -d ' ' -f 2 | grep '^[0-9.]\+$' ) ) | |
# }}} | |
# {{{ Rules | |
# Drop any DNS requests from external IPs. | |
# Internal IPs are allowed to perform DNS lookups, see end of script. | |
$iptables -I INPUT -p tcp --dport 53 -j DROP | |
$iptables -I INPUT -p udp --dport 53 -j DROP | |
# Set up a new chain LOG_DROP. | |
$iptables --new-chain LOG_DROP | |
# Flush any rules to be safe, start clean. | |
$iptables --flush LOG_DROP | |
# All traffic sent to LOG_DROP is logged first. | |
$iptables -A LOG_DROP -p tcp -j LOG --log-prefix '** UNAUTHORISED ** ' --log-level 4 | |
$iptables -A LOG_DROP -p udp -j LOG --log-prefix '** UNAUTHORISED ** ' --log-level 4 | |
# Traffic on TCP is rejected with a TCP RST packet. | |
$iptables -A LOG_DROP -p tcp -j REJECT --reject-with tcp-reset | |
# Traffic on UDP is rejected with port-unreachable (default). | |
$iptables -A LOG_DROP -p udp -j REJECT --reject-with icmp-port-unreachable | |
# Finally, drop the packet altogether. | |
$iptables -A LOG_DROP -j DROP | |
# Log and reject all UDP traffic by default. | |
$iptables -I OUTPUT -p udp -j LOG_DROP | |
# Accept DNS traffic to /etc/resolv.conf listed IPs. | |
for ip in "${resolv_ip_list[@]}"; do | |
$iptables -I OUTPUT -p udp --dport 53 -d "$ip" -j ACCEPT | |
done | |
# Accept DNS traffic to internal IPs: | |
for ip in "${ifconfig_ip_list[@]}"; do | |
$iptables -I OUTPUT -p udp --dport 53 -d "$ip" -j ACCEPT | |
done | |
# Allow NTP: | |
for ip in "${ntpd_ip_list[@]}"; do | |
$iptables -I OUTPUT -p udp --dport 123 -d "$ip" -j ACCEPT | |
done | |
# }}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment