AWS EC2 Security Group

What is AWS EC2 Security Group?

An EC2 (Elastic Compute Cloud) Security Group acts as a virtual firewall for controlling inbound and outbound traffic to EC2 instances. It works by allowing you to define rules that dictate which traffic is allowed to reach your instances and which traffic should be blocked.

EC2 Security Group Characteristics

  1. Defining Rules: Security groups are defined by inbound and outbound rules. Each rule allows traffic based on a combination of the following parameters:

    • Protocol (TCP, UDP, ICMP, etc.)

    • Port range (e.g., specific port or a range of ports)

    • Source or destination IP addresses or CIDR blocks (e.g., specific IP, IP range, or "0.0.0.0/0" for all IPs)

  2. Default Security Group: When you launch an EC2 instance without specifying a security group, AWS automatically assigns a default security group to that instance. The default security group is configured to allow all outbound traffic and deny all inbound traffic by default.

  3. Stateful: Security groups are stateful, which means that if you allow inbound traffic for a specific protocol and port, the corresponding outbound traffic for the same protocol and port is automatically allowed. You don't need to create a separate outbound rule for the response traffic.

  4. Regin Specific: Security Groups are locked down to a region/VPC combination.

  5. SGs live outside the EC2 - if traffic is blocked the EC2 instance will not see it.

  6. Grouping Instances: Each EC2 instance must be associated with one or more security groups. A security group can be associated with multiple instances, and multiple security groups can be assigned to a single instance.

  7. Order of Rules: Rules are evaluated in the order they are defined. If there are conflicting rules (e.g., one rule allows traffic, and another denies it), the "allow" rule takes precedence.

  8. Dynamic Updates: You can modify the security group rules at any time. Changes take effect immediately and are automatically applied to all associated instances.

Hands-on Lab Overview

In this hands-on lab, we are going to create a security group for EC2 instances using AWS Management Console, AWS CLI, and AWS SDK;

Hands-on Lab

Create EC2 SG using AWS Console:

  1. Open the Amazon VPC console at https://console.aws.amazon.com/vpc/.

  2. In the navigation pane, choose Security groups.

  3. Choose Create security group.

  4. Enter a name and description for the security group. You cannot change the name and description of a security group after it is created.

  5. From VPC, choose the VPC.

  6. You can add security group rules now, or you can add them later.

  7. You can add tags now, or you can add them later.

  8. Choose Create security group.

Create EC2 SG using AWS CLI

It is assumed that AWS CLI is configured with aws configure command.

  1. To create a security group without any rules defined, enter the command:
 aws ec2 create-security-group \
 --group-name "ftp-sg" \
 --description "Rules for FTP traffic"

Note down the security group ID from the output. The output would look like the following:

  1. Check whether the SG "ftp-sg" was created via AWS Console:

  1. Next, use the authorize-security-group-ingress and authorize-security-group-egress commands to add inbound and outbound rules, respectively, to an existing security group in Amazon EC2.
aws ec2 authorize-security-group-ingress \
--group-id "sg-0a2ac365fe2cb4c8a" \ 
--ip-permissions "IpProtocol=tcp,FromPort=21,ToPort=80,IpRanges=[{CidrIp=0.0.0.0/0},{CidrIp=10.0.0.0/24}]"

We added an inbound rule to the specified security group that allows TCP traffic on port 21 from both the public internet and a specific private IP range (10.0.0.0/24). This is useful if you want to allow FTP connections from both the internet and your private network to instances in the security group. However, be cautious when opening up security groups to the public internet, and only allow the minimum necessary access for your specific use case.

Create EC2 SG using AWS SDK

To create an AWS EC2 security group using the AWS SDK for Node.js (AWS SDK for JavaScript), follow these steps:

  1. Load the AWS SDK for Node.js:

     const AWS = require("aws-sdk");
    
  2. Load credentials and set region:

    Configure your AWS credentials by setting the access key ID and secret access key. You can do this using the AWS.config object:

     AWS.config.update({
         accessKeyId: "xxx",
         secretAccessKey: "xxx",
         region: "us-east-1"
     })
    
  3. Create an EC2 service object

     const ec2 = new AWS.EC2({apiVersion: '2016-11-15'});
    
  4. Create a variable to hold an ID of a VPC

     let vpc = null;
    
  5. Retrieve the ID of a VPC and create a Security Group with inbound rules:

     ec2.describeVpcs(function(err, data) {
         if(err) {
             console.log("Cannot retrieve a VPC", err);
         } else {
             vpc = data.Vpcs[0].VpcId;
             // Define Security Group parameters:
             const securityGroupParams = {
                 Description: "SG for SSH and HTTP traffic",
                 GroupName: "ssh-http-sg",
                 VpcId: vpc
             }
             // Create Security Group
             ec2.createSecurityGroup(securityGroupParams, (err, data) => {
                 if(err) {
                     console.log("Error creating security group: ", err);
                 } else {
                     const SecurityGroupId = data.GroupId;
                     console.log("Security Group created with ID: ", SecurityGroupId);
    
                     // Define Security Group Rules:
                     const paramsIngress = {
                         GroupId: SecurityGroupId,
                         IpPermissions: [
                             {
                                 IpProtocol: "tcp",
                                 FromPort: 22,
                                 ToPort: 22,
                                 IpRanges: [{CidrIp: "10.0.0.0/24"}]
                             }, 
                             {
                                 IpProtocol: "tcp",
                                 FromPort: 80,
                                 ToPort: 80,
                                 IpRanges: [{CidrIp: "10.0.0.0/24"}]
                             }]
                     };        
                     // Add inbound rules
                     ec2.authorizeSecurityGroupIngress(paramsIngress, (err, data) => {
                         if(err) {
                             console.log("Error adding inbound rules: ", err);
                         } else {
                             console.log("Inbound rules added to the security group successfully!", data);
                         }
                     });
                 }
             });
         }
     });
    

The output:

Check via AWS Console whether the SG and its rules were added:

References

  1. Security Groups

  2. Working with Security Groups in Amazon EC2