Ensure no hard-coded secrets exist in EC2 user data

ID

ec2_credentials

Severity

critical

Vendor

AWS

Resource

EC2 Instance

Tags

reachable

Description

User Data is a metadata field of an EC2 instance used to provide user data script to the instance when is launched.

Any existing configuration with read permissions over the EC2 would have access to the data since it’s not encrypted.

Credentials should be removed to avoid sensible data being exposed to third parties.

Examples

CloudFormation

{
  "Resources": {
    "Dummy": {
      "Type": "AWS::EC2::Instance",
      "Properties": {
        "ImageId": "ami-989491289078sad",
        "UserData": { (1)
          "Fn::Base64": {
            "Fn::Sub": "#! /bin/bash\nsudo apt-get update\nsudo apt-get install -y apache2\nsudo systemctl start apache2\nsudo systemctl enable apache2\nexport AWS_ACCESS_KEY_ID=AKIAIOSTHEDUMMYTEST\nexport AWS_DEFAULT_REGION=us-west-2\necho \"<h1>Deployed</h1>\""
          }
        }
      }
    }
  }
}
1 UserData contains hardcoded credentials.
Resources:
  Dummy:
    Type: AWS::EC2::Instance
    Properties:
      ImageId: ami-989491289078sad
      UserData: (1)
        Fn::Base64:
          !Sub |
            #! /bin/bash
            sudo apt-get update
            sudo apt-get install -y apache2
            sudo systemctl start apache2
            sudo systemctl enable apache2
            export AWS_ACCESS_KEY_ID=AKIAIOSTHEDUMMYTEST
            echo "<h1>Deployed</h1>"
1 UserData contains hardcoded credentials.

Mitigation / Fix

Buildtime

CloudFormation

{
  "Resources": {
    "Dummy": {
      "Type": "AWS::EC2::Instance",
      "Properties": {
        "ImageId": "ami-989491289078sad",
        "UserData": { (1)
          "Fn::Base64": {
            "Fn::Sub": "#! /bin/bash\nsudo apt-get update\nsudo apt-get install -y apache2\nsudo systemctl start apache2\nsudo systemctl enable apache2\nexport AWS_DEFAULT_REGION=us-west-2\necho \"<h1>Deployed</h1>\""
          }
        }
      }
    }
  }
}
1 Do not hardcode credentials into the UserData property.
Resources:
  Dummy:
    Type: AWS::EC2::Instance
    Properties:
      ImageId: ami-989491289078sad
      UserData: (1)
        Fn::Base64:
          !Sub |
            #! /bin/bash
            sudo apt-get update
            sudo apt-get install -y apache2
            sudo systemctl start apache2
            sudo systemctl enable apache2
            echo "<h1>Deployed</h1>"
1 Do not hardcode credentials into the UserData property.

Runtime

CLI Command

Secrets can be reviewed with the following CLI command:

aws ec2 describe-instance-attribute --attribute userData --region <region> --instance-id <instance-id> --query UserData.Value --output text > encodeddata; base64 --decode encodeddata