AWS security groups: A refresher
AWS security groups act as virtual firewalls that control inbound and outbound traffic for Amazon EC2 instances and cloud workloads. Each security group consists of rules that filter traffic and allow or deny requests based on parameters like IP protocol, port number, and source/destination IP address or CIDR block. You can link an instance to one or more security groups when you create it.
To help with this, AWS automatically supplies a security group for each virtual private cloud (VPC) by default.
You can adhere to AWS default security group best practices by customizing and creating custom security groups for your application needs.
AWS Security Group Best Practices [Cheat Sheet]
In this 10 page cheat sheet we'll cover best practices for AWS Security Groups in the following areas: Traffic management, Advanced monitoring, Automation and scalability, Security enhancements.
Download Cheat SheetBest practices and recommendations for AWS security groups
Below are 10 foundational steps to establish effective AWS security groups for your AWS account:
Implement granular access control with AWS security groups
The principle of least privilege (PoLP) ensures that resources are accessible only to entities that absolutely need them. Follow these tips to implement the least-privilege principle effectively:
Start with a “deny-all” rule: This rule blocks unintended traffic, which is a foundational step in AWS best practices for security groups. By denying all traffic by default, you can create a secure baseline and then explicitly allow only necessary traffic. Use this code to create a security group with a “deny-all” default setting:
aws ec2 create-security-group --group-name MySecurityGroup --description "My security group with deny-all default"
Allow specific IPs or CIDR blocks: Opening up your resources to the entire Internet (0.0.0.0/0) is a significant security risk. Wiz recommends being as selective about access as possible when defining your security group rules to minimize your potential attack surface.
Consider the principle of granularity: If only one IP address needs access to a resource, don’t allow access to an entire CIDR block. Use this code to grant access to a specific CIDR block in your security group for SSH (port 22):
aws ec2 authorize-security-group-ingress --group-name MySecurityGroup --protocol tcp --port 22 --cidr 201.0.100.0/24
2. Design security group rules based on user roles
By categorizing your AWS EC2 instances based on their roles, you can tailor security groups to each role’s specific needs. Role-based access ensures that only necessary ports are open for each instance type, which reduces potential vulnerabilities.
For instance, a database server might only need its database port (like 3306 for MySQL) open, while a web server might require ports 80 and 443:
aws ec2 authorize-security-group-ingress --group-name WebServerSG --protocol tcp --port 80 --cidr 0.0.0.0/0 aws ec2 authorize-security-group-ingress --group-name WebServerSG --protocol tcp --port 443 --cidr 0.0.0.0/0
3. Insider security groups’ stateful nature
Due to the stateful nature of AWS security groups, if an inbound rule allows traffic from a specific IP, it also automatically allows return traffic, even if there’s no corresponding outbound rule. For instance, the following security group will allow two-way traffic over port 80 for the CIDR range:
aws ec2 authorize-security-group-ingress --group-name MySecurityGroup --protocol tcp --port 80 --cidr 201.0.100.0/24
Actionable AWS Security Best Practices [Cheat Sheet]
This cheat sheet goes beyond the essential AWS security best practices and offers actionable step-by-step implementations, relevant code snippets, and industry- leading recommendations to fortify your AWS security posture.
Download now4. Aoid overly permissive rules
Overly permissive rules can expose your resources to unnecessary risks. Because of this, it’s essential to strike a balance between accessibility and security.
Follow these two best practices to strike that balance:
Mitigate the risks of 0.0.0.0/0: Allowing traffic from all IPs with a 0.0.0.0/0 CIDR range can expose your resources to various threats, from brute force attacks to potential data breaches. Because of this, sensitive ports like SSH (22) or RDP (3389) shouldn’t be public. (That said, remember to restrict access only to IPs or CIDR blocks that genuinely need it.) For instance, the following can open your resources to potential brute-force attacks from all over the world:
aws ec2 authorize-security-group-ingress --group-name MySecurityGroup --protocol tcp --port 22 --cidr 0.0.0.0/0
Add trusted IPs to your allowlist: Instead of focusing on what to block, focus on what to allow. Adopting an allowlist approach ensures that only known and trusted entities can access your resources. For instance, if you have an API server, allow only traffic that comes from trusted sources on ports 80 and 443:
aws ec2 authorize-security-group-ingress --group-name MySecurityGroup --protocol tcp --port 22 --cidr 180.170.1.0/24
5. Carry out regular audits
As your infrastructure grows and changes, it’s crucial to regularly audit your security groups to ensure that they align with best practices and your organization’s requirements.
Using tools to automate the audit process can save time and help you streamline your processes. AWS offers various services, like AWS Config, that can monitor changes in your security groups and make sure that they comply with best practices. This proactive approach can identify and rectify potential issues promptly for greater peace of mind.
The following code snippet sets up an AWS Config rule named “restricted-ssh” that checks if security groups allow unrestricted SSH traffic and ensures that only the specified CIDR block (201.0.111.0/24) has access to port 22:
aws configservice put-config-rule --config-rule '{
"ConfigRuleName": "restricted-ssh",
"Description": "Checks whether security groups allow unrestricted SSH traffic",
"Scope": {
"ComplianceResourceTypes": ["AWS::EC2::SecurityGroup"]
},
"Source": {
"Owner": "AWS",
"SourceIdentifier": "RESTRICTED_INCOMING_TRAFFIC"
},
"InputParameters": "{\"blockedPort1\":\"22\",\"allowedCidr\":\"201.0.111.0/24\"}"
}'
6. Name and describe security groups
Properly naming and describing your security groups can simplify management, especially as your infrastructure grows.
You can start this process by using standardized naming conventions. This will help you quickly identify a security group’s purpose, particularly when you’re dealing with multiple groups across different environments and projects.
Using a format like <ProjectName>-<Environment>-<Role> provides clarity at a glance. For instance, naming a security group “MyApp-Prod-WebServer” instantly conveys its purpose.
aws ec2 create-security-group --group-name MyApp-Prod-WebServer --description "Production WebServer for MyApp"
7. Restrict outbound traffic
While controlling inbound traffic is essential, managing outbound traffic from your EC2 instances is just as crucial. To do this, consider implementing the following practices:
Prevent data exfiltration: Unrestricted outbound traffic can lead to potential data breaches, where malicious entities might exfiltrate sensitive data from your instances. For example, it could be helpful to restrict outbound traffic to allow only HTTPS (port 443) traffic:
aws ec2 authorize-security-group-egress --group-id sg-0123456789abcdef0 --protocol tcp --port 443 --cidr 0.0.0.0/0
Customize access for third-party integrations: You should also ensure that your instances communicate exclusively with trusted external services. If you fail to exclude bad actors, unrestricted access can expose your resources to vulnerabilities in third-party services. If you need to integrate third-party services, allow outbound traffic only on a specific external service IP:
aws ec2 authorize-security-group-egress --group-id sg-0123456789abcdef0 --protocol tcp --port 443 --cidr <Third-Party-Service-IP>/32
8. Integrate with AWS flow logs
Flow logs provide a deep look into your VPC traffic and aid in monitoring and troubleshooting. Practice the following steps to use these logs effectively:
Maintain visibility: By analyzing flow logs, you can understand traffic patterns, detect anomalies, and troubleshoot connectivity issues. Enabling flow logs for a VPC is straightforward:
aws ec2 create-flow-logs --resource-type VPC --resource-ids vpc-0123456789abcdef0 --traffic-type ALL --log-destination-type cloud-watch-logs --log-group-name MyFlowLogs
Implement a retention policy: You can also set up policies for how long to retain your logs by balancing storage costs and historical data needs. For instance, you can set a retention policy of 30 days for a CloudWatch Logs group:
aws logs put-retention-policy --log-group-name MyFlowLogs --retention-in-days 30
9. Create backup and recovery protocols
Backing up your security group configurations and ensuring quick restoration is crucial for business continuity. Follow these best practices for best results:
Back up your security group rules: Regularly back up your security group rules to ensure that you can quickly recover from misconfigurations or failures. It’s easy to get a security group description and save it as a JSON file:
aws ec2 describe-security-groups --group-names MyWebSG > MyWebSG-backup.json
Plan for disaster recovery: In case of emergencies or failures, have a plan in place to restore your security groups from backups. This plan should include the steps to follow and the personnel responsible for each action. Regularly review and test this plan to ensure its effectiveness.
10. Implement IAM policies to control group management
By building effective IAM integrations with security groups, you can improve your security posture for authorized users and protect your infrastructure. This adds more accountability and stronger layers of access control.
To do this, follow these processes:
Create IAM policies: Clearly define who can modify or create security groups and rules so only authorized users have permission to make approved changes. For example, if your organization has separate development teams for finance and customer support departments, these groups would have different permissions based on the team member and their role.
Add conditional access controls: When users can work anywhere, anytime, and on any device, you have many more threats to consider. To counteract this, implement conditions in your policies to restrict group modifications based on criteria like time, specific IP address, multi-factor authorization, and more. One example of conditional access controls would be making certain changes that are applicable only during business hours.
By following these best practices and regularly reviewing and updating your configurations, you can ensure that your AWS resources remain secure and resilient against potential threats.
Security group considerations for hybrid cloud architectures
While hybrid cloud architectures provide flexibility and accessibility for industries, teams, and customers, they also present challenges for security groups.
Many of these processes include two distinctions:
Role-based access control: Assign permissions based on the user role so that only the correct user can access appropriate resources to minimize risks and simplify management.
Attribute-based access control: Grant permissions based on user attributes (like department or location) so there’s more flexibility for access control.
The following considerations can help you ensure that you’re operating a secure cloud environment across your organization:
Access control and data protection
By implementing and managing access permissions, your security team ensures that only authorized users can access sensitive data and devices at the right time. Through user, group, and role designations, you can assign permissions based on PoLP, like applying consistent privilege and policies on the cloud and on-premise, defining permission-based roles, and auditing and logging activity for compliance and security.
Your DevSecOps team can combine these practices using zero trust principles and architecture, with encryption to enhance security and protect the data itself, whether it’s at rest or in transit. Devs can also choose encryption based on storage types (such as object storage or volumes), implement secure encryption key storage, and use strong cryptographic algorithms that align with the latest industry standards.
Secure configuration and patch management
Hybrid cloud configurations should minimize vulnerabilities and prioritize secure interactions between platforms. To accomplish this, your organization can apply security hardening standards and establish frameworks like CIS Benchmarks.
Additionally, you can:
Separate sensitive data from less critical resources to minimize exposure changes.
Establish proactive security controls and actions, like monitoring and preventing unauthorized access, to strengthen the overall architecture.
Adopt best practices for secure configuration and patch management to manage security groups much more efficiently. For example, you can maintain system integrity with updates and patches.
Update your systems through testing (without interrupting the infrastructure) and implement critical patches quickly as you plan for bigger updates. That way, if there’s a greater issue, you’ll have a rollback plan in place in case you have an issue with a patch.
Continuous monitoring and visibility
We can’t protect what we can’t see.
Menno Vanderlist, Director of Sales Engineering, Wiz
It’s challenging to manage what you can’t measure. That’s why continuous monitoring and observability are crucial elements for security groups.
The key to improved monitoring starts with assertiveness. According to Menno Vanderlist, Wiz’s director of sales engineering, “We want to become proactive. [...] Fix the security issues ahead of them becoming an actual concern.” Through an organized, proactive approach to monitoring and security, you can prevent more threats in the future.
Practices like the following can improve your security posture:
Implement real-time monitoring to detect anomalies and unauthorized access.
Automate log analysis to correlate activity and identify security incidents.
Continuously validate compliance to prevent configuration drift.
Enable anomaly detection for proactive threat response.
Integrate security tracking with incident response for faster remediation.
You can implement practices like those in the following example:
import boto3
import json
from datetime import datetime, timedelta
def get_security_group_changes(region):
client = boto3.client('cloudtrail', region_name=region)
# Set the time range for the past 24 hours
end_time = datetime.utcnow()
start_time = end_time - timedelta(days=1)
response = client.lookup_events(
LookupAttributes=[
{
'AttributeKey': 'EventName',
'AttributeValue': 'AuthorizeSecurityGroupIngress'
},
{
'AttributeKey': 'EventName',
'AttributeValue': 'RevokeSecurityGroupIngress'
}
],
StartTime=start_time,
EndTime=end_time
)
return response['Events']
def analyze_security_group_changes(events):
for event in events:
event_name = event['EventName']
event_time = event['EventTime']
user_name = event['Username']
resources = event['Resources']
print(f"Event: {event_name}")
print(f"Time: {event_time}")
print(f"User: {user_name}")
print("Affected Resources:")
for resource in resources:
print(f" - {resource['ResourceName']}")
print("---")
def main():
region = 'us-west-2' # Replace with your desired region
events = get_security_group_changes(region)
analyze_security_group_changes(events)
if __name__ == "__main__":
main()
When these processes are in place, your team can analyze data and collect insights to optimize security and system reliability.
Amazon AWS security group rule examples by use case
Below are three ways you can use AWS security group rules:
1.Web server security
Use case: Hosting a website or web app that’s accessible through HTTP and HTTPS
Rule Type | Protocol | Port Range | Source |
---|---|---|---|
Inbound | TCP | 80 (HTTP) | 0.0.0.0/0 (Anywhere) |
Inbound | TCP | 443 (HTTPS) | 0.0.0.0/0 (Anywhere) |
Outbound | TCP | All | 0.0.0.0/0 (All traffic out) |
Best practice: Restrict access to specific IPs for enhanced security as you review traffic.
2. SSH access for admins
Use case: Securing remote logins to an EC2 instance with SSH
Rule Type | Protocol | Port Range | Source |
---|---|---|---|
Inboudn | TCP | 22 (SSH) | Public IP |
Best practice: Don’t allow 0.0.0.0/0 for SSH. Instead, you should limit access to trusted IPs and use multi-factor authentication.
3. Database server security
Use case: Allowing secure database connections from a web application server (like MySQL, PostgreSQL, or MongoDB)
Rule Type | Protocol | Port Range | Source |
---|---|---|---|
Inbound | TCP | 3306 (MySQL) | Web server security group |
Inbound | TCP | 5432 (PostgreSQL) | Web server security group |
Inbound | TCP | 27017 (MongoDB) | Web server security group |
Best practice: Use security group references instead of IP addresses to allow only specific users.
While these are some examples of use cases and rules for security groups, it’s important to remember that you should tailor access based on your security needs. While public-facing groups might welcome all traffic, restricting access to areas or IP addresses that produce traffic with known threats could help you mitigate future risks.
Secure and optimize your AWS infrastructure
As you become more familiar with AWS security groups and start to master the foundational best practices, it’s essential to explore advanced tools and integrations that can further enhance your security posture. These can help you keep your AWS infrastructure not only secure but also efficient and optimized.
AWS offers a range of tools that can complement and enhance security groups’ capabilities, including VPC Traffic Mirroring, Shield, and WAF. Let’s take a look at each:
This feature allows you to capture and inspect network traffic on your VPC. By mirroring your traffic, you can identify anomalies or suspicious activities that traditional security tools might miss.
AWS Shield
As the name suggests, this comprehensive service shields AWS-based applications from DDoS attacks. Integrating AWS Shield with your security groups can provide an additional layer of protection against these attacks.
AWS WAF
While security groups act at the instance level, AWS WAF operates at the application layer. It inspects web requests and can block common web-based attacks, such as SQL injections and cross-site scripting.
aws wafv2 create-web-acl --name "MyWebACL" --scope REGIONAL --default-action Allow={} --visibility-config SampledRequestsEnabled=true,CloudWatchMetricsEnabled=true,MetricName=WebAclExample
The AWS Security Groups Best Practices [Cheat Sheet]: Wiz’s approach
There’s a lot to consider when it comes to AWS security groups—so to make sure you always have AWS security group best practices at your fingertips, download Wiz’s comprehensive cheat sheet. This quick reference guide will help you follow the best practices in this article, whether you're a beginner or an AWS expert.
AWS Security Group Best Practices [Cheat Sheet]
In this 10 page cheat sheet we'll cover best practices for AWS Security Groups in the following areas: Traffic management, Advanced monitoring, Automation and scalability, Security enhancements.
Download PDFAs a cloud-native application protection platform, Wiz protects companies with its industry-leading cloud security platform, which offers a holistic view of risks across your entire AWS environment.
Schedule a demo today to see how Wiz can secure everything you build and run in the cloud.
Agentless full stack coverage of your AWS Workloads in minutes
Learn why CISOs at the fastest growing companies choose Wiz to help secure their AWS environments.
Other security best practices you might be interested in: