Last active
October 3, 2018 07:37
-
-
Save tonejito/a9ec59ff8533c444ba1a02c3d106e7f4 to your computer and use it in GitHub Desktop.
Check for spurious @apache httpd connections via iptables -j LOG
This file contains 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 -vx | |
# = ^ . ^ = | |
# iptables-apache.sh | |
# Check for spurious @apache connections via iptables -j LOG | |
# Andres Hernandez - tonejito | |
# Released under the BSD 3-clause license | |
APACHE_USER=www-data | |
APACHE_UID=$(getent passwd ${APACHE_USER} | awk -F : '{print $3}') | |
APACHE_CHAIN=APACHE | |
APACHE_PORTS=80,443 | |
# Resolve domain to add LB addresses | |
DOMAIN=example.com. | |
DNS="$(dig +short ${DOMAIN})" | |
# Get our own IP addresses | |
IP="$(hostname -I)" | |
# Remove IPv6 addresses because we're dealing only with iptables(8) | |
TARGETS="" | |
for TARGET in ${DNS} ${IP} | |
do | |
echo ${TARGET} | grep : && continue | |
TARGETS="${TARGETS} ${TARGET}" | |
done | |
# Flush old chain IF EXISTS | |
iptables -S ${APACHE_CHAIN} && \ | |
iptables -F ${APACHE_CHAIN} | |
# Remove old chain IF EXISTS | |
iptables -D OUTPUT -m owner --uid-owner ${APACHE_UID} -j ${APACHE_CHAIN} && \ | |
iptables -X ${APACHE_CHAIN} | |
# Create custom chain | |
iptables -N ${APACHE_CHAIN} | |
# Send Apache traffic to custom chain | |
iptables -A OUTPUT -m owner --uid-owner ${APACHE_UID} -j ${APACHE_CHAIN} | |
# Ignore loopback connections | |
iptables -A ${APACHE_CHAIN} -o lo -j RETURN | |
# Ignore established connections | |
iptables -A ${APACHE_CHAIN} -m conntrack --ctstate RELATED,ESTABLISHED -j RETURN | |
# Ignore connections to self | |
for TARGET in ${TARGETS} | |
do | |
iptables -A ${APACHE_CHAIN} -s ${TARGET}/32 -m multiport -p tcp --sports ${APACHE_PORTS} -j RETURN | |
iptables -A ${APACHE_CHAIN} -d ${TARGET}/32 -j RETURN | |
done | |
# Log and drop spurious connections | |
iptables -A ${APACHE_CHAIN} -m limit --limit 1/min -j LOG --log-prefix "iptables-apache: " --log-tcp-options --log-ip-options --log-uid | |
iptables -A ${APACHE_CHAIN} -j DROP | |
# Display iptables ruleset | |
iptables-save | |
# Now grab a coffee and watch your kernel logs for "iptables-apache" related messages |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment