Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save delfuego/878a778e34478f875f7b198ac09dca75 to your computer and use it in GitHub Desktop.
Save delfuego/878a778e34478f875f7b198ac09dca75 to your computer and use it in GitHub Desktop.
docker-swarm iptables FORWARD custom chain enforcement
#!/bin/bash
CUSTOM_CHAIN=DOCKER-BLOCK
DELAY=10
NEW_RULE="-o docker0 -j ${CUSTOM_CHAIN}"
chain_exists()
{
[ $# -lt 1 -o $# -gt 2 ] && {
echo "Usage: chain_exists <chain_name> [table]" >&2
return 1
}
local chain_name="$1" ; shift
[ $# -eq 1 ] && local table="--table $1"
iptables $table -n --list "$chain_name" >/dev/null 2>&1
}
while [ True ];
do
custom_chain_position=`iptables-save | grep -e "-A FORWARD" | grep --line-number -e "-A FORWARD ${NEW_RULE}" | sed 's/\([0-9]\+\):.*/\1/g'`
if ! chain_exists DOCKER-BLOCK
then
echo "`date`: create DOCKER-BLOCK chain"
iptables -N DOCKER-BLOCK
fi
if [[ -z "$custom_chain_position" ]]
then
echo "`date`: insert DOCKER-BLOCK rule into FILTER chain"
iptables -I FORWARD ${NEW_RULE}
elif [[ "$custom_chain_position" -ne "1" ]]
then
echo "`date`: enforce priority of DOCKER-BLOCK rule in FILTER chain"
iptables -D FORWARD ${custom_chain_position}
iptables -I FORWARD ${NEW_RULE}
fi
sleep $DELAY
done
[Unit]
Description=DOCKER-BLOCK filter enforcement service
[Service]
Type=simple
ExecStart=/usr/local/bin/docker-block-enforcement.sh
KillMode=mixed
TimeoutStartSec=0
RestartSec=0
Restart=always
[Install]
WantedBy=multi-user.target
Alias=docker-block-filter.service
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment