Securing Your Network Using Auto-Updating Security Groups

Posted on Thu 17 December 2015 in aws

We all know that no ports should be open to the internet for development purposes, but for convenience it's common to find a security group with port 22 (SSH) open to . Even narrower ingress rules can create backdoors.

Here we'll show you how to create an auto-updating security group that adds your active WAN IP address when you connect. This way, only your active IP is authorized.

Create the "development" security group with no ingress

aws ec2 create-security-group --group-name=development --group-description="ssh access for my dev machine"

Create a limited role that can only update this security group

Since you may want to embed this script on your router or elsewhere, it's important to generate a restricted access key that can only do one thing Create a user and add this policy

Make sure you put your account id & SG id in the role

    "Version": "2012-10-17",
    "Statement": [
            "Sid": "Stmt1450378262000",
            "Effect": "Allow",
            "Action": [
            "Resource": [

Add a Shell function to automate the process

Put this function into your .bashrc or .zshrc so you can trigger it either manually or when you connect to the internet.

aws-open-ssh() {
  aws ec2 authorize-security-group-ingress --group-id sg-xxxxxxx --protocol tcp --port 22 --cidr $(dig +short

Run the function and check that your WAN IP has been added

$ aws-open-ssh
# show your wan-ip (yours will be a real addr)
$ dig +short
$ aws ec2 describe-security-groups --group-ids sg-xxxxxxx|jq '.SecurityGroups[].IpPermissions'
    "PrefixListIds": [],
    "FromPort": 22,
    "IpRanges": [
        "CidrIp": ""
    "ToPort": 22,
    "IpProtocol": "tcp",
    "UserIdGroupPairs": []

Attach this group to any development resources you actively connect to.

Now that the security group can be updated, add this group to any development resources, e.g. EC2 instances, RDS instances etc.

With this technique, you won't be tempted to open ports 22 or 3306 to the internet. By making security-group changes convenient, you keep them more secure.