Continuing with Boto: Find security group having port 22 open for all

05 / May / 2015 by Vikash Jha 0 comments

Consider a use case where in any team members have opened port 22 for 0.0.0.0/0 inside an EC2 security group and forgot, which is a big security concern for the Instances.

So I have written a script using python boto library which scans all the security groups of running / stopped instances and sends an email to all stakeholders on daily/weekly basis if port 22 is open for all. This script uses SNS API calls to send an email if defined rule matches.

This script has few prerequisites

1) Create an SNS topic and configure subscription.

Once you create SNS topic, you get an end point that you need to configure in scripts.

2) Configure IAM User / Role with required policy.

import sys
import boto
from boto import ec2
from boto import sns
connection=ec2.connect_to_region("region-name")
connSNS = boto.sns.connect_to_region("region-name")
sg=connection.get_all_security_groups()

listOfInstances=""
messages="Following Instances have port 22 open"

def getTag(instanceId):
    reservations=connection.get_all_instances(filters={'instance_id':instanceId})
    for r in reservations:
        for i in r.instances:
            return i.tags['Name']

try:
    for securityGroup in sg:
        for rule in securityGroup.rules:
            global instanceId;
            if (rule.from_port=='22' and rule.to_port == '22') and '0.0.0.0/0' in str(rule.grants):
                for instanceid in securityGroup.instances():
                    instanceId=str(instanceid)
                    listOfInstances += "Instance Name : " + getTag(instanceId.split(':')[1]) + "\t State:" + instanceid.state + "\t SecurityGroup:" +securityGroup.name + "\n"
                    connSNS.publish(topic='SNS-topic-arn-endpoint',message = messages + "\n" + listOfInstances, subject='ProjectName : Server List with Port 22 Open')

except :
    print 'Some Error occurred : '
    print sys.exc_info()
    connSNS.publish(topic='SNS-topic-arn-endpoint',message = sys.exc_info(), subject='script ended with error')

You can schedule this script as a cron on a daily basis to get the report over the email. You can download these scripts from our github profile AWS-Boto-Scripts.

Leave a comment if you have any questions regarding this article.

FOUND THIS USEFUL? SHARE IT

Leave a comment -