A security group acts as a virtual firewall for your instance to control inbound and outbound traffic. When you launch an instance in a VPC, you can assign up to five security groups to the instance. And Security Groups can be attached to multiple instances. Security groups can only be created for a region/VPC. If we switch to another region or if we create another VPC, we have to recreate the Security Groups.
Security group rules can reference by IP or by the security group. Referencing other Security Groups means that, We can authorize and allow access from other security groups which might be attached to another EC2 instance.
Security groups are not part of EC2 instances, it’s placed outside to the EC2 instances.
If traffic is blocked, EC2 instances won’t receive any requests. If your application is not accessible or timed out, then it’s a Security Group issue.
If your application gives a “Connection Refused” error, then it’s an application error or it’s not launched.
Allow rules, not deny rules
Security Groups only contain allow rules, not deny rules.
Default
If we don’t specify a security group, the instance is automatically assigned to the default security group. All inbound traffic is blocked by default. All outbound traffic is authorized by default.
Security groups are stateful
if you send a request from your instance, the response traffic for that request is allowed to flow in regardless of inbound security group rules. Responses to allowed inbound traffic are allowed to flow out, regardless of outbound rules.
For each rule, we need to specify the below,
- Name: name of the security group.
- Protocol: Protocol to allow like TCP, UDP.
- Port range: We can specify port range or single port number to allow.
- Source or destination : The source (inbound rules) or destination (outbound rules) for the traffic. IPV4 and IPV6 address ranges or another Security Group.
Type | Protocol | Port Range | Source |
HTTP | TCP | 80 | 0.0.0.0/0 |
ssh | TCP | 22 | 184.146.196.72/28 |
Custom TCP Rule | TCP | 8765 | 0.0.0.0/0 |
Security Group vs Network Access Control List
Security groups act at the instance level, not at the subnet level. Network ACL(NACL) controls traffic from & to the subnet. It can have both Allow & deny rules. Rules only include IP addresses, not another security group or NACL.
NACL is stateless, you must specify allow-rule for return traffic. It applies to all instances in the subnet. We don’t have to specify the security groups at the instance level.