Secure configuration of EC2 Security Groups
Resources:
InsecureEC2Instance:
Type: AWS::EC2::Instance
Properties:
ImageId: ami-0c94855ba95c574c8
InstanceType: t2.micro
# No security group is defined
In the above CloudFormation template, an AWS EC2 instance is being created
without any security group associated with it. This is a major security
vulnerability as it means that the instance is not protected by any firewall
rules, allowing unrestricted access from the internet.
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 must
associate it with at least one security group. If no security group is explicitly
defined, the default security group is used, which might have permissive rules.
In the provided code, there are no input/output rules defined for the EC2
instance, which could allow unauthorized access depending on the default
group's configuration. This is a serious security concern and should be
addressed immediately.
Resources:
SecureSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: "Security Group with restricted access"
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 22
ToPort: 22
CidrIp: 0.0.0.0/0
SecurityGroupEgress:
- IpProtocol: -1
FromPort: 0
ToPort: 0
CidrIp: 0.0.0.0/0
SecureEC2Instance:
Type: AWS::EC2::Instance
Properties:
ImageId: ami-0c94855ba95c574c8
InstanceType: t2.micro
SecurityGroupIds:
- !Ref SecureSecurityGroup
The following CloudFormation template creates a security group named
"SecureSecurityGroup" with an inbound rule that allows TCP traffic on
port 22 (SSH) from any IP address (0.0.0.0/0), and an outbound rule that
allows all traffic.
The EC2 instance is then updated to associate this security group using
the
SecurityGroupIds
property. This ensures that the instance is protected
by defined network rules, reducing the risk of unauthorized access.