Insecure service configuration - EC2 - cloudformation

Insecure service configuration - EC2 - cloudformation

Need

Secure configuration of EC2 instances

Context

  • Usage of CloudFormation for Infrastructure as Code (IaC)
  • Usage of AWS native service to manage infrastructure as code

Description

Non compliant code

        Resources:
  InsecureInstance:
    Type: AWS::EC2::Instance
    Properties:
      ImageId: ami-0c94855ba95c574c8
      InstanceType: t2.micro

        
        

This CloudFormation template launches an EC2 instance without a security group or key pair, exposing it publicly and making it inaccessible securely.

Steps

Compliant code

        Parameters:
  KeyName:
    Type: String
    Description: Existing EC2 KeyPair

Resources:
  InstanceSG:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: SSH access
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 22
          ToPort: 22
          CidrIp: 0.0.0.0/0

  EC2Instance:
    Type: AWS::EC2::Instance
    Properties:
      ImageId: ami-0c94855ba95c574c8
      InstanceType: t2.micro
      KeyName: !Ref KeyName
      SecurityGroupIds:
        - !Ref InstanceSG
      BlockDeviceMappings:
        - DeviceName: /dev/sda1
          Ebs:
            Encrypted: true

        
        

This template secures the instance by using a key pair for SSH, a restrictive security group, and encrypted storage.

References