From 62a6fc230fac108a9225057bd2db13d38cde006e Mon Sep 17 00:00:00 2001 From: furkan sahin Date: Wed, 18 Feb 2026 14:05:16 +0100 Subject: [PATCH] Block non-root access to EC2 instance metadata endpoint Co-Authored-By: Claude Opus 4.6 --- common/assets/imds-protection.nftables.conf | 17 +++++++++++++++++ common/assets/imds-protection.service | 12 ++++++++++++ common/setup_base.sh | 7 +++++++ 3 files changed, 36 insertions(+) create mode 100644 common/assets/imds-protection.nftables.conf create mode 100644 common/assets/imds-protection.service diff --git a/common/assets/imds-protection.nftables.conf b/common/assets/imds-protection.nftables.conf new file mode 100644 index 0000000..c68c397 --- /dev/null +++ b/common/assets/imds-protection.nftables.conf @@ -0,0 +1,17 @@ +#!/usr/sbin/nft -f + +flush ruleset + +table inet imds_protection { + chain output { + type filter hook output priority 0; policy accept; + + # Allow root to access IMDS + meta skuid 0 ip daddr 169.254.169.254 accept + meta skuid 0 ip6 daddr fd00:ec2::254 accept + + # Block all other users from accessing IMDS + ip daddr 169.254.169.254 drop + ip6 daddr fd00:ec2::254 drop + } +} diff --git a/common/assets/imds-protection.service b/common/assets/imds-protection.service new file mode 100644 index 0000000..74d95e2 --- /dev/null +++ b/common/assets/imds-protection.service @@ -0,0 +1,12 @@ +[Unit] +Description=Block non-root access to EC2 instance metadata +DefaultDependencies=no +Before=network-pre.target +Wants=network-pre.target + +[Service] +Type=oneshot +ExecStart=/bin/sh -c 'grep -qi amazon /sys/devices/virtual/dmi/id/sys_vendor 2>/dev/null && nft -f /etc/nftables.conf || true' + +[Install] +WantedBy=multi-user.target diff --git a/common/setup_base.sh b/common/setup_base.sh index ee439fe..4b5c73d 100644 --- a/common/setup_base.sh +++ b/common/setup_base.sh @@ -112,4 +112,11 @@ usermod --append --groups cert_readers prometheus echo "[setup_base.sh] Restricting su to sudo group..." echo -e '\nauth required pam_wheel.so group=sudo\n' | tee -a /etc/pam.d/su +echo "=== [setup_base.sh] Setting up IMDS protection ===" + +apt-get install -y nftables +cp /tmp/common/assets/imds-protection.nftables.conf /etc/nftables.conf +cp /tmp/common/assets/imds-protection.service /etc/systemd/system/imds-protection.service +systemctl enable imds-protection.service + echo "=== [setup_base.sh] Complete ==="