15

The AWS EC2 Instance Metadata API provides a lot of useful functionality. Anyone on the actual EC2 instance can make a call to http://169.254.169.254/ and see metadata for the instance the call was made from. The security of the API is such that it only checks that the call originates from the instance. Therefore, if I am allowing someone to run code on my instance I would like to know how to best block access to that particular url while retaining access myself.

As a highlight, I was surprised to find that the Metadata API can be also accessed via http://instance-data/ (which I found by accident somewhere).

I am able to inspect the urls being called by all of the code running on this instance, but I assume that this is not a good approach given IPv6 addresses (possibly), or some weird URI encodings that would resolve into the Metadata IP (169.254.169.254), or some undocumented (it seems) URLs like http://instance-data/.

Tristan
  • 273
  • 2
  • 8

1 Answers1

25

Firewall it off.

iptables -A OUTPUT -m owner ! --uid-owner root -d 169.254.169.254 -j DROP

This rule prohibits any user other than the root user from opening connections to 169.254.169.254.

Michael Hampton
  • 237,123
  • 42
  • 477
  • 940
  • Will this not prevent the the "normal" usage of this service. Typically the service is called by/obo the EC2 user who is almost never the root. – Sam-T Jan 02 '20 at 17:06
  • @Sam-T If you need the ec2-user to access it, you can certainly write a rule to allow that as well. – Michael Hampton Jan 02 '20 at 19:31
  • If you prevent at the firewall level- to allow only root, not sure how you would enable it for the EC2 user (I just dont know). By EC2 user - I mean whoever started the instance- my understanding is metadata is accessed by this (and any other) EC2 user on the instance. Could you give example – Sam-T Jan 02 '20 at 19:47