condescendent
condescendent

Reputation: 33

How can retrieve all the security group IDs and save them into a iterable list?

I want to loop through all the security groups and find those with rules wide open to internet on any ports.

# This script is for identifying security groups with rules with open to internet.


import boto3

def inspect(thing):
        print("Funcs: "+str(dir(thing)))
        for key in list(thing):
                print("   "+key+": "+str(thing[key]))

ec2 = boto3.resource('ec2')
security_group = ec2.SecurityGroup('id')
type = inspect(security_group)
print ("type")

for i in security_group:
    try:
        response = client.describe_security_groups(GroupIds=[i])
        print(response)
    except ClientError as e:
        print(e)

Upvotes: 0

Views: 752

Answers (1)

Vikyol
Vikyol

Reputation: 5615

You can use EC2 low-level client to fetch all security groups. describe_security_groups() returns a dictionary object as a response. So you just need to iterate over it to evaluate your security group rules.

import boto3

client = boto3.client('ec2')
response = client.describe_security_groups()

for sg in response['SecurityGroups']:
    for ingressrule in sg['IpPermissions']:
        print(ingressrule.get('FromPort', -1))
        print(ingressrule.get('ToPort', -1))
        for iprange in ingressrule['IpRanges']:
            print(iprange.get('CidrIp', -1))

You can also use the filters to list only the ingress rules with wide-open access:

client.describe_security_groups(Filters=[
    {
      "Name": "ip-permission.cidr",
      "Values": ["0.0.0.0/0"]
    }
])

Upvotes: 2

Related Questions