Last active
December 5, 2017 11:49
-
-
Save pandeybk/403d1b2a1154281960c8a2afd1a0adb5 to your computer and use it in GitHub Desktop.
Lambda function, trigger email using SES and alert publicly open security group
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import boto3 | |
ec2 = boto3.client('ec2') | |
ses = boto3.client('ses') | |
def email_service(email_title, email_body): | |
fromaddr = '[email protected]' | |
toaddr = '[email protected]' | |
bcc = '[email protected]' | |
response = ses.send_email( | |
Source=fromaddr, | |
Destination={ | |
'ToAddresses': [ | |
toaddr, | |
], | |
'BccAddresses': [ | |
bcc | |
] | |
}, | |
Message={ | |
'Subject': { | |
'Data': email_title, | |
'Charset': 'UTF-8' | |
}, | |
'Body': { | |
'Html': { | |
'Data': email_body, | |
'Charset': 'UTF-8' | |
} | |
} | |
} | |
) | |
def alert_security_group_by_source(): | |
alert_sources = ['0.0.0.0/0', '8.8.8.8/8'] | |
allowed_security_group = ['sg-bgy574da', 'sg-4ok56e29'] | |
allowed_ports= ['80', '443'] | |
alert_security_group(alert_sources, allowed_security_group, allowed_ports) | |
def alert_security_group(alert_sources, allowed_security_group, allowed_ports): | |
email_title="Urgent: Security rules with inbound source of " + str(alert_sources) + " detected " | |
email_body="Security rules with inbound source of " + str(alert_sources) + " detected </br> </br>" | |
groupfound=0 | |
security_group_list = ec2.describe_security_groups() | |
for security_group in security_group_list['SecurityGroups']: | |
for ip_rule in security_group['IpPermissions']: | |
try: | |
for ip_range in ip_rule['IpRanges']: | |
if(ip_range['CidrIp'] in alert_sources and security_group['GroupId'] not in allowed_security_group and str(ip_rule['FromPort']) not in allowed_ports): | |
groupfound=1 | |
email_body+="Security Group Id: " + security_group['GroupId'] + " Port Range: " + str(ip_rule['FromPort'])+ " Inbound Source: " + ip_range['CidrIp'] + " </br>" | |
except Exception as e: | |
e | |
if(groupfound==1): | |
email_service(email_title, email_body) | |
def lambda_handler(json_input, context): | |
alert_security_group_by_source() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment