【CDK】セキュリティ関連サービスのSlack通知を検証

## はじめに
今回はセキュリティ周りのSlack通知をCDKで試してみました。Chatbotと直接統合されていないサービス群はEventBridgeによるイベントをトリガーとしてSNS->Chatbotの流れで通知させます。
※今回少し長くなってしまったので幾つかの項目を折りたたんでます。

・関連記事
[【CDK】Cost Anomaly DetectionがChatbotと統合されたのでCDKで実装してみた【アップデート】](https://qiita.com/hedgehog051/items/5e22846d6b8b7b895073)
[【CDK】ECRイメージスキャンの結果をchatbot経由でslackに通知させる](https://qiita.com/hedgehog051/items/51653e0c61c5190ebb64)

## SecurityHub

>Q: AWS Security Hub とは何ですか?
>
>AWS Security Hub は、AWS 内のセキュリティの状態と、セキュリティ標準およびベストプラクティスに準拠しているかどうかを、包括的に把握できるようにします。AWS Security Hub は、AWS のアカウント、サービス、サポート対象のサードパーティーパートナーの全体にわたってセキュリティの検出結果を一元化および優先順位を設定することで、セキュリティの傾向を分析し、最も重要なセキュリティの問題を特定します。

### 要するに
- **セキュリティデータの集約と一元的な可視化**
- **業界標準やベストプラクティスに基づいた自動コンプライアンスチェック**


<details><summary>集約対象のセキュリティデータ一覧</summary><div>

|サービス名|対象|
| --- | --- |
| Amazon GuardDuty | 脅威検知に関する全ての検出結果 |
| Amazon Inspector  |セキュリティ評価による全ての検出結果  |
| Amazon Macie | ポリシー違反時の検出結果 |
| AWS IAM Access Analyzer |  自身のアカウント内のリソースに対して、外部からのアクセスを許可するポリシー記述を検出した時の検出結果|
| AWS Firewall Manager | AWS WAF ポリシーや Web ACL ルールのコンプライアンス非準拠時の検出結果<br>AWS Shield Advanced によりリソース保護されていない、または攻撃を検知した時の検出結果 |
| AWS Systems Manager Patch Manager | EC2インスタンスがパッチベースラインに基づくコンプライアンスルールに非準拠の時の検出結果 |

</div></details>

<details><summary>自動コンプライアンスチェック一覧</summary><div>

|対象|説明|
| --- | --- |
|AWS 基礎セキュリティのベストプラクティス v1.0.0| AWS アカウントとデプロイされたリソースがセキュリティのベストプラクティスと一致しないことを検出する自動化されたセキュリティチェックのセットです。<br>この標準は AWS セキュリティの専門家によって定義されたものです。<br>この厳選された一連の統制は、AWS におけるセキュリティ体制の改善に役立ち、AWS で最も人気の高い基礎的なサービスを網羅しています。 |
| CIS AWS Foundations Benchmark v1.2.0 | Center for Internet Security (CIS) AWS Foundations Benchmark v1.2.0 は、AWS のセキュリティ設定のベストプラクティスのセットです。<br>この Security Hub 標準では、CIS 要件のサブセットに対するコンプライアンスの準備状況が自動的にチェックされます。 |
| PCI DSS v3.2.1 | Payment Card Industry Data Security Standard (PCI DSS) v3.2.1 は、カード所有者データを保存、処理、転送するエンティティ向けの情報セキュリティ標準です。<br>この Security Hub 標準では、PCI DSS 要件のサブセットに対するコンプライアンスの準備状況が自動的にチェックされます。 |

</div></details>

#### 参考
[AWS-BlackBelt-AWSSecurityHub](https://d1.awsstatic.com/webinars/jp/pdf/services/20201013_AWS-BlackBelt-AWSSecurityHub.pdf)

## Config
>AWS Config とは?
AWS Config は、AWS アカウントにある AWS リソースの設定詳細ビューを提供します。これには、リソース間の関係と設定の履歴が含まれるため、時間の経過と共に設定と関係がどのように変わるかを確認できます。

### 要するに
- **AWSリソースなどの構成変更をロギング (どのサービスを、誰が、いつ、何をしたかを記録)**
※他にもConfigRuleという評価機能がありますがここでは割愛

### サポートされるリソースタイプ

https://docs.aws.amazon.com/ja_jp/config/latest/developerguide/resource-config-reference.html

### 参考
[AWS-Blackbelt_Config](https://d1.awsstatic.com/webinars/jp/pdf/services/20190618_AWS-Blackbelt_Config.pdf)

## GuardDuty
>Q: Amazon GuardDuty とは何ですか?
Amazon GuardDuty は、AWS アカウントとワークロード、および Amazon Simple Storage Service (Amazon S3) に保存されたデータを継続的にモニタリグおよび保護できる脅威検出機能を提供します。GuardDuty は、アカウントから生成された継続的なメタデータストリームと、AWS CloudTrail イベント、Amazon Virtual Private Cloud (VPC) フローログ、およびドメインネームシステム (DNS) ログに見られるネットワークアクティビティを分析します。また、GuardDuty は既知の悪意のある IP アドレス、異常の検出、機械学習 (ML) などの統合された脅威インテリジェンスを使用して、より正確に脅威を識別します。

### 要するに
- **CloudTrail Event Logs、VPCFlowlog、DNSログをデータソースとして分析して驚異リスクを検知**
- **悪意のあるIPアドレスやドメイン、異常検出、機械学習を使用して脅威を識別**
- **S3に保存されたデータの保護(データアクセスイベントと設定のモニタリングとプロファイリング)**

<details><summary>検出される驚異リスク一覧</summary><div>

|カテゴリ||
| --- | --- |
| 悪意のあるスキャン | Instance Recon:<br>• Port Probe/Accepted Comm<br>• Port Scan (intra-VPC)<br>• Brute Force Attack (IP)<br>• Drop Point (IP)<br>• Tor CommunicationsAccount Recon:<br>• Tor API Call (failed)<br><br>Account Recon:<br>• Tor API Call (failed) |
| インスタンスへの脅威 | • C&C Activity<br>• Malicious Domain Request<br>• EC2 on Threat List<br>• Drop Point IP<br>• Malicious Comms (ASIS)<br>• Bitcoin Mining<br>• Outbound DDoS<br>• Spambot Activity<br>• Outbound SSH Brute Force<br>• Unusual Network Port<br>• Unusual Traffic Volume/Direction<br>• Unusual DNS Requests<br>• Domain Generated Algorithms |
| アカウントへの脅威 | • Malicious API Call (bad IP)<br>• Tor API Call (accepted)<br>• CloudTrail Disabled<br>• Password Policy Change<br>• Instance Launch Unusual<br>• Region Activity Unusual<br>• Suspicious Console Login<br>• Unusual ISP Caller<br>• Mutating API Calls (create,update, delete)<br>• High Volume of Describe calls<br>• Unusual IAM User Added |
</div></details>

<details><summary>検索タイプ一覧</summary><div>

| FINDING TYPE | RESOURCE | DATA SOURCE | SEVERITY |
| --- | --- | --- | --- |
| Backdoor:EC2/C&CActivity.B | EC2 | VPC Flow Logs | High |
| Backdoor:EC2/C&CActivity.B!DNS | EC2 | DNS logs | High |
| Backdoor:EC2/DenialOfService.Dns | EC2 | VPC Flow Logs | High |
| Backdoor:EC2/DenialOfService.Tcp | EC2 | VPC Flow Logs | High |
| Backdoor:EC2/DenialOfService.Udp | EC2 | VPC Flow Logs | High |
| Backdoor:EC2/DenialOfService.UdpOnTcpPorts | EC2 | VPC Flow Logs | High |
| Backdoor:EC2/DenialOfService.UnusualProtocol | EC2 | VPC Flow Logs | High |
| Backdoor:EC2/Spambot | EC2 | VPC Flow Logs | Medium |
| Behavior:EC2/NetworkPortUnusual | EC2 | VPC Flow Logs | Medium |
| Behavior:EC2/TrafficVolumeUnusual | EC2 | VPC Flow Logs | Medium |
| CredentialAccess:IAMUser/AnomalousBehavior | IAM | CloudTrail management event | Medium |
| CredentialAccess:Kubernetes/MaliciousIPCaller | Kubernetes | Kubernetes audit logs | High |
| CredentialAccess:Kubernetes/MaliciousIPCaller.Custom | Kubernetes | Kubernetes audit logs | High |
| CredentialAccess:Kubernetes/SuccessfulAnonymousAccess | Kubernetes | Kubernetes audit logs | High |
| CredentialAccess:Kubernetes/TorIPCaller | Kubernetes | Kubernetes audit logs | High |
| CryptoCurrency:EC2/BitcoinTool.B | EC2 | VPC Flow Logs | High |
| CryptoCurrency:EC2/BitcoinTool.B!DNS | EC2 | DNS logs | High |
| DefenseEvasion:IAMUser/AnomalousBehavior | IAM | CloudTrail management event | Medium |
| DefenseEvasion:Kubernetes/MaliciousIPCaller | Kubernetes | Kubernetes audit logs | High |
| DefenseEvasion:Kubernetes/MaliciousIPCaller.Custom | Kubernetes | Kubernetes audit logs | High |
| DefenseEvasion:Kubernetes/SuccessfulAnonymousAccess | Kubernetes | Kubernetes audit logs | High |
| DefenseEvasion:Kubernetes/TorIPCaller | Kubernetes | Kubernetes audit logs | High |
| Discovery:IAMUser/AnomalousBehavior | IAM | CloudTrail management event | Low |
| Discovery:Kubernetes/MaliciousIPCaller | Kubernetes | Kubernetes audit logs | Medium |
| Discovery:Kubernetes/MaliciousIPCaller.Custom | Kubernetes | Kubernetes audit logs | Medium |
| Discovery:Kubernetes/SuccessfulAnonymousAccess | Kubernetes | Kubernetes audit logs | Medium |
| Discovery:Kubernetes/TorIPCaller | Kubernetes | Kubernetes audit logs | Medium |
| Discovery:S3/MaliciousIPCaller | S3 | CloudTrail S3 data event | High |
| Discovery:S3/MaliciousIPCaller.Custom | S3 | CloudTrail S3 data event | High |
| Discovery:S3/TorIPCaller | S3 | CloudTrail S3 data event | Medium |
| Execution:Kubernetes/ExecInKubeSystemPod | Kubernetes | Kubernetes audit logs | Medium |
| Exfiltration:IAMUser/AnomalousBehavior | IAM | CloudTrail management event | High |
| Exfiltration:S3/MaliciousIPCaller | S3 | CloudTrail S3 data event | High |
| Exfiltration:S3/ObjectRead.Unusual | S3 | S3 CloudTraildata events | Medium* |
| Impact:EC2/AbusedDomainRequest.Reputation | EC2 | DNS logs | Medium |
| Impact:EC2/BitcoinDomainRequest.Reputation | EC2 | DNS logs | High |
| Impact:EC2/MaliciousDomainRequest.Reputation | EC2 | DNS logs | High |
| Impact:EC2/PortSweep | EC2 | VPC Flow Logs | High |
| Impact:EC2/SuspiciousDomainRequest.Reputation | EC2 | DNS logs | Low |
| Impact:EC2/WinRMBruteForce | EC2 | VPC Flow Logs | Low* |
| Impact:IAMUser/AnomalousBehavior | IAM | CloudTrail management event | High |
| Impact:Kubernetes/MaliciousIPCaller | Kubernetes | Kubernetes audit logs | High |
| Impact:Kubernetes/MaliciousIPCaller.Custom | Kubernetes | Kubernetes audit logs | High |
| Impact:Kubernetes/SuccessfulAnonymousAccess | Kubernetes | Kubernetes audit logs | High |
| Impact:Kubernetes/TorIPCaller | Kubernetes | Kubernetes audit logs | High |
| Impact:S3/MaliciousIPCaller | S3 | CloudTrail S3 data event | High |
| InitialAccess:IAMUser/AnomalousBehavior | IAM | CloudTrail management event | Medium |
| PenTest:IAMUser/KaliLinux | IAM | CloudTrail management event | Medium |
| PenTest:IAMUser/ParrotLinux | IAM | CloudTrail management event | Medium |
| PenTest:IAMUser/PentooLinux | IAM | CloudTrail management event | Medium |
| PenTest:S3/KaliLinux | S3 | CloudTrail S3 data event | Medium |
| PenTest:S3/ParrotLinux | S3 | CloudTrail S3 data event | Medium |
| PenTest:S3/PentooLinux | S3 | CloudTrail S3 data event | Medium |
| Persistence:IAMUser/AnomalousBehavior | IAM | CloudTrail management event | Medium |
| Persistence:Kubernetes/ContainerWithSensitiveMount | Kubernetes | Kubernetes audit logs | Medium |
| Persistence:Kubernetes/MaliciousIPCaller | Kubernetes | Kubernetes audit logs | Medium |
| Persistence:Kubernetes/MaliciousIPCaller.Custom | Kubernetes | Kubernetes audit logs | Medium |
| Persistence:Kubernetes/SuccessfulAnonymousAccess | Kubernetes | Kubernetes audit logs | High |
| Persistence:Kubernetes/TorIPCaller | Kubernetes | Kubernetes audit logs | Medium |
| Policy:IAMUser/RootCredentialUsage | IAM | CloudTrail management events or CloudTrail data events | Low |
| Policy:Kubernetes/AdminAccessToDefaultServiceAccount | Kubernetes | Kubernetes audit logs | High |
| Policy:Kubernetes/AnonymousAccessGranted | Kubernetes | Kubernetes audit logs | High |
| Policy:Kubernetes/KubeflowDashboardExposed | Kubernetes | Kubernetes audit logs | Medium |
| Policy:Kubernetes/ExposedDashboard | Kubernetes | Kubernetes audit logs | Medium |
| Policy:S3/AccountBlockPublicAccessDisabled | S3 | CloudTrail management events | Low |
| Policy:S3/BucketAnonymousAccessGranted | S3 | CloudTrail management events | High |
| Policy:S3/BucketBlockPublicAccessDisabled | S3 | CloudTrail management events | Low |
| Policy:S3/BucketPublicAccessGranted | S3 | CloudTrail management events | High |
| PrivilegeEscalation:IAMUser/AnomalousBehavior | IAM | CloudTrail management events | Medium |
| PrivilegeEscalation:Kubernetes/PrivilegedContainer | Kubernetes | Kubernetes audit logs | Medium |
| Recon:EC2/PortProbeEMRUnprotectedPort | EC2 | VPC Flow Logs | High |
| Recon:EC2/PortProbeUnprotectedPort | EC2 | VPC Flow Logs | Low* |
| Recon:EC2/Portscan | EC2 | VPC Flow Logs | Medium |
| Recon:IAMUser/MaliciousIPCaller | IAM | CloudTrail management events | Medium |
| Recon:IAMUser/MaliciousIPCaller.Custom | IAM | CloudTrail management events | Medium |
| Recon:IAMUser/TorIPCaller | IAM | CloudTrail management events | Medium |
| Stealth:IAMUser/CloudTrailLoggingDisabled | IAM | CloudTrail management events | Low |
| Stealth:IAMUser/PasswordPolicyChange | IAM | CloudTrail management event | Low |
| Stealth:S3/ServerAccessLoggingDisabled | S3 | CloudTrail management events | Low |
| Trojan:EC2/BlackholeTraffic | EC2 | VPC Flow Logs | Medium |
| Trojan:EC2/BlackholeTraffic!DNS | EC2 | DNS logs | Medium |
| Trojan:EC2/DGADomainRequest.B | EC2 | DNS logs | High |
| Trojan:EC2/DGADomainRequest.C!DNS | EC2 | DNS logs | High |
| Trojan:EC2/DNSDataExfiltration | EC2 | DNS logs | High |
| Trojan:EC2/DriveBySourceTraffic!DNS | EC2 | DNS logs | High |
| Trojan:EC2/DropPoint | EC2 | VPC Flow Logs | Medium |
| Trojan:EC2/DropPoint!DNS | EC2 | DNS logs | Medium |
| Trojan:EC2/PhishingDomainRequest!DNS | EC2 | DNS logs | High |
| UnauthorizedAccess:EC2/MaliciousIPCaller.Custom | EC2 | VPC Flow Logs | Medium |
| UnauthorizedAccess:EC2/MetadataDNSRebind | EC2 | DNS logs | High |
| UnauthorizedAccess:EC2/RDPBruteForce | EC2 | VPC Flow Logs | Low* |
| UnauthorizedAccess:EC2/SSHBruteForce | EC2 | VPC Flow Logs | Low* |
| UnauthorizedAccess:EC2/TorClient | EC2 | VPC Flow Logs | High |
| UnauthorizedAccess:EC2/TorRelay | EC2 | VPC Flow Logs | High |
| UnauthorizedAccess:IAMUser/ConsoleLoginSuccess.B | IAM | CloudTrail management events | Medium |
| UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration.InsideAWS | IAM | CloudTrail management event | High* |
| UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration.OutsideAWS | IAM | CloudTrail management events or S3 data events | High |
| UnauthorizedAccess:IAMUser/MaliciousIPCaller | IAM | CloudTrail management events | Medium |
| UnauthorizedAccess:IAMUser/MaliciousIPCaller.Custom | IAM | CloudTrail management events | Medium |
| UnauthorizedAccess:IAMUser/TorIPCaller | IAM | CloudTrail management events | Medium |
| UnauthorizedAccess:S3/MaliciousIPCaller.Custom | S3 | CloudTrail S3 data event | High |
| UnauthorizedAccess:S3/TorIPCaller | S3 | CloudTrail S3 data event | High |
</div></details>

上の検索タイプ一覧を見てもらえば変わると思いますが、GuardDutyはVPC Flow Logsなどのデータソースを分析した結果、EC2、IAM、S3、EKSそれぞれに対して驚異リスクがあるか否かという観点で知らせてくれます。

### 参考
[AWS-BlackBelt_Amazon-GuardDuty](https://d1.awsstatic.com/webinars/jp/pdf/services/20180509_AWS-BlackBelt_Amazon-GuardDuty.pdf)

## CloudTrail
>Q: AWS CloudTrail とは何ですか?
>
>AWS CloudTrail は、ユーザーのアクティビティや API の使用状況を追跡することで、監査、セキュリティモニタリング、運用トラブルシューティングを可能にします。CloudTrail は、お客様の AWS インフラストラクチャ全体のアクションに関連するアカウントアクティビティをログに記録し、継続的にモニタリングして、保持し、保存、分析、および修復アクションをコントロールできます。

### 要するに
- **AWSに対するAPI操作を記録、保存、分析**

<details><summary>サポートされるサービス一覧</summary><div>

| AWS Service | CloudTrail Topics | Support began |
| --- | --- | --- |
| Alexa for Business | Logging Alexa for Business Administration Calls Using AWS CloudTrail | 11/29/2017 |
| AWS Amplify | Logging Amplify API calls using AWS CloudTrail | 11/30/2020 |
| AWS Audit Manager | Logging AWS Audit Manager API calls with AWS CloudTrail | 12/07/2020 |
| Amazon API Gateway | Log API management calls to Amazon API Gateway Using AWS CloudTrail | 07/09/2015 |
| Amazon Connect | Logging Amazon Connect API Calls with AWS CloudTrail | 12/11/2019 |
| Application Auto Scaling | Logging Application Auto Scaling API calls with AWS CloudTrail | 10/31/2016 |
| AWS Application Discovery Service | Logging Application Discovery Service API Calls with AWS CloudTrail | 05/12/2016 |
| Amazon AppFlow | Logging Amazon AppFlow API calls with AWS CloudTrail | 04/22/2020 |
| AWS App Mesh | Logging App Mesh API Calls with AWS CloudTrail | AWS App Mesh 10/30/2019 |
|  |  |  |
|  |  | App Mesh Envoy Management Service 03/18/2022 |
| AWS App Runner | Logging App Runner API calls with AWS CloudTrail | 05/18/2021 |
| Amazon AppStream 2.0 | Logging Amazon AppStream 2.0 API Calls with AWS CloudTrail | 04/25/2019 |
| AWS AppSync | Logging AWS AppSync API Calls with AWS CloudTrail | 02/13/2018 |
| Amazon Athena | Logging Amazon Athena API Calls with AWS CloudTrail | 05/19/2017 |
| AWS Auto Scaling | Logging AWS Auto Scaling API Calls By Using CloudTrail | 08/15/2018 |
| AWS Backup | Logging AWS Backup API Calls with AWS CloudTrail | 02/04/2019 |
| AWS Batch | Logging AWS Batch API Calls with AWS CloudTrail | 1/10/2018 |
| AWS Billing and Cost Management | Logging AWS Billing and Cost Management API Calls with AWS CloudTrail | 06/07/2018 |
| AWS BugBust | Logging BugBust API calls using CloudTrail | 06/24/2021 |
| AWS Certificate Manager | Using AWS CloudTrail | 03/25/2016 |
| AWS Certificate Manager Private Certificate Authority | Using CloudTrail | 06/06/2019 |
| Amazon Chime | Log Amazon Chime Administration Calls Using AWS CloudTrail | 09/27/2017 |
| Amazon Cloud Directory | Logging Amazon Cloud Directory API Calls Using AWS CloudTrail | 01/26/2017 |
| AWS Cloud9 | Logging AWS Cloud9 API Calls with AWS CloudTrail | 01/21/2019 |
| AWS CloudFormation | Logging AWS CloudFormation API Calls in AWS CloudTrail | 04/02/2014 |
| Amazon CloudFront | Using AWS CloudTrail to Capture Requests Sent to the CloudFront API | 05/28/2014 |
| AWS CloudHSM | Logging AWS CloudHSM API Calls By Using AWS CloudTrail | 01/08/2015 |
| AWS Cloud Map | Logging AWS Cloud Map API Calls with AWS CloudTrail | 11/28/2018 |
| Amazon CloudSearch | Logging Amazon CloudSearch Configuration Service Calls Using AWS CloudTrail | 10/16/2014 |
| AWS CloudTrail | AWS CloudTrail API Reference (All CloudTrail API calls are logged by CloudTrail.) | 11/13/2013 |
| Amazon CloudWatch | Logging Amazon CloudWatch API Calls in AWS CloudTrail | 04/30/2014 |
| CloudWatch Events | Logging Amazon CloudWatch Events API Calls in AWS CloudTrail | 01/16/2016 |
| CloudWatch Logs | Logging Amazon CloudWatch Logs API Calls in AWS CloudTrail | 03/10/2016 |
| AWS CodeBuild | Logging AWS CodeBuild API Calls with AWS CloudTrail | 12/01/2016 |
| AWS CodeCommit | Logging AWS CodeCommit API Calls with AWS CloudTrail | 01/11/2017 |
| AWS CodeDeploy | Monitoring Deployments with AWS CloudTrail | 12/16/2014 |
| Amazon CodeGuru Reviewer | Logging Amazon CodeGuru Reviewer API Calls with AWS CloudTrail | 12/02/2019 |
| AWS CodePipeline | Logging CodePipeline API Calls By Using AWS CloudTrail | 07/09/2015 |
| AWS CodeStar | Logging AWS CodeStar API Calls with AWS CloudTrail | 06/14/2017 |
| AWS CodeStar Notifications | Logging AWS CodeStar Notifications API Calls with AWS CloudTrail | 11/05/2019 |
| Amazon Cognito | Logging Amazon Cognito API Calls with AWS CloudTrail | 02/18/2016 |
| Amazon Comprehend | Logging Amazon Comprehend API Calls with AWS CloudTrail | 01/17/2018 |
| Amazon Comprehend Medical | Logging Amazon Comprehend Medical API Calls by Using AWS CloudTrail | 11/27/2018 |
| AWS Config | Logging AWS Config API Calls By with AWS CloudTrail | 02/10/2015 |
| AWS Control Tower | Logging AWS Control Tower Actions with AWS CloudTrail | 08/12/2019 |
| Amazon Data Lifecycle Manager | Logging Amazon Data Lifecycle Manager API Calls Using AWS CloudTrail | 07/24/2018 |
| AWS Data Pipeline | Logging AWS Data Pipeline API Calls by using AWS CloudTrail | 12/02/2014 |
| AWS Database Migration Service (AWS DMS) | Logging AWS Database Migration Service API Calls Using AWS CloudTrail | 02/04/2016 |
| AWS DataSync | Logging AWS DataSync API Calls with AWS CloudTrail | 11/26/2018 |
| Amazon Detective | Logging Amazon Detective API calls with AWS CloudTrail | 03/31/2020 |
| AWS Device Farm | Logging AWS Device Farm API Calls By Using AWS CloudTrail | 07/13/2015 |
| AWS Direct Connect | Logging AWS Direct Connect API Calls in AWS CloudTrail | 03/08/2014 |
| AWS Directory Service | Logging AWS Directory Service API Calls by Using CloudTrail | 05/14/2015 |
| Amazon DocumentDB (with MongoDB compatibility) | Logging Amazon DocumentDB API Calls with AWS CloudTrail | 01/09/2019 |
| Amazon DynamoDB | Logging DynamoDB Operations By Using AWS CloudTrail | 05/28/2015 |
| Amazon Elastic Container Registry (Amazon ECR) | Logging Amazon ECR API Calls By Using AWS CloudTrail | 12/21/2015 |
| Amazon Elastic Container Service (Amazon ECS) | Logging Amazon ECS API Calls By Using AWS CloudTrail | 04/09/2015 |
| AWS Elastic Beanstalk (Elastic Beanstalk) | Using Elastic Beanstalk API Calls with AWS CloudTrail | 03/31/2014 |
| Amazon Elastic Block Store (Amazon EBS) | Logging API Calls Using AWS CloudTrail | Amazon EBS: 11/13/2013 |
|  |  |  |
| EBS direct APIs | Log API Calls for the EBS direct APIs with AWS CloudTrail | EBS direct APIs: 06/30/2020 |
| Amazon Elastic Compute Cloud (Amazon EC2) | Logging API Calls Using AWS CloudTrail | 11/13/2013 |
| Amazon EC2 Auto Scaling | Logging Auto Scaling API Calls By Using CloudTrail | 07/16/2014 |
| Amazon EC2 Image Builder | Logging EC2 Image Builder API calls using CloudTrail | 12/02/2019 |
| Amazon Elastic File System (Amazon EFS) | Logging Amazon EFS API Calls with AWS CloudTrail | 06/28/2016 |
| Amazon Fraud Detector | Logging Amazon Fraud Detector API Calls with AWS CloudTrail | 01/09/2020 |
| Amazon GameSparks | Log GameSparks API calls with AWS CloudTrail | 03/23/2022 |
| Amazon Elastic Kubernetes Service (Amazon EKS) | Logging Amazon EKS API Calls with AWS CloudTrail | 06/05/2018 |
| Elastic Load Balancing | AWS CloudTrail Logging for Your Classic Load Balancer and AWS CloudTrail Logging for Your Application Load Balancer | 04/04/2014 |
| Amazon Elastic Transcoder | Logging Amazon Elastic Transcoder API Calls with AWS CloudTrail | 10/27/2014 |
| Amazon ElastiCache | Logging Amazon ElastiCache API Calls Using AWS CloudTrail | 09/15/2014 |
| Amazon OpenSearch Service | Auditing Amazon OpenSearch Service Domains with AWS CloudTrail | 10/01/2015 |
| AWS Elemental MediaConnect | Logging AWS Elemental MediaConnect API Calls with AWS CloudTrail | 11/27/2018 |
| AWS Elemental MediaConvert | Logging AWS Elemental MediaConvert API Calls with CloudTrail | 11/27/2017 |
| AWS Elemental MediaLive | Logging MediaLive API Calls with AWS CloudTrail | 01/19/2019 |
| AWS Elemental MediaPackage | Logging AWS Elemental MediaPackage API Calls with AWS CloudTrail | 12/21/2018 |
| AWS Elemental MediaStore | Logging AWS Elemental MediaStore API Calls with CloudTrail | 11/27/2017 |
| AWS Elemental MediaTailor | Logging AWS Elemental MediaTailor API Calls with AWS CloudTrail | 02/11/2019 |
| Amazon EMR | Logging Amazon EMR API Calls in AWS CloudTrail | 04/04/2014 |
| Amazon EMR on EKS | Logging Amazon EMR on EKS API calls using AWS CloudTrail | 12/09/2020 |
| AWS Fault Injection Simulator | Log API calls with AWS CloudTrail | 03/15/2021 |
| AWS Firewall Manager | Logging AWS Firewall Manager API Calls with AWS CloudTrail | 04/05/2018 |
| Amazon Forecast | Logging Amazon Forecast API Calls with AWS CloudTrail | 11/28/2018 |
| FreeRTOS Over-the-Air Updates (OTA) | Logging AWS IoT OTA API Calls with AWS CloudTrail | 05/22/2019 |
| Amazon FSx for Lustre | Logging Amazon FSx for Lustre API Calls with AWS CloudTrail | 01/11/2019 |
| Amazon FSx for Windows File Server | Monitoring with AWS CloudTrail | 11/28/2018 |
| Amazon GameLift | Logging Amazon GameLift API Calls with AWS CloudTrail | 01/27/2016 |
| Amazon S3 Glacier | Logging S3 Glacier API Calls By Using AWS CloudTrail | 12/11/2014 |
| AWS Global Accelerator | Logging AWS Global Accelerator API Calls with AWS CloudTrail | 11/26/2018 |
| AWS Glue | Logging AWS Glue Operations Using AWS CloudTrail | 11/07/2017 |
| AWS Ground Station | Logging AWS Ground Station API Calls with AWS CloudTrail | 05/31/2019 |
| Amazon GuardDuty | Logging Amazon GuardDuty API Calls with AWS CloudTrail | 02/12/2018 |
| AWS Health | Logging AWS Health API Calls with AWS CloudTrail | 11/21/2016 |
| Amazon HealthLake | Logging Amazon HealthLake API calls with AWS CloudTrail | 12/07/2020 |
| Amazon Honeycode | Logging Amazon Honeycode API Calls with AWS CloudTrail | 06/24/2020 |
| Amazon Inspector | Logging Amazon Inspector API calls with AWS CloudTrail | 04/20/2016 |
| Amazon Interactive Video Service | Logging Amazon IVS API Calls with AWS CloudTrail | 07/15/2020 |
| AWS IoT | Logging AWS IoT API Calls with AWS CloudTrail | 04/11/2016 |
| AWS IoT Analytics | Logging AWS IoT Analytics API calls with AWS CloudTrail | 04/23/2018 |
| AWS IoT 1-Click | Logging AWS IoT 1-Click API Calls with AWS CloudTrail | 05/14/2018 |
| AWS IoT Events | Logging AWS IoT Events API Calls with AWS CloudTrail | 06/11/2019 |
| AWS IoT Greengrass | Logging AWS IoT Greengrass API Calls with AWS CloudTrail | 10/29/2018 |
| AWS IoT Greengrass V2 | Log AWS IoT Greengrass V2 API calls with AWS CloudTrail | 12/14/2020 |
| AWS IoT SiteWise | Logging AWS IoT SiteWise API calls with AWS CloudTrail | 04/29/2020 |
| AWS IoT Things Graph | Logging AWS IoT Things Graph API Calls with AWS CloudTrail | 05/31/2019 |
| AWS Identity and Access Management (IAM) | Logging IAM Events with AWS CloudTrail | 11/13/2013 |
| Amazon Kendra | Logging Amazon Kendra API calls with AWS CloudTrail | 05/11/2020 |
| AWS Key Management Service (AWS KMS) | Logging AWS KMS API Calls using AWS CloudTrail | 11/12/2014 |
| Amazon Kinesis Data Analytics | Monitoring Amazon Kinesis Data Analytics with AWS CloudTrail (SQL Applications) and Monitoring Amazon Kinesis Data Analytics with AWS CloudTrail (Apache Flink Applications) | 03/22/2019 |
| Amazon Kinesis Data Firehose | Monitoring Amazon Kinesis Data Firehose API Calls with AWS CloudTrail | 03/17/2016 |
| Amazon Kinesis Data Streams | Logging Amazon Kinesis Data Streams API Calls Using AWS CloudTrail | 04/25/2014 |
| Amazon Kinesis Video Streams | Logging Kinesis Video Streams API Calls with AWS CloudTrail | 05/24/2018 |
| AWS Lake Formation | Logging AWS Lake Formation API Calls Using AWS CloudTrail | 08/09/2019 |
| AWS Lambda | Logging AWS Lambda API Calls By Using AWS CloudTrail | Management events: 04/09/2015 |
|  |  |  |
|  | Using Lambda with AWS CloudTrail | Data events: 11/30/2017 |
| Amazon Lex | Logging Amazon Lex API Calls with CloudTrail | 08/15/2017 |
| AWS License Manager | Logging AWS License Manager API Calls with AWS CloudTrail | 03/01/2019 |
| Amazon Lightsail | Logging Lightsail API Calls with AWS CloudTrail | 12/23/2016 |
| Amazon Location Service | Logging and monitoring with AWS CloudTrail | 12/15/2020 |
| Amazon Lookout for Vision | Logging Amazon Lookout for Vision calls with AWS CloudTrail | 12/01/2020 |
| Amazon Lookout for Equipment | Monitoring Amazon Lookout for Equipment calls with AWS CloudTrail | 12/01/2020 |
| Amazon Lookout for Metrics | Viewing Amazon Lookout for Metrics API activity in AWS CloudTrail | 12/08/2020 |
| Amazon Machine Learning | Logging Amazon ML API Calls By Using AWS CloudTrail | 12/10/2015 |
| Amazon Macie | Log Amazon Macie API calls using AWS CloudTrail | 05/13/2020 |
| Amazon Managed Blockchain | Logging Amazon Managed Blockchain API calls using AWS CloudTrail | 04/01/2019 |
|  |  |  |
|  | Logging Ethereum for Managed Blockchain API calls using AWS CloudTrail (Preview) |  |
| Amazon Managed Grafana | Logging Amazon Managed Grafana API calls using AWS CloudTrail | 12/15/2020 |
| Amazon Managed Service for Prometheus | Logging Amazon Managed Service for Prometheus API calls using AWS CloudTrail | 12/15/2020 |
| Amazon Keyspaces (for Apache Cassandra) | Logging Amazon Keyspaces API calls with AWS CloudTrail | 01/13/2020 |
| AWS Managed Services | AWS Managed Services | 12/21/2016 |
| Amazon Managed Streaming for Apache Kafka | Logging Amazon MSK API Calls with AWS CloudTrail | 12/11/2018 |
| Amazon Managed Workflows for Apache Airflow | Monitoring Amazon MWAA API activity with AWS CloudTrail | 11/24/2020 |
| AWS Marketplace | Logging AWS Marketplace API Calls with AWS CloudTrail | 05/02/2017 |
| AWS Marketplace Metering Service | Logging AWS Marketplace API Calls with AWS CloudTrail | 08/22/2018 |
| AWS Migration Hub | Logging AWS Migration Hub API Calls with AWS CloudTrail | 08/14/2017 |
| AWS Mobile Hub | Logging AWS Mobile CLI API Calls with AWS CloudTrail | 06/29/2018 |
| Amazon MQ | Logging Amazon MQ API Calls Using AWS CloudTrail | 07/19/2018 |
| Amazon Neptune | Logging Amazon Neptune API Calls Using AWS CloudTrail | 05/30/2018 |
| AWS Network Firewall | Logging calls to the AWS Network Firewall API with AWS CloudTrail | 11/17/2020 |
| AWS OpsWorks for Chef Automate | Logging AWS OpsWorks for Chef Automate API Calls with AWS CloudTrail | 07/16/2018 |
| AWS OpsWorks for Puppet Enterprise | Logging OpsWorks for Puppet Enterprise API Calls with AWS CloudTrail | 07/16/2018 |
| AWS OpsWorks Stacks | Logging AWS OpsWorks Stacks API Calls with AWS CloudTrail | 06/04/2014 |
| AWS Organizations | Logging AWS Organizations Events with AWS CloudTrail | 02/27/2017 |
| AWS Outposts | Logging AWS Outposts API calls with AWS CloudTrail | 02/04/2020 |
| AWS Health Dashboard | Logging AWS Health API Calls with AWS CloudTrail | 12/01/2016 |
| Amazon Personalize | Logging Amazon Personalize API Calls with AWS CloudTrail | 11/28/2018 |
| Amazon Pinpoint | Logging Amazon Pinpoint API Calls with AWS CloudTrail | 02/06/2018 |
| Amazon Pinpoint SMS and Voice API | Logging Amazon Pinpoint API Calls with AWS CloudTrail | 11/16/2018 |
| Amazon Polly | Logging Amazon Polly API Calls with AWS CloudTrail | 11/30/2016 |
| Amazon Quantum Ledger Database (Amazon QLDB) | Logging Amazon QLDB API Calls with AWS CloudTrail | 09/10/2019 |
| AWS Certificate Manager Private Certificate Authority | Using CloudTrail | 04/04/2018 |
| Amazon QuickSight | Logging Operations with CloudTrail | 04/28/2017 |
| Amazon Redshift | Logging Amazon Redshift API Calls with AWS CloudTrail | 06/10/2014 |
| Amazon Rekognition | Logging Amazon Rekognition API Calls Using AWS CloudTrail | 04/6/2018 |
| Amazon Relational Database Service (Amazon RDS) | Logging Amazon RDS API Calls Using AWS CloudTrail | 11/13/2013 |
| Amazon RDS Performance Insights | Logging Amazon RDS API Calls Using AWS CloudTrail | 06/21/2018 |
|  | The Amazon RDS Performance Insights API is a subset of the Amazon RDS API. |  |
| AWS Resilience Hub | AWS CloudTrail | 11/10/2021 |
| AWS Resource Access Manager (AWS RAM) | Logging AWS RAM API Calls with AWS CloudTrail | 11/20/2018 |
| AWS Resource Groups | Logging AWS Resource Groups API Calls with AWS CloudTrail | 06/29/2018 |
| AWS RoboMaker | Logging AWS RoboMaker API Calls with AWS CloudTrail | 01/16/2019 |
| Amazon Route 53 | Using AWS CloudTrail to Capture Requests Sent to the Route 53 API | 02/11/2015 |
| Amazon Route 53 Application Recovery Controller | Logging Amazon Route 53 Application Recovery Controller API calls using AWS CloudTrail | 07/27/2021 |
| Amazon SageMaker | Logging Amazon SageMaker API Calls with AWS CloudTrail | 01/11/2018 |
| AWS Secrets Manager | Monitor the Use of Your AWS Secrets Manager Secrets | 04/05/2018 |
| AWS Security Hub | Logging AWS Security Hub API Calls with AWS CloudTrail | 11/27/2018 |
| AWS Security Token Service (AWS STS) | Logging IAM Events with AWS CloudTrail | 11/13/2013 |
|  |  |  |
|  | The IAM topic includes information for AWS STS. |  |
| AWS Server Migration Service | AWS SMS API Reference | 11/14/2016 |
| AWS Serverless Application Repository | Logging AWS Serverless Application Repository API Calls with AWS CloudTrail | 02/20/2018 |
| AWS Service Catalog | Logging AWS Service Catalog API Calls with AWS CloudTrail | 07/06/2016 |
| Service Quotas |  | 06/24/2019 |
| AWS Shield | Logging Shield Advanced API Calls with AWS CloudTrail | 02/08/2018 |
| Amazon Simple Email Service (Amazon SES) | Logging Amazon SES API Calls By Using AWS CloudTrail | 05/07/2015 |
| Amazon Simple Notification Service (Amazon SNS) | Logging Amazon Simple Notification Service API Calls By Using AWS CloudTrail | 10/09/2014 |
| Amazon Simple Queue Service (Amazon SQS) | Logging Amazon SQS API Actions Using AWS CloudTrail | 07/16/2014 |
| Amazon Simple Storage Service | Logging Amazon S3 API Calls By Using AWS CloudTrail | Management events: 09/01/2015 |
|  |  |  |
|  |  | Data events: 11/21/2016 |
| Amazon Simple Workflow Service (Amazon SWF) | Logging Amazon Simple Workflow Service API Calls with AWS CloudTrail | 05/13/2014 |
| AWS Single Sign-On (AWS SSO) | Logging AWS SSO API Calls with AWS CloudTrail | 12/07/2017 |
| AWS Snowball | Logging AWS Snowball API Calls with AWS CloudTrail | 01/25/2019 |
| AWS Snowball Edge | Logging AWS Snowball Edge API Calls with AWS CloudTrail | 01/25/2019 |
| AWS Step Functions | Logging AWS Step Functions API Calls with AWS CloudTrail | 12/01/2016 |
| Storage Gateway | Logging Storage Gateway API Calls by Using AWS CloudTrail | 12/16/2014 |
| AWS Support | Logging AWS Support API Calls with AWS CloudTrail | 04/21/2016 |
| AWS Systems Manager | Logging AWS Systems Manager API Calls with AWS CloudTrail | 11/13/2013 |
| AWS Systems Manager Incident Manager | Logging AWS Systems Manager Incident Manager API calls using AWS CloudTrail | 05/10/2021 |
| Amazon Textract | Logging Amazon Textract API Calls with AWS CloudTrail | 05/29/2019 |
| Amazon Transcribe | Logging Amazon Transcribe API Calls with AWS CloudTrail | 06/28/2018 |
| AWS Transfer for SFTP | Logging AWS Transfer for SFTP API Calls with AWS CloudTrail | 01/08/2019 |
| Amazon Translate | Logging Amazon Translate API Calls with AWS CloudTrail | 04/04/2018 |
| AWS Transit Gateway | Logging API Calls for Your Transit Gateway Using AWS CloudTrail | 11/26/2018 |
| AWS Trusted Advisor | Logging AWS Trusted Advisor console actions with AWS CloudTrail | 10/22/2020 |
| Amazon Virtual Private Cloud (Amazon VPC) | Logging API Calls Using AWS CloudTrail | 11/13/2013 |
|  |  |  |
|  | The Amazon VPC API is a subset of the Amazon EC2 API. |  |
| AWS WAF | Logging AWS WAF API Calls with AWS CloudTrail | 04/28/2016 |
| AWS Well-Architected Tool | Logging AWS Well-Architected Tool API Calls with AWS CloudTrail | 12/15/2020 |
| Amazon WorkDocs | Logging Amazon WorkDocs API Calls By Using AWS CloudTrail | 08/27/2014 |
| Amazon WorkLink | Logging Amazon WorkLink API Calls with AWS CloudTrail | 01/23/2019 |
| Amazon WorkMail | Logging Amazon WorkMail API Calls Using AWS CloudTrail | 12/12/2017 |
| Amazon WorkSpaces | Logging Amazon WorkSpaces API Calls by Using CloudTrail | 04/09/2015 |
| Amazon WorkSpaces Web | Logging Amazon WorkSpaces Web API calls using AWS CloudTrail | 11/30/2021 |
| AWS X-Ray | Logging AWS X-Ray API Calls With CloudTrail | 04/25/2018 |
</div></details>

<details><summary>サポートされないサービス一覧</summary><div>

| AWS のサービス | 開始日 |
| --- | --- |
| AWS Import/Export | 2020 年 6 月 17 日 |
| AWS Price List サービス | 2018 年 12 月 17 日 |
| AWS Deep Learning AMI | 2017 年 11 月 15 日 |
| Amazon WorkSpaces Application Manager | 2015 年 4 月 9 日 |
| AWS Artifact | 2016 年 11 月 30 日 |
| AWS DeepComposer | 2019 年 12 月 2 日 |
| AWS DeepLens | 2017 年 11 月 29 日 |
| AWS DeepRacer | 2019 年 4 月 29 日 |
| AWS Snowmobile | 2016 年 11 月 30 日 |
| Amazon Sumerian | 2018 年 5 月 15 日 |
</div></details>

### 参考
[AWSBlackbelt_CloudTrail](https://d1.awsstatic.com/webinars/jp/pdf/services/20210119_AWSBlackbelt_CloudTrail.pdf)

## 事前準備

<details><summary>ChatbotとSlack連携</summary><div>

事前にchatbotがslackworkspaceにアクセスする権限を付与しておきましょう。

- AWS Chatbotコンソールより「チャットクライアント」を「Slack」にして「クライアントを設定」を押下する
 <img width="713" alt="スクリーンショット_2022-03-12_16_05_21.png (64.0 kB)" src="https://img.esa.io/uploads/production/attachments/10655/2022/03/12/108350/3380bf47-3651-4dfc-b391-03dd2152d3e5.png">

- アクセス権限をリクエスト画面が表示されたら対象のSlackワークスペースを確認して「許可する」を押下する
<img width="531" alt="スクリーンショット_2022-03-12_16_13_16.png (69.1 kB)" src="https://img.esa.io/uploads/production/attachments/10655/2022/03/12/108350/33ba529b-7d34-4018-a150-8cbd8a23b6ae.png">

</div></details>

## CDK
今回も複数のStackで関連リソースを展開させます。

ContextのslackWorkspaceIdとslackChannelIdは検証者の環境を適宜指定

<details><summary>cdk.json</summary><div>

```cdk.json
{
  "app": "npx ts-node --prefer-ts-exts bin/src.ts",
  "watch": {
    "include": [
      "**"
    ],
    "exclude": [
      "README.md",
      "cdk*.json",
      "**/*.d.ts",
      "**/*.js",
      "tsconfig.json",
      "package*.json",
      "yarn.lock",
      "node_modules",
      "test"
    ]
  },
  "context": {
    "@aws-cdk/aws-apigateway:usagePlanKeyOrderInsensitiveId": true,
    "@aws-cdk/core:stackRelativeExports": true,
    "@aws-cdk/aws-rds:lowercaseDbIdentifier": true,
    "@aws-cdk/aws-lambda:recognizeVersionProps": true,
    "@aws-cdk/aws-cloudfront:defaultSecurityPolicyTLSv1.2_2021": true,
    "@aws-cdk-containers/ecs-service-extensions:enableDefaultLogDriver": true,
    "@aws-cdk/core:target-partitions": [
      "aws",
      "aws-cn"
    ],
    "prefix": "sample",
    "slackWorkspaceId":"xxxxxxxxx",
    "slackChannelId":"xxxxxxxxxx",
  }
}
```

</div></details>

<details><summary>bin/src.ts</summary><div>

```bin/src.ts
#!/usr/bin/env node
import * as cdk from "aws-cdk-lib";
import { SnsStack } from "../lib/sns-stack";
import { ChatbotStack } from "../lib/chatbot-stack";
import { SecrityStack } from "../lib/secrity-stack";

const app = new cdk.App();
const prefix = app.node.tryGetContext("prefix"); // Contextで指定したprefixを取得

const snsStack = new SnsStack(app, `${prefix}-sns-stack`);
const chatbotStack = new ChatbotStack(app, `${prefix}-chatbot-stack`, snsStack);
const securityStack = new SecrityStack(app, `${prefix}-security-stack`, snsStack);

chatbotStack.addDependency(snsStack);
securityStack.addDependency(snsStack);
```

</div></details>

<details><summary>lib/sns-stack.ts</summary><div>

```sns-stack.ts
import * as cdk from "aws-cdk-lib";
import * as sns from "aws-cdk-lib/aws-sns";
import * as iam from 'aws-cdk-lib/aws-iam';

export interface SnsStackProps { 
  readonly snsTopic: sns.Topic
}

export class SnsStack extends cdk.Stack {
  public readonly snsTopic: sns.Topic

  // SNS Topic
  private createSnsTopic(name: string): sns.Topic {

    const snsTopic = new sns.Topic(this, `${name}`, {
      displayName: "security Nottification",
      topicName: name,
    });
    snsTopic.addToResourcePolicy(new iam.PolicyStatement({
      sid: 'SNSPublishingPermissions',
      effect: iam.Effect.ALLOW,
      principals: [
        new iam.ServicePrincipal('config.amazonaws.com'),
        new iam.ServicePrincipal('events.amazonaws.com')
      ],
      actions: ['SNS:Publish'],
      resources: [snsTopic.topicArn],
    }));
    return snsTopic;
  }

  constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    const prefix = this.node.tryGetContext("prefix"); // Contextで指定したprefixを取得

    this.snsTopic = this.createSnsTopic(`${prefix}-sns-topic`);
  }
}
```

</div></details>

<details><summary>lib/chatbot-stack.ts</summary><div>

```chatbot-stack.ts
import * as cdk from "aws-cdk-lib";
import * as sns from "aws-cdk-lib/aws-sns";
import type { SnsStackProps } from "./sns-stack"
import * as chatbot from "aws-cdk-lib/aws-chatbot";

export class ChatbotStack extends cdk.Stack {

  // Chatbot
  private createChatbot(name: string, sns: sns.Topic): chatbot.SlackChannelConfiguration {
    const slackWorkspaceId = this.node.tryGetContext("slackWorkspaceId"); // Contextで指定したslackworkspaceidを取得
    const slackChannelId = this.node.tryGetContext("slackChannelId"); // Contextで指定したslackchannelidを取得

    const slackchatbot = new chatbot.SlackChannelConfiguration(this, `${name}`, {
      slackChannelConfigurationName: name,
      slackWorkspaceId: slackWorkspaceId, // 事前にコンソール上でchatbotがslackworkspaceにアクセスする権限を与えていること
      slackChannelId: slackChannelId,
      loggingLevel: chatbot.LoggingLevel.INFO,
      notificationTopics: [sns],
    });
    return slackchatbot;
  }

  constructor(scope: cdk.App, id: string, SnsStack: SnsStackProps, props?: cdk.StackProps) {
    super(scope, id, props);

    const prefix = this.node.tryGetContext("prefix"); // Contextで指定したprefixを取得

    this.createChatbot(`${prefix}-chatbot`, SnsStack.snsTopic);
  }
}
```

</div></details>

### security-stack

作成するリソース

| リソース | 設定値 |
| --- | --- |
| S3 | 暗号化<br>1年後にGlacierへ移行<br>パブリック・アクセスブロック<br>削除ポリシー(Destroy) |
| SecurityHub | 基礎セキュリティのベストプラクティスの自動チェック有効化 |
| GuardDuty | GuardDuty有効化 |
| CloudTrail | CloudWatchlogsへ配信有効化<br>ログファイルの整合性の検証を有効 |
| Config | サポートされている全てのサービスを記録(グローバルサービス含む)<br>24時間毎に記録情報をS3、snsに配信 |
| EventBridge | GuardDuty->重要度：高以上で通知<br>SecurityHub->コンプライアンスチェックにPassしなかったもので、重要度がMIDDLE以上の新規項目を通知<br>Config->リソース設定などが変更されたものを通知<br>Trail->RootユーザによるAWSコンソールログインを通知 |

※Defaultで適用される設定を除いた項目

```lib/security-stack.ts
import * as cdk from "aws-cdk-lib";
import type { SnsStackProps } from "./sns-stack"
import * as iam from 'aws-cdk-lib/aws-iam';
import * as sns from 'aws-cdk-lib/aws-sns';
import * as s3 from "aws-cdk-lib/aws-s3";
import * as sechub from 'aws-cdk-lib/aws-securityhub';
import * as guardduty from 'aws-cdk-lib/aws-guardduty';
import * as config from 'aws-cdk-lib/aws-config';
import * as trail from 'aws-cdk-lib/aws-cloudtrail';
import * as events from "aws-cdk-lib/aws-events";
import * as targets from "aws-cdk-lib/aws-events-targets";

export interface SecrityStackProps {
  readonly s3bucket: s3.Bucket;
}

export class SecrityStack extends cdk.Stack {
  public readonly s3bucket: s3.Bucket;

  // S3
  private createS3Bucket(name: string): s3.Bucket {
    const accountId = cdk.Stack.of(this).account;

    const s3bucket = new s3.Bucket(this, `${name}`, {
      bucketName: name,
      encryption: s3.BucketEncryption.S3_MANAGED,
      blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
      removalPolicy: cdk.RemovalPolicy.DESTROY, // 動作確認後に削除させるため'DESTROY'
      lifecycleRules: [{
        id: `${name}-lifecycleRule`,
        transitions: [
          {storageClass: s3.StorageClass.GLACIER, transitionAfter: cdk.Duration.days(365)}, // 1年後Glacierへ
        ]
      }]
    });
    s3bucket.addToResourcePolicy(new iam.PolicyStatement({
      sid: `AWSConfigBucketPermissionsCheck`,
      effect: iam.Effect.ALLOW,
      principals: [new iam.ServicePrincipal(`config.amazonaws.com`)],
      actions: ["s3:GetBucketAcl"],
      resources: [s3bucket.bucketArn],
    }))
    s3bucket.addToResourcePolicy(new iam.PolicyStatement({
      sid: `AWSConfigBucketDelivery`,
      effect: iam.Effect.ALLOW,
      principals: [new iam.ServicePrincipal(`config.amazonaws.com`)],
      actions: ["s3:PutObject"],
      resources: [s3bucket.bucketArn + "/AWSLogs/" + accountId + "/*"],
    }))
  return s3bucket;
  }

  // securityhub
  private createSecurityHub(name: string): void {

    const securityhub = new sechub.CfnHub(this, `${name}`, {
      tags: {
        key: "Name",
        value: `${name}`,
      },
    });
  }

  // GuardDuty
  private createGuardDuty(name: string): void {

    const detector = new guardduty.CfnDetector(this, `${name}`, {
      enable: true,
    });
  }

  // Config
  private createConfig(name: string, sns: sns.Topic, s3: s3.IBucket): void {

    const configrole = new iam.Role(this, `${name}-configrole`, {
      roleName: name,
      path: '/',
      assumedBy: new iam.CompositePrincipal(
        new iam.ServicePrincipal('config.amazonaws.com')
      ),
      managedPolicies: [
        iam.ManagedPolicy.fromAwsManagedPolicyName('service-role/AWS_ConfigRole'),
      ]
    });

    const recorder = new config.CfnConfigurationRecorder(this, `${name}-configdetector`, {
      name: name,
      recordingGroup: {
        allSupported: true, // サポートされている全てのサービスを記録
        includeGlobalResourceTypes: true // グローバルリソースを含める
      },
      roleArn: configrole.roleArn
    });

    const deliverychannel = new config.CfnDeliveryChannel(this, `${name}-cinfigdeliverychannel`, {
      name: name,
      s3BucketName: s3.bucketName,
      configSnapshotDeliveryProperties: {deliveryFrequency: 'TwentyFour_Hours'},　// 24時間毎に記録情報を配信
      snsTopicArn: sns.topicArn,
    });
  }

  // CloudTrail
  private createCloudTrail(name: string, s3: s3.Bucket): void {

    const cloudtrail = new trail.Trail(this, `${name}`, {
      trailName: name,
      sendToCloudWatchLogs: true, // logs送信を有効
      enableFileValidation: true, // ログファイルの整合性の検証を有効
      bucket: s3,
    });
  }

  // EventBridge
  private createEvent(name: string, sns: sns.Topic): void {

    // GuardDuty(脅威検出のEvent通知)
    const guardDutyRule = new events.Rule(this, `${name}-guardduty`, {
      eventPattern: {
        source: ['aws.guardduty'],
        detailType: ['GuardDuty Finding'],
        detail: {
          severity:[{numeric: [">=", 7]}] //　重要度：高　以上で通知。　低:0.1〜3.9,中:4.0〜6.9,高:7.0〜8.9
        }
      },
      ruleName: `${name}-guardduty`,
    });
    guardDutyRule.addTarget(new targets.SnsTopic(sns)) 

    // SecurityHub(セキュリティチェック結果のEvent通知)
    const secrityHubRule = new events.Rule(this, `${name}-sechub`, {
      eventPattern: {
        source: ['aws.securityhub'],
        detailType: ['Security Hub Findings - Imported'],
        detail: {
          findings: {
            Compliance: { Status: ['FAILED', 'WARNING', 'NOT_AVAILABLE']}, //セキュリティチェックに"PASSED"しなかったもの以外
            RecordState: ['ACTIVE'],
            Severity: { Label: ['MEDIUM' ,'HIGH', 'CRITICAL']}, //　重要度がMEDIUM、HIGH、CRITICALのものを対象
            Workflow: { Status: ['NEW']} //　通知済のものは除外して、新規のものだけ
          }
        }
      },
      ruleName: `${name}-sechub`,
    });
    secrityHubRule.addTarget(new targets.SnsTopic(sns))

    // Config(リソース各種の設定変更でEvent通知)
    // ※通知が非常に多くなるので実際には対象を絞るなりする
    const configRule = new events.Rule(this, `${name}-config`, {
      eventPattern: {
        source: ['aws.config'],
        detailType: ['Config Configuration Item Change'],
        detail: {
          messageType:['ConfigurationItemChangeNotification']
        }
      },
      ruleName: `${name}-config`,
    });
    configRule.addTarget(new targets.SnsTopic(sns))

    // root login(rootユーザによるAWSコンソールログインでEvent通知)
    const rootloginRule = new events.Rule(this, `${name}-rootlogin`, {
      eventPattern: {
        detailType: ['AWS Console Sign In via CloudTrail'],
        detail: {
          userIdentity: {
            type: ['Root']
          }
        }
      },
      ruleName: `${name}-rootlogin`,
    });
    rootloginRule.addTarget(new targets.SnsTopic(sns))
  }

  constructor(scope: cdk.App, id: string, SnsStack: SnsStackProps, props?: cdk.StackProps) {
    super(scope, id, props);

    const prefix = this.node.tryGetContext("prefix"); // Contextで指定したprefixを取得

    this.s3bucket = this.createS3Bucket(`${prefix}-s3bucket`);
    this.createSecurityHub(`${prefix}-securityhub`);
    this.createGuardDuty(`${prefix}-detector`);
    this.createConfig(`${prefix}-config`, SnsStack.snsTopic, this.s3bucket);
    this.createCloudTrail(`${prefix}-trail`,this.s3bucket);
    this.createEvent(`${prefix}-event`, SnsStack.snsTopic);
  }
}
```

## slack通知動作確認
### SecurityHub
<img width="608" alt="スクリーンショット_2022-03-22_1_04_35.png (46.3 kB)" src="https://img.esa.io/uploads/production/attachments/10655/2022/03/22/108350/a53913af-2644-4908-b7ee-8f3e0161fbfd.png">

### GuardDuty
<img width="654" alt="スクリーンショット_2022-03-22_1_05_39.png (42.0 kB)" src="https://img.esa.io/uploads/production/attachments/10655/2022/03/22/108350/ec9075e7-28b0-4e55-bd92-a46afaa327c2.png">

### Config
<img width="649" alt="スクリーンショット_2022-03-22_1_05_03.png (40.4 kB)" src="https://img.esa.io/uploads/production/attachments/10655/2022/03/22/108350/4b63b32e-735d-4a1d-9a9b-08cd4bf5be5d.png">

### CloudTrail(RootLogin)
<img width="582" alt="スクリーンショット_2022-03-22_1_39_20.png (58.9 kB)" src="https://img.esa.io/uploads/production/attachments/10655/2022/03/22/108350/a4386b52-aec5-41a1-b27b-870ab74a430b.png">

## さいごに
:::note info
Chatbotは、2021年の春頃にEventBridgeでサポートされるイベントパターンが大きく拡張されたことで様々なイベントを連携させることが出来る様になり、Slackへの通知の実装が楽になりました。
[AWS Chatbot が Amazon EventBridge を通じて AWS のサービスのモニタリング範囲を拡大](https://aws.amazon.com/jp/about-aws/whats-new/2021/04/aws-chatbot-now-expands-coverage-of-aws-services-monitored-through-amazon-eventbridge/)
:::

昔はLambdaとか使ってゴニョゴニョしないといけなかったですが、そのおかげもあってCDKでもEventBridgeを駆使すれば大体は出来そうな感覚が掴めたので今後のChatOpsが捗りますね。

何かとCDKでSlackへ通知させたがる人みたいになってますが慣れてきたので次は違うネタ書こうと思います！

## 参考
https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_guardduty-readme.html
https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_config-readme.html
https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_securityhub-readme.html
https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudtrail-readme.html