I'm attempting to lockdown an Amazon EC2 instance which has a single open port for Amazon SNS. I can't use security groups to restrict the port as the IP is forever changing, so it must be open to all there and then secured with IPtables.
All I need to do is drop all connections to the port except from local, and then accept connections from the SNS endpoint eg. sns.us-west-1.amazonaws.com
eg.
#!/bin/bash
# Deny all except localhost on 8080
iptables -A INPUT ! -s 127.0.0.1 -p tcp -m tcp --dport 8080 -j DROP
# Run every 5 minutes and whitelist resolved AWS SNS IP
iptables -I INPUT -p tcp -s sns.us-west-1.amazonaws.com --dport 8080 -j ACCEPT
The problem is that the sns endpoint "sns.us-west-1.amazonaws.com" is regularly changing IP.
If I run that iptables rule, it will add an ACCEPT rule for a new IP as it continually changes. This list of IP's is not freely available from Amazon as far as I can tell.
If I can have IPtables allow specifically from the endpoint eg. "sns.us-west-1.amazonaws.com" then I'm good, but as far as I understand this is not possible as it always resolves rules to IP.
The only workaround I can think of in lieu of a maintained public list of SNS IP ranges from amazon that I can query and whitelist, is to run a cron every few minutes whitelisting the endpoint and whatever IP it happens to resolve to.
This raises the issue of the -I or -A and the -C flags for iptables. I can't run -C on the first run as it finds nothing and errors. I can't run -I as it will add duplicate IP's everytime it encounters one.
How can I do the following:
1) always have the DENY rule: iptables -A INPUT ! -s 127.0.0.1 -p tcp -m tcp --dport 8080 -j DROP
2) add a rule to allow source "sns.ap-southeast-2.amazonaws.com" on 8080, but first check if a matching rule exists for the resolved IP at that time.