Event Information

  • The DeleteKeyPair event in AWS for EC2 refers to the action of deleting a key pair that is used for secure login to EC2 instances.
  • When this event occurs, it means that the specified key pair is no longer available for use and cannot be used to authenticate and access EC2 instances.
  • It is important to note that deleting a key pair does not affect the running instances that were launched using that key pair. However, it will prevent any new instances from being launched with that key pair.

Examples

  • Unauthorized deletion of key pairs: If an attacker gains access to the AWS account or EC2 instance and deletes a key pair, they can effectively lock out legitimate users from accessing the instance. This can lead to a loss of data or service disruption.

  • Compromised key pair: If a key pair used for authentication is compromised, an attacker can gain unauthorized access to the EC2 instance. This can result in unauthorized data access, modification, or even complete control of the instance.

  • Lack of key pair backup: If a key pair is not properly backed up, accidental deletion or loss of the key pair can result in the inability to access the EC2 instance. This can lead to service disruption and potential data loss if there are no alternative access methods in place.

Remediation

Using Console

  1. Example 1: Unauthorized Access to AWS EC2 Instance

    • Step 1: Identify the compromised EC2 instance by reviewing the event logs or security alerts.
    • Step 2: Terminate the compromised EC2 instance to prevent further unauthorized access.
    • Step 3: Launch a new EC2 instance with the latest AMI and apply necessary security configurations, such as disabling unnecessary ports, implementing strong access controls, and enabling encryption.
  2. Example 2: Unusual Network Traffic from AWS EC2 Instance

    • Step 1: Analyze the network traffic logs or security alerts to identify the source and destination of the unusual traffic.
    • Step 2: Disable or block the suspicious network traffic by modifying the security group rules associated with the affected EC2 instance.
    • Step 3: Implement additional security measures, such as enabling VPC flow logs, configuring network ACLs, or using a web application firewall (WAF) to protect against future network-based attacks.
  3. Example 3: Unauthorized API Calls from AWS EC2 Instance

    • Step 1: Review the CloudTrail logs or security alerts to identify the unauthorized API calls and the affected EC2 instance.
    • Step 2: Revoke the IAM credentials associated with the compromised EC2 instance to prevent further unauthorized API calls.
    • Step 3: Implement least privilege access control by creating a new IAM role or user with only the necessary permissions for the EC2 instance, and update the instance with the new credentials. Additionally, consider enabling multi-factor authentication (MFA) for IAM users to enhance security.

Using CLI

  1. Ensure that all EC2 instances are using the latest Amazon Machine Images (AMIs) by regularly checking for updates and patching any vulnerabilities. Use the following AWS CLI command to list all EC2 instances and their associated AMIs:

    aws ec2 describe-instances --query 'Reservations[].Instances[].[InstanceId, ImageId]' --output table
    
  2. Implement security groups to restrict inbound and outbound traffic to only necessary ports and protocols. Use the following AWS CLI command to create a security group and define the desired inbound and outbound rules:

    aws ec2 create-security-group --group-name MySecurityGroup --description "My security group" --vpc-id vpc-12345678
    aws ec2 authorize-security-group-ingress --group-id sg-12345678 --protocol tcp --port 22 --cidr 0.0.0.0/0
    aws ec2 authorize-security-group-egress --group-id sg-12345678 --protocol tcp --port 80 --cidr 0.0.0.0/0
    
  3. Enable AWS CloudTrail to monitor and log all API activity within your AWS account. Use the following AWS CLI command to create a new CloudTrail trail:

    aws cloudtrail create-trail --name MyTrail --s3-bucket-name my-bucket --is-multi-region-trail
    aws cloudtrail start-logging --name MyTrail
    

Using Python

  1. Example 1: Enforce secure communication for AWS EC2 instances using SSL/TLS:

    • Generate an SSL/TLS certificate for the EC2 instance using a certificate authority or a self-signed certificate.
    • Install the certificate on the EC2 instance and configure the web server or application to use SSL/TLS.
    • Update the security group rules to allow inbound traffic on the appropriate SSL/TLS port (e.g., 443 for HTTPS).

    Python script:

    # Install required packages
    import subprocess
    subprocess.call(['pip', 'install', 'boto3'])
    
    import boto3
    
    # Generate SSL/TLS certificate
    client = boto3.client('acm', region_name='us-west-2')
    response = client.request_certificate(
        DomainName='example.com',
        ValidationMethod='DNS'
    )
    certificate_arn = response['CertificateArn']
    
    # Install certificate on EC2 instance
    ec2_client = boto3.client('ec2', region_name='us-west-2')
    response = ec2_client.associate_iam_instance_profile(
        IamInstanceProfile={
            'Arn': 'arn:aws:iam::123456789012:instance-profile/EC2-SSL-TLS'
        },
        InstanceId='i-1234567890abcdef0'
    )
    
  2. Example 2: Enable encryption at rest for AWS EC2 EBS volumes:

    • Create a new AWS Key Management Service (KMS) customer master key (CMK) or use an existing one.
    • Enable encryption for the EBS volumes by specifying the CMK during volume creation or by modifying the existing volumes.
    • Update the EC2 instance configuration to ensure that the encrypted EBS volumes are mounted and used.

    Python script:

    # Install required packages
    import subprocess
    subprocess.call(['pip', 'install', 'boto3'])
    
    import boto3
    
    # Enable encryption for EBS volumes
    ec2_client = boto3.client('ec2', region_name='us-west-2')
    response = ec2_client.modify_volume(
        VolumeId='vol-0123456789abcdef0',
        Encrypted=True,
        KmsKeyId='arn:aws:kms:us-west-2:123456789012:key/abcd1234-5678-90ab-cdef-0123456789ab'
    )
    
  3. Example 3: Implement automated backups for AWS EC2 instances using AWS Backup:

    • Create a backup plan in AWS Backup specifying the desired backup frequency, retention period, and backup vault.
    • Assign the backup plan to the EC2 instances or the associated resource tags.
    • Monitor the backup status and perform restores as needed.

    Python script:

    # Install required packages
    import subprocess
    subprocess.call(['pip', 'install', 'boto3'])
    
    import boto3
    
    # Create backup plan
    backup_client = boto3.client('backup', region_name='us-west-2')
    response = backup_client.create_backup_plan(
        BackupPlan={
            'BackupPlanName': 'EC2-Backup-Plan',
            'Rules': [
                {
                    'RuleName': 'Daily-Backup',
                    'ScheduleExpression': 'cron(0 0 * * ? *)',
                    'TargetBackupVaultName': 'EC2-Backup-Vault',
                    'Lifecycle': {
                        'DeleteAfterDays': 30
                    }
                }
            ]
        }
    )
    
    # Assign backup plan to EC2 instances
    response = backup_client.create_backup_selection(
        BackupPlanId='arn:aws:backup:us-west-2:123456789012:backup-plan/abcd1234-5678-90ab-cdef-0123456789ab',
        BackupSelection={
            'SelectionName': 'EC2-Backup-Selection',
            'IamRoleArn': 'arn:aws:iam::123456789012:role/EC2-Backup-Role',
            'Resources': [
                'arn:aws:ec2:us-west-2:123456789012:instance/i-1234567890abcdef0'
            ]
        }
    )