I’ve been using Amazon Lightsail, which is kind of an “EC2-lite” to host my VPN server. It’s quick to set up and tear down, but one limitation is that, unlike traditional EC2, you can’t granularly control access to firewall ports from Amazon’s web UI. You open the port or close it, it’s all or nothing. While I might leave the VPN port open to access via mobile device, I don’t really want SSH open to the world. In addition, you can access Lightsail using Amazon’s web console, so you don’t even really need SSH open to yourself, just Amazon’s internal network.
What follows is a quick how-to for blocking access to your system using iptables, excerpted from my book, The Seven Minute Server: Build Your Own VPN.
Note that this procedure assumes you’re running a VPN on the system and want to block SSH, and thus includes rules to allow access from IPs you might use to access the system if connected to the VPN. Switch
-p tcp and
--dport 22 to whichever port/protocol you need to block.
Using iptables to Block Outside Access to Your Systems
Open the Lightsail console, tap the menu next to your instance, and select Connect.
lastto show the last IP addresses that accessed the system; this will show our internal network via the web console. For instance, if all connections came from between 126.96.36.199 through 188.8.131.52, we can assume Amazon is using this network block to manage Lightsail.
Once in, enter the following command to allow the web-based console connection (184.108.40.206/8), the internal EC2 network (220.127.116.11/12), the internal VPN network (10.0.0.0/8), the VPN server’s external address (s.s.s.s/32 below; add your VPN server’s external IP here instead) and any IP address you normally use to connect via SSH into the system:
$ sudo iptables -A INPUT -p tcp -s 18.104.22.168/12 --dport 22 -j ACCEPT $ sudo iptables -A INPUT -p tcp -s 10.0.0.0/8 --dport 22 -j ACCEPT $ sudo iptables -A INPUT -p tcp -s 22.214.171.124/24 --dport 22 -j ACCEPT $ sudo iptables -A INPUT -p tcp -s s.s.s.s/32 --dport 22 -j ACCEPT $ sudo iptables -A INPUT -p tcp -s y.y.y.y/32 --dport 22 -j ACCEPT
Run the following command to show your changes to the INPUT chain and review them. Make sure they are correct or you may be locked out (restart the system to clear the rules if you goof up!):
$ sudo iptables -L INPUT
If you need to delete any rules, use the same syntax, but replace the -A with a -D, for example:
$ sudo iptables -D INPUT -p tcp -s 126.96.36.199/12 --dport 22 -j ACCEPT
Once you’ve got these in, you’re ready to block port 22 to everyone else:
$ sudo iptables -A INPUT -p tcp --dport 22 -j DROP
Make sure you still have access! If not, you can reboot the system to clear your changes. If the changes are good and you can still access your server via SSH, save your changes and restart:
$ sudo service iptables save && sudo service iptables restart
If you’re logged on using the web console, you may get kicked off during restart. You can click Reconnect to reconnect.