Skip to content

Instantly share code, notes, and snippets.

@cdpb
Created February 16, 2016 08:41
Show Gist options
  • Save cdpb/f899f8adbcd643eb9bb2 to your computer and use it in GitHub Desktop.
Save cdpb/f899f8adbcd643eb9bb2 to your computer and use it in GitHub Desktop.
simple iptables to secure docker from host
#!/bin/bash
# for coreos with flannel ...
# Example use ./iptables.sh --source 172.16.23.0/24 --destination 172.16.23.1 --local 10.2.0.2 --dry-run true
while [[ $# > 1 ]]
do
ARGS="$1"
case $ARGS in
-s|--source)
SRC="$2"
shift
;;
-d|--destination)
DST="$2"
shift
;;
--local)
LOCAL="$2"
shift
;;
--dry-run)
DRY="$2"
shift
;;
esac
shift
done
if [[ -z $SRC || -z $DST || -z $LOCAL ]]
then
echo "nope"
exit 99
fi
if [[ $DRY = true ]]
then
echo "dryrun"
A="echo"
else
echo "install iptables"
A="eval"
fi
function _checkandset() {
CHECK=$( echo $1 | sed 's/-A/-C/g' )
eval $CHECK
if [[ $? = 1 ]]; then
echo "new rule $1"
$A $1
fi
}
netstat -tpln | awk '{ print $4 }' | grep -e 0.0.0.0 -e "::" | sed 's/:://g' | cut -d ":" -f 2 | while read LINE
do
if [[ -n $LINE ]]; then
_checkandset "iptables -A INPUT -s $SRC -d $DST -p tcp -m state --state NEW -m tcp --dport $LINE -j DROP"
fi
done
_checkandset "iptables -A INPUT -s $SRC -d $LOCAL -j DROP"
_checkandset "iptables -A FORWARD -s $SRC -d 10.2.0.1 -j ACCEPT"
_checkandset "iptables -A FORWARD -s $SRC -d 10.0.0.0/8 -j DROP"
etcdctl ls --recursive /coreos.com/network/subnets | cut -d "/" -f5 | cut -d "-" -f1 | \
grep -v $(source /etc/network-environment && echo $FLANNEL0_IPV4 ) | \
sed 's/.$/1/g' | while read LINE
do
if [[ -n $LINE ]]; then
_checkandset "iptables -A FORWARD -s $SRC -d $LINE -j DROP"
fi
done
[Unit]
Description=k8s hardining
After=setup-network-environment.service flanneld.service
Requires=setup-network-environment.service flanneld.service
[Service]
EnvironmentFile=/etc/network-environment
EnvironmentFile=/run/flannel/subnet.env
RemainAfterExit=yes
ExecStartPre=/usr/bin/wget -N -P /opt/bin http://10.2.0.1/other/iptables.sh
ExecStartPre=/usr/bin/chmod +x /opt/bin/iptables.sh
ExecStartPre=/opt/bin/setup-network-environment
ExecStart=/bin/bash -c "while true; do /opt/bin/iptables.sh -s ${FLANNEL0_IPV4}/24 -d ${DOCKER0_IPV4} --local ${DEFAULT_IPV4}; sleep 300; done"
ExecStop=/bin/bash -c "iptables -F FORWARD && iptables -F INPUT"
[X-Fleet]
Global=true
MachineMetadata=role=kubernetes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment