{Config}ec2-managedinstance-applications-blacklisted

https://dev.classmethod.jp/articles/stop-ec2-by-application-blacklist/

https://dev.classmethod.jp/articles/show-installed-appilications-by-ssm-inventory/


EC2作成

SSMインベントリ登録

Configリソース登録

Configルール作成

 


-- 1. コマンド等のインストール

-- 1.1 aws cli version 2 インストール

curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install
aws --version

-- 1.2 jqインストール
sudo yum -y install jq

 


-- 2. EC2用IAMロール作成
vim role01.json

{
    "Version": "2012-10-17",
    "Statement": [
      {
        "Effect": "Allow",
        "Principal": {
          "Service": "ec2.amazonaws.com"
        },
        "Action": "sts:AssumeRole"
      }
    ]
}

 

aws iam create-role \
--role-name role01 \
--assume-role-policy-document file://role01.json


-- 3. ポリシーをロールにアタッチ

aws iam attach-role-policy \
--policy-arn arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore \
--role-name role01

 

-- 4. インスタンスプロファイルを作成

aws iam create-instance-profile --instance-profile-name profile01

aws iam list-instance-profiles | grep InstanceProfileName

-- 5. インスタンスプロファイルにロールを追加
aws iam add-role-to-instance-profile --instance-profile-name profile01 --role-name role01

aws iam list-instance-profiles-for-role --role-name role01

 


-- 6. IAM ロールを使用したEC2インスタンス起動

vim a.sh

#!/bin/bash
yum -y update
yum -y install vsftpd


aws ec2 run-instances \
--image-id ami-0404778e217f54308 \
--instance-type t3.nano \
--key-name key1 \
--tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=instance01}]' \
--iam-instance-profile Name="profile01" \
--user-data file://a.sh

 

aws ec2 describe-instances


-- 7. State Manager の関連付けを作成


aws ssm create-association \
--name "AWS-GatherSoftwareInventory" \
--parameters "networkConfig=Enabled,awsComponents=Enabled,applications=Enabled" \
--targets "Key=instanceids,Values=i-11111111111111111" \
--schedule-expression "rate(30 minutes)" \
--association-name inventory01

 

 

aws ssm describe-instance-associations-status \
--instance-id i-11111111111111111


aws ssm list-associations

aws ssm describe-association \
--association-id 66666666-7777-8888-9999-aaaaaaaaaaaa

 

-- 8. インベントリ確認

aws ssm list-inventory-entries \
--output yaml \
--instance-id i-11111111111111111 \
--type-name "AWS:Application" \
--filters Key=Name,Values=vsftpd,Type=Equal

 

 

-- 9. S3 バケットを作成する

aws s3 ls

aws s3 mb s3://bucket123

 

-- 10. バケットポリシーの設定

vim b.json

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AWSConfigBucketPermissionsCheck",
            "Effect": "Allow",
            "Principal": {
                "Service": "config.amazonaws.com"
            },
            "Action": "s3:GetBucketAcl",
            "Resource": "arn:aws:s3:::bucket123",
            "Condition": {
                "StringEquals": {
                    "AWS:SourceAccount": "999999999999"
                }
            }
        },
        {
            "Sid": "AWSConfigBucketExistenceCheck",
            "Effect": "Allow",
            "Principal": {
                "Service": "config.amazonaws.com"
            },
            "Action": "s3:ListBucket",
            "Resource": "arn:aws:s3:::bucket123",
            "Condition": {
                "StringEquals": {
                    "AWS:SourceAccount": "999999999999"
                }
            }
        },
        {
            "Sid": "AWSConfigBucketDelivery",
            "Effect": "Allow",
            "Principal": {
                "Service": "config.amazonaws.com"
            },
            "Action": "s3:PutObject",
            "Resource": "arn:aws:s3:::bucket123/*",
            "Condition": {
                "StringEquals": {
                    "AWS:SourceAccount": "999999999999",
                    "s3:x-amz-acl": "bucket-owner-full-control"
                }
            }
        }
    ]
}

aws s3api put-bucket-policy \
--bucket bucket123 \
--policy file://b.json


aws s3api get-bucket-policy \
--bucket bucket123

 


-- 11. SNSトピック作成

aws sns list-topics
aws sns list-subscriptions

aws sns create-topic --name topic01

aws sns subscribe \
--topic-arn arn:aws:sns:ap-northeast-1:999999999999:topic01 \
--protocol email \
--notification-endpoint hoge@example.com

 

 

-- 12. SNSアクセスポリシー設定

aws sns get-topic-attributes \
--topic-arn arn:aws:sns:ap-northeast-1:999999999999:topic01

vim a.json

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "__default_statement_ID",
      "Effect": "Allow",
      "Principal": {
        "AWS": "*"
      },
      "Action": [
        "sns:GetTopicAttributes",
        "sns:SetTopicAttributes",
        "sns:AddPermission",
        "sns:RemovePermission",
        "sns:DeleteTopic",
        "sns:Subscribe",
        "sns:ListSubscriptionsByTopic",
        "sns:Publish"
      ],
      "Resource": "arn:aws:sns:ap-northeast-1:999999999999:topic01",
      "Condition": {
        "StringEquals": {
          "AWS:SourceOwner": "999999999999"
        }
      }
    },
    {
      "Sid": "AWSConfigSNSPolicy20180529",
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::999999999999:role/aws-service-role/config.amazonaws.com/AWSServiceRoleForConfig"
      },
      "Action": "sns:Publish",
      "Resource": "arn:aws:sns:ap-northeast-1:999999999999:topic01"
    }
  ]
}

 

aws sns set-topic-attributes \
--topic-arn arn:aws:sns:ap-northeast-1:999999999999:topic01 \
--attribute-name Policy \
--attribute-value file://a.json

 

 


-- 13. AWS Config の有効化


aws configservice put-configuration-recorder \
--configuration-recorder name=default,roleARN=arn:aws:iam::999999999999:role/aws-service-role/config.amazonaws.com/AWSServiceRoleForConfig \
--recording-group '{
  "allSupported": false,
  "includeGlobalResourceTypes": false,
  "resourceTypes": [
    "AWS::EC2::Instance",
    "AWS::SSM::ManagedInstanceInventory"
  ]
}'


aws configservice put-delivery-channel \
--delivery-channel '{
    "name": "default",
    "s3BucketName": "bucket123",
    "snsTopicARN": "arn:aws:sns:ap-northeast-1:999999999999:topic01",
    "configSnapshotDeliveryProperties": {
        "deliveryFrequency": "TwentyFour_Hours"
    }
}'

 

aws configservice start-configuration-recorder \
--configuration-recorder-name default


aws configservice put-retention-configuration \
--retention-period-in-days 30

 

aws configservice describe-delivery-channels
aws configservice describe-configuration-recorders
aws configservice describe-configuration-recorder-status
aws configservice describe-retention-configurations


-- 14. 検出されたリソースの検索

aws configservice list-discovered-resources \
--resource-type AWS::EC2::Instance

aws configservice list-discovered-resources \
--resource-type AWS::SSM::ManagedInstanceInventory

 


-- 15. 自動修復用IAMロール作成
vim role02.json

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "",
            "Effect": "Allow",
            "Principal": {
                "Service": [
                    "ssm.amazonaws.com"
                ]
            },
            "Action": "sts:AssumeRole"
        }
    ]
}


aws iam create-role \
--role-name role02 \
--assume-role-policy-document file://role02.json

 

-- 16. ポリシーをロールにアタッチ
aws iam attach-role-policy \
--policy-arn arn:aws:iam::aws:policy/service-role/AmazonSSMAutomationRole \
--role-name role02

 

-- 17. ルールの追加

vim rule.json

{
  "ConfigRule": {
     "ConfigRuleName": "rule01",
     "Description": "ec2-managedinstance-applications-blacklisted",
     "Scope": {
       "ComplianceResourceTypes": ["AWS::SSM::ManagedInstanceInventory"]
     },
     "Source": {
       "Owner": "AWS",
       "SourceIdentifier": "EC2_MANAGEDINSTANCE_APPLICATIONS_BLACKLISTED"
     },
       "InputParameters": "{\"applicationNames\":\"vsftpd\",\"platformType\":\"Linux\"}"
     }
}


※このルールは、記録されたリソースが作成、編集、削除されたときにのみトリガーできます。


※ルール評価対象はConfigの変更管理の対象リソースとして登録しておく必要がある

 

aws configservice put-config-rule \
--cli-input-json file://rule.json

 

aws configservice describe-config-rules

 

-- 18. 自動修復の設定

vim remediation.json


[
  {
    "ConfigRuleName": "rule01",
    "TargetType": "SSM_DOCUMENT",
    "TargetId": "AWS-StopEC2Instance",
    "TargetVersion": "1",
    "Parameters": {"AutomationAssumeRole": {
          "StaticValue": {
            "Values": ["arn:aws:iam::999999999999:role/role02"]
          }
        },
        "InstanceId": {
            "ResourceValue": {
                "Value": "RESOURCE_ID"
            }
        }
    },
    "Automatic": true,
    "MaximumAutomaticAttempts": 5,
    "RetryAttemptSeconds": 60
  }
]


aws configservice put-remediation-configurations \
--remediation-configurations file://remediation.json

 

aws configservice describe-remediation-configurations \
--config-rule-names rule01

 

 

-- 19. 動作確認

aws configservice describe-config-rule-evaluation-status

aws configservice describe-remediation-execution-status \
--config-rule-name rule01


しばらく待ち、ルール非準拠となることを確認する
vsftpdのインストールされたEC2インスタンスが停止を確認

 

 

-- 20. クリーンアップ


-- 自動修復の削除

aws configservice describe-remediation-configurations \
--config-rule-names rule01

aws configservice delete-remediation-configuration \
--config-rule-name rule01

 

-- ルールの削除

aws configservice describe-config-rules

aws configservice delete-config-rule \
--config-rule-name rule01

少し時間がかかる

 

-- 自動修復用IAMロールの削除
aws iam list-roles | grep role02

aws iam detach-role-policy \
--role-name role02 \
--policy-arn arn:aws:iam::aws:policy/service-role/AmazonSSMAutomationRole


aws iam delete-role --role-name role02

 

-- AWS Config の無効化

aws configservice describe-delivery-channels
aws configservice describe-configuration-recorders
aws configservice describe-configuration-recorder-status
aws configservice describe-retention-configurations

aws configservice delete-retention-configuration \
--retention-configuration-name default


aws configservice stop-configuration-recorder \
--configuration-recorder-name default

aws configservice delete-delivery-channel \
--delivery-channel-name default

aws configservice delete-configuration-recorder \
--configuration-recorder-name default


-- SNSトピック削除
aws sns list-topics
aws sns list-subscriptions


aws sns unsubscribe --subscription-arn arn:aws:sns:ap-northeast-1:999999999999:topic01:11111111-2222-3333-4444-555555555555
aws sns delete-topic --topic-arn arn:aws:sns:ap-northeast-1:999999999999:topic01


-- バケットの削除

aws s3 ls

aws s3 rb s3://bucket123 --force

 

 


-- State Manager の関連付けの削除


aws ssm list-associations

aws ssm describe-association \
--association-id 66666666-7777-8888-9999-aaaaaaaaaaaa

aws ssm delete-association \
--association-id 66666666-7777-8888-9999-aaaaaaaaaaaa

 

-- EC2インスタンスの削除

aws ec2 describe-instances

aws ec2 terminate-instances --instance-ids i-11111111111111111


-- インスタンスプロファイルの削除

aws iam remove-role-from-instance-profile --instance-profile-name profile01 --role-name role01


aws iam delete-instance-profile --instance-profile-name profile01

aws iam list-instance-profiles | grep InstanceProfileName

 

-- EC2用IAMロールの削除
aws iam list-roles | grep role01

aws iam detach-role-policy \
--role-name role01 \
--policy-arn arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore

aws iam delete-role --role-name role01