Wednesday, February 28, 2018

AWS Adding Security Group Ingress rule

Bulk editing your Security Group Ingress rules

Need to add/delete rules to all the Security Group in your account? Here's how to do it in PowerShell. 


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
#Get list of all security group under this account
#we assume AWS configure has been ran and output has been set to JSON
$sgs = aws ec2 describe-security-groups --query 'SecurityGroup[]{Name:GroupName,Id:GroupId}'
#convert this json output to 
$ps_sgs = $sgs | out-string | convertfrom-json
foreach($sg in $ps_sgs){
   #below line adds a rule to each SG
   aws ec2 authorize-security-group-ingress --group-id $sg.id --protocol -1 --port 0-65535 --cidr x.x.x.x/32
   #Uncomment below to revoke the rules
   #aws ec2 revoke-security-group-ingress --group-id $sg.id --protocol -1 --port 0-65535 --cidr x.x.x.x/32
}

Explanation: 

Line 3: describe-security-groups command returns list of all security groups and their attributes of the account where this command is ran. To limit the amount of output, we query the command to only want GroupName and GroupID. We really just need GroupID, but in case we want to do any friendly output or log as we go along. We know these two attributes by looking at the output without the --query flag:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
{
    "SecurityGroups": [
        {
            "IpPermissionsEgress": [],
            "Description": "My security group",
            "IpPermissions": [
                {
                    "PrefixListIds": [],
                    "FromPort": 22,
                    "IpRanges": [
                        {
                            "CidrIp": "203.0.113.0/24"
                        }
                    ],
                    "ToPort": 22,
                    "IpProtocol": "tcp",
                    "UserIdGroupPairs": []
                }
            ],
            "GroupName": "MySecurityGroup",
            "OwnerId": "123456789012",
            "GroupId": "sg-903004f8",
        }
    ]
}

Line 5: Convert the JSON output to PowerShell object.
Line 6: We can iterate through this PowerShell object applying next AWS command to each Security Group.
Line 8: This is how we add ALL ALL allow from this IP Address. The result would look as follows:
Line 9: This is how to remove ingress rules from this security group

References:

AWS EC2 describe-security-groups
PowerShell convertfrom-json

No comments:

Post a Comment

AWS WAF log4j query

How to query AWS WAF log for log4j attacks 1. Setup your Athena table using this instruction https://docs.aws.amazon.com/athena/latest/ug/wa...