-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathiptables.sh
49 lines (38 loc) · 1.16 KB
/
iptables.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#!/bin/bash
#
# This script outputs iptables rules compatible with iptables-restore.
# The rules are designed to block traffic to the public interface
# that is not from whitelisted addresses before they reach the
# standard Docker routing rules.
#
# Expects the following environment variables:
#
# Optional:
# - FW_DISABLE if set to 1, disables the firewall rules
#
# Example:
# $ iptables.sh | iptables-restore --counters --noflush
# Get public interface name
IF=$(ip route | awk '/^default/{print $5}')
service=cloudflare
prefix=DOCKER-$service
chain=$prefix-$(openssl rand -hex 3)
echo "# Generated by iptables.sh: $service"
echo "# Public interface: $IF"
iptables-save -t mangle | sed "/$prefix-/d;/^COMMIT$/d;/^#/d"
# Allow the firewall to be disabled
if [[ "$FW_DISABLE" = "1" ]]; then
echo COMMIT
exit 0
fi
# Add new chain
echo -N ${chain}
# Allow source IPs
for addr in $(curl https://www.cloudflare.com/ips-v4); do
echo -A ${chain} -s ${addr} -j RETURN -m comment --comment "static-entry"
done
# Deny all other IPs
echo -A ${chain} -j DROP
# Insert rule into PREROUTING
echo -A PREROUTING -i $IF -p tcp -m multiport --dports 80,443 -j ${chain}
echo COMMIT