Skip to content

Instantly share code, notes, and snippets.

@flavienbwk
Last active January 5, 2022 22:08
Show Gist options
  • Save flavienbwk/7bb88e1206ac1fc01d90f7d35b38d6d8 to your computer and use it in GitHub Desktop.
Save flavienbwk/7bb88e1206ac1fc01d90f7d35b38d6d8 to your computer and use it in GitHub Desktop.
Dynamic IPtables by domains part of [my guide](https://medium.com/@flavienb/installing-and-securing-docker-rootless-for-production-use-8e358d1c0956) on Docker Rootless mode
#!/bin/bash
# Dynamically retrieves and add IPs from a list of domain names
# Creates a cache folder with IP as filenames to know if they have been added previously
# Manages both IPv4 and IPv6 rules.
MAIN_INTERFACE=$(ip -4 route ls | grep default | grep -Po '(?<=dev )(\S+)' | head -1)
THIS_DIR="$(cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd)"
CACHE_DIR="$THIS_DIR/.ips"
function is_ipv4()
{
local ip=$1
local stat=1
if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
OIFS=$IFS
IFS='.'
ip=($ip)
IFS=$OIFS
[[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \
&& ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]
stat=$?
fi
return $stat
}
if [ ! -z "$1" ] && [ "$1" = "clear-cache" ];
then
echo -e "Removing IPs cache"
rm -r $CACHE_DIR
fi
mkdir -p $CACHE_DIR
# Allow `dockerprod` user to access HTTP(i/o)+HTTPS(i/o)+SSH(git, o) for some IPs only
# Dynamically retrieving IPs from their hostnames
WHITELIST_DOMAINS=$(cat "$THIS_DIR/whitelist-domains.txt")
for WHITELIST_DOMAIN in $WHITELIST_DOMAINS;
do
WHITELIST_IPS=$(getent ahosts $WHITELIST_DOMAIN | awk '{ print $1; }') # Retrieves a list of IP per domain
if [ ! -z "$WHITELIST_IPS" ];
then
for WHITELIST_IP in $WHITELIST_IPS;
do
if [ ! -z "$WHITELIST_IP" ];
then
IP_FILE="$CACHE_DIR/$(echo $WHITELIST_IP | sed -e 's/[^A-Za-z0-9._-]/_/g')"
if [ ! -f "$IP_FILE" ];
then
# Allow HTTP(i/o)+HTTPS(i/o)+SSH(git, o) queries for user dockerprod
if is_ipv4 $WHITELIST_IP;
then
iptables -A OUTPUT -o $MAIN_INTERFACE -m owner --uid-owner dockerprod -p tcp -m multiport --dports 80,443,22 -m state --state NEW -d $WHITELIST_IP -j ACCEPT
else
ip6tables -A OUTPUT -o $MAIN_INTERFACE -m owner --uid-owner dockerprod -p tcp -m multiport --dports 80,443,22 -m state --state NEW -d $WHITELIST_IP -j ACCEPT
fi
echo "Added at `date`" > $IP_FILE
echo -e "Authorized dockerprod for IP $WHITELIST_IP binding to $WHITELIST_DOMAIN"
else
echo -e "IP already added for $WHITELIST_DOMAIN : $WHITELIST_IP"
fi
else
echo -e "Empty IP ignored for $WHITELIST_DOMAIN"
fi
done
else
echo -e "Could not find any IP binded to $WHITELIST_DOMAIN"
fi
done
registry-1.docker.io
production.cloudflare.docker.com
security.ubuntu.com
archive.ubuntu.com
github.com
gist.githubusercontent.com
@Mixie-12
Copy link

Mixie-12 commented Jan 5, 2022

<3 Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment