LoginSignup
9
5

More than 5 years have passed since last update.

AWS Lambda で Amazon Inspector によるEC2のセキュリティ脆弱性評価を実行する

Last updated at Posted at 2016-11-16

はじめに

Amazon InspectorというAmazon EC2インスタンスのセキュリティ脆弱性評価を行えるサービスがあります。
https://aws.amazon.com/jp/inspector/

Amazon InspectorによるEC2インスタンスの脆弱性評価について、AWS CLIを用いてコマンドで実行したり、AWS Lambdaで実行出来ないか調査しました。

AWS Lambdaファンクション(Node.js 4.3)を作成して、Amazon Inspectorによる脆弱性評価を実行する方法が分かりましたので、ご参考までに以下に記します。

また、AWS CLI(aws inspector start-assessment-runコマンド)による脆弱性評価実行方法も以下に記します。

AWS Lambdaファンクションと脆弱性評価対象のEC2インスタンスについて

作成したAWS Lambdaファンクションは Node.js 4.3になります。

Amazon Inspectorによる脆弱性評価対象のEC2インスタンスはAmazon Linuxです。以下のAMIを使用してインスタンスを作成しました。

・amzn-ami-hvm-2016.09.0.20160923-x86_64-gp2 (ami-1a15c77b)

脆弱性評価対象のEC2インスタンスのOSバージョンは以下になります。

脆弱性評価対象EC2インスタンスのOSバージョン
[ec2-user@example-server ~]$ uname -a
Linux example-server 4.4.30-32.54.amzn1.x86_64 #1 SMP Thu Nov 10 15:52:05 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux
[ec2-user@example-server ~]$ 

[ec2-user@example-server ~]$ cat /etc/system-release
Amazon Linux AMI release 2016.09
[ec2-user@example-server ~]$

参考資料

Amazon Inspectorの設定にあたり、以下の資料を参考にさせて頂きました。
とても参考になりました。ありがとうございました。

Amazon Inspector自体については、以下をご参照下さい。
https://docs.aws.amazon.com/ja_jp/inspector/latest/userguide/inspector_introduction.html

Amazon InspectorのAPIリファレンスについては、以下をご参照下さい。
http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Inspector.html#startAssessmentRun-property
http://docs.aws.amazon.com/ja_jp/inspector/latest/APIReference/API_StartAssessmentRun.html

EC2インスタンスへのAmazon Inspectorエージェント(AwsAgent)インストールについては、以下をご参照下さい。
https://docs.aws.amazon.com/ja_jp/inspector/latest/userguide/inspector_settingup.html
https://docs.aws.amazon.com/ja_jp/inspector/latest/userguide/inspector_working-with-agents.html

AWS CLIのリファレンスについては、以下をご参照下さい。
http://docs.aws.amazon.com/cli/latest/reference/inspector/start-assessment-run.html

Amazon Inspector導入手順 + AWSマネジメントコンソールでEC2インスタンスの脆弱性評価実行手順については、以下をご参照下さい。

【速報】Amazon Inspectorが正式リリースされました
http://dev.classmethod.jp/cloud/aws/aws-inspector/

Amazon Inspector プレビューを試してみた #reinvent
http://dev.classmethod.jp/cloud/aws/inspector-preview/

Amazon Inspectorに作成した脆弱性評価テンプレート

Amazon InspectorでEC2インスタンスのセキュリティ脆弱性評価を実行するには、Amazon Inspector評価テンプレートを作成します。

本手順では、例として以下の評価テンプレートを作成したという前提で説明させて頂きます。

設定項目 設定項目の例
評価テンプレート名 example-template
評価テンプレートのARN(Amazonリソースネーム) arn:aws:inspector:ap-northeast-1:XXXXXXXXXXXX:target/0-XXXXXXXX/template/X-XXXXXXXX

スクリーンショット 2016-11-16 21.15.25.png

※本文に記載する図については、一部白抜きでマスクしている部分があります。

また、脆弱性評価対象のEC2インスタンスにも、Amazon Inspectorエージェント(AwsAgent)をインストールして、起動しておきます。

[ec2-user@example-server ~]$ chkconfig --list | grep awsagent
awsagent        0:off   1:off   2:on    3:on    4:on    5:on    6:off
[ec2-user@example-server ~]$ 
[ec2-user@example-server ~]$ rpm -qa | grep AwsAgent
AwsAgentKernelModule__amzn__4.4.30-32.54.amzn1-1.0.18.10-0.x86_64
AwsAgent-1.0.536.0-100536.x86_64
AwsAgentKernelModule__amzn__4.4.23-31.54.amzn1-1.0.18.5-0.x86_64
[ec2-user@example-server ~]$ 
[ec2-user@example-server ~]$ ps awux | grep -v grep | grep awsagent
root      2616  0.1  3.6 570932 37508 ?        Ssl  10:04   0:20 /opt/aws/awsagent/bin/awsagent
[ec2-user@example-server ~]$ 

AWS CLI(コマンド)によるAmazon Inspector脆弱性評価実行について

まず、AWS CLIを使って、コマンドでAmazon Inspectorの脆弱性評価を実行する例を記します。

(1) EC2インスタンスのIAMロールに対して、Amazon Inspectorによる脆弱性評価実行を許可するIAMポリシーを追加します。

AWS CLIを実行するEC2インスタンスのIAMロールに対して、以下のIAMポリシーを追加します。

Amazon Inspectorによる脆弱性評価コマンドの実行を許可するIAMポリシーになります。

AmazonInspectorRunAssessmentポリシー
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "inspector:Get*",
                "inspector:List*",
                "inspector:Preview*",
                "inspector:Describe*",
                "inspector:StartAssessmentRun",
                "inspector:StartDataCollection",
                "inspector:AddAttributesToFindings",
                "inspector:AttachAssessmentAndRulesPackage",
                "inspector:DetachAssessmentAndRulesPackage",
                "inspector:GetAssessmentTelemetry",
                "inspector:LocalizeText",
                "inspector:PreviewAgentsForResourceGroup",
                "inspector:RegisterCrossAccountAccessRole",
                "inspector:RemoveAttributesFromFindings",
                "inspector:RetireRulesPackage",
                "inspector:RunAssessment",
                "inspector:SetTagsForResource",
                "inspector:UpdateApplication",
                "inspector:UpdateAssessment",
                "ec2:DescribeInstances",
                "ec2:DescribeTags",
                "sns:ListTopics"
            ],
            "Resource": "*"
        }
    ]
}

(2) EC2インスタンスにログインし、AWS CLIでAmazon Inspectorによる脆弱性評価を実行します。

AWS CLIを実行して、Amazon InspectorによりEC2インスタンスの脆弱性評価を実行します。

パラメータ名 パラメータ内容
--assessment-template-arn Amazon Inspector脆弱性評価テンプレートのARNを指定します
--assessment-run-name Amazon Inspector脆弱性評価結果に付けたい名前を指定します。この例では 「example-server-20161116-213151」 のような名前を指定しています。

Amazon InspectorによるEC2インスタンスの脆弱性評価実行コマンドは以下のようになります。

/usr/bin/aws inspector start-assessment-run --region ap-northeast-1 --assessment-template-arn "arn:aws:inspector:ap-northeast-1:XXXXXXXXXXXX:target/0-XXXXXXXX/template/X-XXXXXXXX" --assessment-run-name "`/bin/hostname`-`/bin/date '+%Y%m%d-%H%M%S'`"
[ec2-user@example-server ~]$ /bin/hostname
example-server
[ec2-user@example-server ~]$ /bin/date '+%Y%m%d-%H%M%S'
20161116-213151
[ec2-user@example-server ~]$ 

以下のようなコマンドを実行すると、Amazon InspectorによるEC2インスタンスの脆弱性評価を実行出来ます。

[ec2-user@example-server ~]$ /usr/bin/aws inspector start-assessment-run --region ap-northeast-1 --assessment-template-arn "arn:aws:inspector:ap-northeast-1:XXXXXXXXXXXX:target/0-XXXXXXXX/template/X-XXXXXXXX" --assessment-run-name "`/bin/hostname`-`/bin/date '+%Y%m%d-%H%M%S'`"
{
    "assessmentRunArn": "arn:aws:inspector:ap-northeast-1:XXXXXXXXXXXX:target/0-XXXXXXXX/template/X-XXXXXXXX/run/0-XXXXXXXX"
}
[ec2-user@example-server ~]$ 

AWS LambdaによるAmazon Inspector脆弱性評価実行について

(1) Lambda用のIAMロールに対して、Amazon Inspectorによる脆弱性評価実行を許可するIAMポリシーを追加します。

Lambdaファンクション用のIAMロール「example-lambda-amazon-inspector-assessment-role」を作成し、以下のIAMポリシーを追加します。

Amazon Inspectorによる脆弱性評価APIの実行を許可するIAMポリシーになります。

AmazonInspectorRunAssessmentポリシー
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "inspector:Get*",
                "inspector:List*",
                "inspector:Preview*",
                "inspector:Describe*",
                "inspector:StartAssessmentRun",
                "inspector:StartDataCollection",
                "inspector:AddAttributesToFindings",
                "inspector:AttachAssessmentAndRulesPackage",
                "inspector:DetachAssessmentAndRulesPackage",
                "inspector:GetAssessmentTelemetry",
                "inspector:LocalizeText",
                "inspector:PreviewAgentsForResourceGroup",
                "inspector:RegisterCrossAccountAccessRole",
                "inspector:RemoveAttributesFromFindings",
                "inspector:RetireRulesPackage",
                "inspector:RunAssessment",
                "inspector:SetTagsForResource",
                "inspector:UpdateApplication",
                "inspector:UpdateAssessment",
                "ec2:DescribeInstances",
                "ec2:DescribeTags",
                "sns:ListTopics"
            ],
            "Resource": "*"
        }
    ]
}

Lambdaファンクション実行時にCloudWatchLogsにLambda実行ログを出力する為のIAMポリシーを追加します。

ExampleLambdaFunctionOutPutCloudWatchLogsポリシー
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogGroup",
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ],
            "Resource": "arn:aws:logs:*:*:*"
        }
    ]
}

(2) Amazon Inspectorによる脆弱性評価を実行するAWS Lambdaファンクションを作成します。

AWSマネジメントコンソールにログインして「Lambda」をクリックします。

スクリーンショット 2016-11-16 21.44.30.png

「Create a Lambda function」をクリックします。

スクリーンショット 2016-11-16 21.43.18.png

「Select blueprint」では「hello-world」をクリックします。

スクリーンショット 2016-11-16 21.47.37.png

「Configure triggers」では「Next」をクリックします。
スクリーンショット 2016-11-16 21.49.03.png

「Configure function」では以下のように入力・選択します。

設定項目 設定例
Name example-lambda-amazon-inspector-assessment
Description example-lambda-amazon-inspector-assessment
Runtime* Node.js 4.3

スクリーンショット 2016-11-16 21.59.24.png

「Lambda function code」に以下のコードを入力します。

example-lambda-amazon-inspector-assessmentファンクションのコード
'use strict';

// http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Inspector.html#startAssessmentRun-property
var AWS = require('aws-sdk')
  , inspector = new AWS.Inspector({ apiVersion: '2016-02-16' })
  ;

exports.handler = (event, context) => {

  console.log('Start Amazon Inspector AssessmentRun');

  // Add timedate to description
  var date = new Date();
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var day = date.getDate();
  var hour = date.getHours();
  var minutes = date.getMinutes();
  if ( day < 10 ) {
    day = '0' + day;
  }
  // UTC to JST
  hour += 9;
  if ( hour < 10 ) {
    hour = '0' + hour;
  }
  if ( minutes < 10 ) {
    minutes = '0' + minutes;
  }
  var assessmentRunDate = '-' + year.toString() + month.toString() + day.toString() + '-' + hour.toString() + minutes.toString();

  var params = {
    assessmentTemplateArn: 'arn:aws:inspector:ap-northeast-1:XXXXXXXXXXXX:target/0-XXXXXXXX/template/X-XXXXXXXX',
    assessmentRunName: 'example-server' + assessmentRunDate
  };

  inspector.startAssessmentRun(params, function(err, data) {
    if (err) context.done(err, err.stack);
    else context.done(null, data);
  });

};

スクリーンショット 2016-11-17 16.06.13.png

「Lambda function handler and role」では以下のように入力・選択します。
作成するLambdaファンクションのIAMロールは前述で作成した「example-lambda-amazon-inspector-assessment-role」ロールを指定します。

設定項目 設定例
Handler* index.handler
Role* Choose an exitsing role
Existing role* example-lambda-amazon-inspector-assessment-role

スクリーンショット 2016-11-16 22.06.02.png

「Advanced settings」ではデフォルトのままで「Next」をクリックします。

設定項目 設定例
Memory (MB)* 128
Timeout 0 min 3 sec
VPC No VPC

スクリーンショット 2016-11-16 22.07.52.png

「Review」で作成するLambdaファンクション情報が表示されるので「Create Function」をクリックします。

スクリーンショット 2016-11-16 22.08.10.png

(3) Amazon Inspector脆弱性評価実行用のAWS Lambdaファンクションが作成された事を確認します。

スクリーンショット 2016-11-16 22.11.07.png

スクリーンショット 2016-11-16 22.12.05.png

(4) AWS Lambdaファンクションを実行し、Amazon InspectorによるEC2インスタンス脆弱性評価を実行します。

「Test」をクリックして、Lambdaファンクションを実行します。

スクリーンショット 2016-11-16 22.12.57.png

「Input test event」と表示されるので「Save and test」をクリックします。

スクリーンショット 2016-11-16 22.14.47.png

スクリーンショット 2016-11-16 22.14.56.png

Lambdaファンクション実行結果「Execution result: succeeded」に以下のように表示されていれば、Amazon InspectorによるEC2インスタンス脆弱性評価が正常に開始されています。

Lambdaファンクション実行結果
{
  "assessmentRunArn": "arn:aws:inspector:ap-northeast-1:XXXXXXXXXXXX:target/0-XXXXXXXX/template/X-XXXXXXXX/run/0-XXXXXXXX"
}

スクリーンショット 2016-11-16 22.18.01.png
}

スクリーンショット 2016-11-16 22.16.35.png

スクリーンショット 2016-11-16 22.18.01.png

(5) AWS Lambdaファンクションの実行でAmazon InspectorによるEC2インスタンス脆弱性評価が実行されている事を確認します。

Amazon InspectorによるEC2インスタンス脆弱性評価の実行状態はAWSマネジメントコンソールの「Inspector」の「評価の実行」で確認出来ます。

AWS LambdaファンクションでAmazon InspectorによるEC2インスタンス脆弱性評価が正常に実行された場合、AWSマネジメントコンソールの「Inspector」->「評価の実行」をクリックします。

「ステータス」に「データの収集中」と表示されている場合、C2インスタンス脆弱性評価が実行中になります。

今回のLambdaファンクションを実行した場合、脆弱性評価結果には以下のような名前がつきます。

脆弱性評価結果の名前の例(11月17日に評価を実行した場合の例)
example-server-20161117-1552

スクリーンショット 2016-11-17 15.53.46.png

(6) Amazon InspectorによるEC2インスタンス脆弱性評価が完了した事を確認します。

AWSマネジメントコンソールの「Inspector」->「評価の実行」をクリックします。
「ステータス」が「分析完了」に変われば、EC2インスタンス脆弱性評価は完了です。

スクリーンショット 2016-11-17 10.10.56.png

(7) Amazon InspectorによるEC2インスタンス脆弱性評価結果を確認します。

AWSマネジメントコンソールの「Inspector」->「結果」をクリックします。
EC2インスタンスの脆弱性評価結果を確認出来ます。

「結果」に「No potential security issues found」と表示されていれば、EC2インスタンスの脆弱性評価結果に問題ございません。

スクリーンショット 2016-11-17 10.34.57.png

スクリーンショット 2016-11-17 10.36.45.png

Amazon InspectorによるEC2インスタンス脆弱性評価で問題や推奨事項が検出された場合の対応例

EC2インスタンス脆弱性評価の結果、問題や推奨設定等がある場合は「結果」「説明」「推奨事項」に以下のように表示されます。

以下の例では、EC2インスタンス脆弱性評価の結果、EC2インスタンスの/etc/ssh/sshd_configの 'PermitRootLogin' を 'no' に変更し、sshdを再起動する事で、EC2インスタンスへのrootユーザによるsshログインを禁止するよう推奨されています。

スクリーンショット 2016-11-17 10.42.35.png

「結果」の例
Instance i-XXXXXXXX is configured to allow users to log in with root credentials over SSH. This increases the likelihood of a successful brute-force attack.
「説明」の例
This rule helps determine whether the SSH daemon is configured to permit logging in to your EC2 instance as root.
「推奨事項」
It is recommended that you configure your EC2 instance to prevent root logins over SSH. Instead, log in as a non-root user and use sudo to escalate privileges when necessary. To disable SSH root logins, set PermitRootLogin to "no" in /etc/ssh/sshd_config and restart sshd.

EC2インスタンス(Amazon Linux)の場合、デフォルトではrootユーザによるsshログインは許可されておらず、/etc/ssh/sshd_configの 'PermitRootLogin' は 'forced-commands-only' になっております。

今回の「推奨事項」は対応しなくても、基本的には大丈夫ではありますが、今回は例として、EC2インスタンス脆弱性評価結果に従って、EC2インスタンスの/etc/ssh/sshd_config の 'PermitRootLogin' を 'no' に変更してみます。

まず、/etc/ssh/sshd_configをバックアップします。

[ec2-user@example-server ~]$ sudo cp -p /etc/ssh/sshd_config /etc/ssh/sshd_config.ORG
[ec2-user@example-server ~]$ diff /etc/ssh/sshd_config /etc/ssh/sshd_config.ORG
[ec2-user@example-server ~]$

/etc/ssh/sshd_configの 'PermitRootLogin' を 'forced-commands-only' から 'no' へ変更します。

[ec2-user@example-server ~]$ sudo vi /etc/ssh/sshd_config
PermitRootLogin forced-commands-only
 ↓
PermitRootLogin no
[ec2-user@example-server ~]$ 

/etc/ssh/sshd_configの 'PermitRootLogin' が 'no' に変更された事を確認します。

[ec2-user@example-server ~]$ grep PermitRootLogin /etc/ssh/sshd_config | grep -v ^#
PermitRootLogin no
[ec2-user@example-server ~]$ 

/etc/ssh/sshd_configの変更箇所が 'PermitRootLogin' だけである事を確認します。

[ec2-user@example-server ~]$ diff /etc/ssh/sshd_config /etc/ssh/sshd_config.ORG 
51c51
< PermitRootLogin no
---
> PermitRootLogin forced-commands-only
[ec2-user@example-server ~]$ 

EC2インスタンスのsshdをrestartしてみます。
なお、sshdを再起動する場合、sshログインしている他のセッションが切れますので、sshdのrestartを行なう時はご注意下さい。

[ec2-user@example-server ~]$ sudo /etc/init.d/sshd restart
sshd を停止中:                                             [  OK  ]
sshd を起動中:                                             [  OK  ]
[ec2-user@example-server ~]$ 

sshdが起動している事を確認します。

[ec2-user@example-server ~]$ ps awux | grep -v grep | grep sshd
root      3686  0.0  0.6 117812  6692 ?        Ss   10:44   0:00 sshd: ec2-user [priv]
ec2-user  3688  0.0  0.3 117812  3964 ?        S    10:44   0:00 sshd: ec2-user@pts/0
root      3771  0.0  0.2  77844  2744 ?        Ss   10:48   0:00 /usr/sbin/sshd
[ec2-user@example-server ~]$ 

sshdのrestart後、sshログイン出来る事を確認します。

$ ssh -i EC2インスタンスログイン用のpemファイル ec2-user@EC2インスタンスのIPアドレス
[ec2-user@example-server ~]$ 

rootユーザではEC2インスタンスへsshログイン出来ない事も確認しておきます。

$ ssh -i root@EC2インスタンスのIPアドレス

推奨事項を対応した後で、再度EC2インスタンスの脆弱性評価を行うと、脆弱性評価の「結果」が「No potential security issues found」に変わります。

スクリーンショット 2016-11-17 10.54.33.png


以上になります。

9
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
5