Skip to content

Instantly share code, notes, and snippets.

@fortejas
Created November 6, 2019 08:50
Show Gist options
  • Save fortejas/1cdc39827e1a9b9aa5e2a3dd9c7af5fe to your computer and use it in GitHub Desktop.
Save fortejas/1cdc39827e1a9b9aa5e2a3dd9c7af5fe to your computer and use it in GitHub Desktop.
Block Access to EC2 Metadata Service on ECS Optimized AMIs
#!/usr/bin/env bash
#
# Prevent access to the metadata endpoint from docker containers in Amazon Linux and Amazon Linux 2
#
printf "Creating /bin/update-iptables.sh"
cat <<EOF | tee /bin/update-iptables.sh
#!/usr/bin/env bash
rule_exists=\$(iptables --check FORWARD --in-interface docker+ --destination 169.254.169.254/32 --jump DROP)
if [[ \$rule_exists -eq 0 ]]; then
iptables --delete FORWARD --in-interface docker+ --destination 169.254.169.254/32 --jump DROP
fi
iptables --insert FORWARD 1 --in-interface docker+ --destination 169.254.169.254/32 --jump DROP
EOF
chmod +x /bin/update-iptables.sh
KRNL=$(/bin/uname -r)
if [[ $KRNL =~ "amzn1" ]]; then
printf "Updating /etc/init.d/docker"
sed -i -e '/success/a \\t\tsleep 1 && /bin/update-iptables.sh' /etc/init.d/docker
elif
printf "Updating /usr/lib/systemd/system/docker.service"
sed -i -e '/ExecStart=/a ExecStartPost=/bin/update-iptables.sh' /usr/lib/systemd/system/docker.service
systemctl daemon-reload
fi
/bin/update-iptables.sh
printf "Done"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment