Skip to content

Instantly share code, notes, and snippets.

@pandeybk
Last active December 5, 2017 11:49
Show Gist options
  • Save pandeybk/403d1b2a1154281960c8a2afd1a0adb5 to your computer and use it in GitHub Desktop.
Save pandeybk/403d1b2a1154281960c8a2afd1a0adb5 to your computer and use it in GitHub Desktop.
Lambda function, trigger email using SES and alert publicly open security group
import boto3
ec2 = boto3.client('ec2')
ses = boto3.client('ses')
def email_service(email_title, email_body):
fromaddr = 'sesverified@email.address'
toaddr = 'email@addresses.com'
bcc = 'email@addresses.com'
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