Automate Security Group Compliance with AWS Config, Lambda, and SNS

Table of contents

Overview
Security is a primary concern in today's hectic cloud environments. Limiting network access to your instances is one of the most important aspects of cloud security. Your AWS instances' virtual firewalls are called EC2 Security Groups, and setup errors that leave SSH (port 22) or RDP (port 3389) open to the public can result in serious security flaws. This article presents an automated method that uses AWS Config, AWS Lambda, and SNS to identify and notify users of such misconfigurations.
The Importance of Security Groups and Their Misconfigurations
As a kind of firewall, AWS Security Groups manage incoming and outgoing traffic for EC2 instances. On critical ports like 22 (SSH) and 3389 (RDP), misconfigurations, like permitting incoming traffic from 0.0.0.0/0 (public access), provide a serious security risk. These open ports put your EC2 instances at risk of illegal access and brute-force attacks, which could jeopardize the security of your data and system.
It is essential to make sure that EC2 Security Groups are set up correctly in order to avoid these vulnerabilities, particularly as your AWS infrastructure grows.
Why Automate Security Group Compliance?
In big environments, manually verifying and auditing Security Groups takes a lot of effort and is prone to mistakes. AWS Config is useful in this situation. You can log configuration changes and keep an eye on your AWS resources with AWS Config. We can go one step further, though, by automating compliance checks to make sure Security Groups follow best practices, including keeping important ports private.
Solution Architecture
How AWS Config + Lambda + SNS Work Together
AWS Config detects a change (e.g., Security Group modified).
Config Rule (custom) triggers the Lambda function.
Lambda analyzes the Security Group configuration.
If NON_COMPLIANT (e.g., 0.0.0.0/0 on port 22 or 3389):
Lambda fetches the SNS topic ARN from SSM Parameter Store.
Lambda sends an alert via SNS to notify the security team.
SNS delivers notifications via email
This ensures real-time alerting and visibility for high-risk network exposures.
Step-by-Step Implementation
1. Create a Config Rule to Detect Security Group Misconfigurations
First, you need to create a custom AWS Config rule that triggers when a Security Group is modified. Here’s how to set up a basic Config Rule for monitoring EC2 Security Groups:
SGComplianceConfigRule:
Type: AWS::Config::ConfigRule
Properties:
ConfigRuleName: !Ref RuleName
Description: Checks if EC2 Security Groups allow inbound access from 0.0.0.0/0 on ports 22, 3389
Scope:
ComplianceResourceTypes:
- AWS::EC2::SecurityGroup
Source:
Owner: CUSTOM_LAMBDA
SourceIdentifier: !ImportValue LambdaFunctionArn
SourceDetails:
- EventSource: aws.config
MessageType: ConfigurationItemChangeNotification
This rule ensures that any change to EC2 Security Groups triggers the Lambda function for evaluation.
2. Lambda Function for Security Group Compliance Check
Now, we need to create the Lambda function that will evaluate whether the Security Group is compliant with our policies. The function checks if any inbound traffic is allowed from 0.0.0.0/0 on ports 22 or 3389. If such a configuration is found, the function will mark it as NON_COMPLIANT.
Here’s the Python code for the Lambda function:
def evaluate_compliance(configuration_item):
if configuration_item['resourceType'] != 'AWS::EC2::SecurityGroup':
return 'NOT_APPLICABLE', "Resource is not a Security Group."
security_group = configuration_item.get('configuration', {})
group_id = configuration_item.get('resourceId', 'unknown')
if 'ipPermissions' in security_group:
for permission in security_group['ipPermissions']:
from_port = permission.get('fromPort')
to_port = permission.get('toPort')
ip_ranges = permission.get('ipRanges', [])
for ip_range in ip_ranges:
if isinstance(ip_range, dict):
cidr = ip_range.get('cidrIp')
elif isinstance(ip_range, str):
cidr = ip_range
else:
cidr = None
if cidr == '0.0.0.0/0':
if from_port in [22, 3389] or (from_port is None and to_port is None):
message = (
f"Security Group {group_id} allows inbound access from 0.0.0.0/0 "
f"on port {from_port}."
)
return 'NON_COMPLIANT', message
return 'COMPLIANT', "Security Group is compliant."
This Lambda function checks the configuration of each Security Group and sends a notification if it finds any non-compliant rules.
3. SNS Integration for Notifications
To ensure that your security team gets alerted, we use Amazon SNS to send notifications. The Lambda function will publish messages to a pre-configured SNS topic whenever a non-compliant Security Group is detected.
You can store the SNS Topic ARN in SSM Parameter Store and retrieve it in the Lambda function. This ensures that your SNS topic is managed securely and can be changed without updating the Lambda code.
Best Practices for EC2 Security Groups
Some recommended practices for administering EC2 Security Groups include automating security group compliance checks and the following:
Apply the Least Privilege Principle: Always limit access to the IPs or CIDRs that need it.
Group EC2 instances according to their functions and assign distinct security groups to each role by segmenting security groups.
Regularly check security groups to make sure that open ports and IP ranges are still required for the EC2 instances to operate.
Conclusion
This solution allows you to swiftly identify when vulnerable ports are open to the public and automate the monitoring of EC2 Security Groups. You can build a strong security framework that continuously scans your AWS environment and instantly notifies your security team by utilizing AWS Config, Lambda, and SNS.
Automating security controls like this reduces manual effort, minimizes errors, and improves your cloud infrastructure’s security posture.
Get the Code
Our GitHub repository contains the whole code for this solution. It comes with all the tools you need to get started right away, including Lambda functions and configuration templates.
Link: https://github.com/Utkarshlearner/aws-sg-compliance-checker
Deployment Steps Using AWS CLI Commands
🚀 Deployment Steps
Make sure the AWS CLI is configured (aws configure) before running these commands.
1) Create IAM Role
aws cloudformation create-stack --stack-name SG-Compliance-IAM-Stack --template-body file://iam.yaml --capabilities CAPABILITY_NAMED_IAM
2) Create SNS
aws cloudformation create-stack --stack-name SG-Compliance-SNS-Stack --template-body file://sns.yaml --capabilities CAPABILITY_NAMED_IAM
3) Create Lambda
aws cloudformation create-stack --stack-name SG-Compliance-Lambda-Stack --template-body file://lambda.yaml --capabilities CAPABILITY_NAMED_IAM
4) Create Config Rules
aws cloudformation create-stack --stack-name SG-Compliance-ConfigRules-Stack --template-body file://configrules.yaml --capabilities CAPABILITY_NAMED_IAM
"Thank you for reading! If you found this blog helpful, don't forget to subscribe and follow for more insightful content. Your support keeps me motivated to bring you valuable insights. Stay updated and never miss out on our latest posts. Feel free to leave comments or suggestions for future topics. Happy learning!"
https://awslearner.hashnode.dev/amazon-web-services-via-category
https://awslearner.hashnode.dev/aws-beginner-level-project-ideas
Subscribe to my newsletter
Read articles from Utkarsh Rastogi directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Utkarsh Rastogi
Utkarsh Rastogi
👨💻 AWS Cloud Engineer | Around 6 years of Corporate Experience | Driving Innovation in Cloud Solutions 🔧 Day-to-Day Tasks: Specialize in creating AWS infrastructure for Migration Projects. Leveraging services such as S3, SNS, SQS, IAM, Lambda, System Manager, Kinesis, OpenSearch, Cognito, Storage Gateway, Cloud Watch, API Gateway, AWS Event Scheduler, Secret Manager, ECS, Application Load Balancer, VPC among others. Additionally, I excel in crafting Splunk Dashboards and implementing alerting mechanisms for Cloud Watch logs to monitor failures. My approach involves constructing AWS infrastructure using the Serverless framework and Cloud Formation templates, while automating tasks through Boto3 (Python Scripting) Lambdas. 🎯 Passion: I am deeply passionate about continuously learning new technologies and eagerly anticipate the transformative impact of cloud computing on the tech landscape. 📧 Connect: Feel free to reach out to me at awslearningoals@gmail.com. Let's connect and explore potential collaborations! https://www.linkedin.com/in/rastogiutkarsh/