[Windows版] Amazon Inspector をプロキシ経由で使用してみた

Amazon Inspectorをプロキシ経由で使用する方法をまとめてみました。
2021.09.14

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

プロキシ経由でAmazon Inspectorを使いたい

こんにちは、のんピ(@non____97)です。

皆さんはAmazon Inspectorは使っていますか? 私は使っています。

Amazon Inspectorは、OSにAmazon Inspectorエージェントをインストールして使用するサービスで、EC2インスタンス内の脆弱性診断サービスを選定する際に、まず候補として出てきます。

今回、プロキシ経由でAmazon Inspectorを使いたい要件に遭遇することがあったので、Amazon Inspector をプロキシ経由で使用する方法をまとめます。

いきなりまとめ

  • インターネットにアクセスする経路及び、S3のVPCエンドポイントが存在しない場合、SSM Run CommandでAmazon Inspectorエージェントをインストールしようとするとインストールに失敗する
  • Amazon InspectorエージェントはWinHTTPプロキシを参照する
  • Amazon Inspectorエージェントにプロキシを経由させるかは、レジストリで設定する
  • Amazon Inspectorエージェントのプロキシ設定を反映させるためには、サービスの再起動が必要

検証の環境

検証の環境は以下の通りです。

構成図

プロキシサーバー用のSquidをインストールしたEC2インスタンスをPublicサブネットに、Amazon InspectorエージェントをインストールしたEC2インスタンスはPrivateサブネットに配置します。

また、SSMセッションマネージャーで各OSの操作をしたいので、SSM用のエンドポイントをPrivateサブネットに配置しています。

VPCとEC2インスタンスのデプロイ

まず、VPCとEC2インスタンスをAWS CDKでデプロイします。

AWS CDKの実行環境のディレクトリの構成は以下の通りです。

> tree   
.
├── .gitignore
├── .npmignore
├── README.md
├── bin
│   └── app.ts
├── cdk.json
├── jest.config.js
├── lib
│   └── app-stack.ts
├── package-lock.json
├── package.json
├── test
│   └── app.test.ts
└── tsconfig.json

3 directories, 11 files

メインで動かすのは./lib/app-stack.tsです。ここで全てのリソースを作成しています。

./lib/app-stack.tsの大まかな処理の流れは以下の通りです。

  • SSM用のIAMロールの作成
  • VPCの作成
  • SSM用のVPCエンドポイントの作成
    • com.amazonaws.region.ssm
    • com.amazonaws.region.ec2messages
    • com.amazonaws.region.ssmmessages
    • com.amazonaws.region.s3
  • セキュリティグループの作成
  • Squidをインストールするプロキシサーバー用のEC2インスタンスの作成
  • Amazon InspectorエージェントをインストールするEC2インスタンスの作成

実際のコードは以下の通りです。

./lib/app-stack.ts

import * as cdk from "@aws-cdk/core";
import * as ec2 from "@aws-cdk/aws-ec2";
import * as iam from "@aws-cdk/aws-iam";

export class AppStack extends cdk.Stack {
  constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    // Create SSM IAM role
    const ssmIamRole = new iam.Role(this, "SsmIamRole", {
      assumedBy: new iam.ServicePrincipal("ec2.amazonaws.com"),
      managedPolicies: [
        iam.ManagedPolicy.fromAwsManagedPolicyName(
          "AmazonSSMManagedInstanceCore"
        ),
      ],
    });

    // Create a VPC
    const vpc = new ec2.Vpc(this, "Vpc", {
      cidr: "10.0.0.0/24",
      enableDnsHostnames: true,
      enableDnsSupport: true,
      maxAzs: 1,
      natGateways: 0,
      subnetConfiguration: [
        {
          name: "Public",
          subnetType: ec2.SubnetType.PUBLIC,
          cidrMask: 27,
        },
        {
          name: "Isolated",
          subnetType: ec2.SubnetType.PRIVATE_ISOLATED,
          cidrMask: 27,
        },
      ],
    });

    // Create SSM Privatelink
    new ec2.InterfaceVpcEndpoint(this, "SsmVpcEndpoint", {
      vpc: vpc,
      service: ec2.InterfaceVpcEndpointAwsService.SSM,
      subnets: vpc.selectSubnets({ subnetGroupName: "Isolated" }),
    });

    // Create SSM MESSAGES Privatelink
    new ec2.InterfaceVpcEndpoint(this, "SsmMessagesVpcEndpoint", {
      vpc: vpc,
      service: ec2.InterfaceVpcEndpointAwsService.SSM_MESSAGES,
      subnets: vpc.selectSubnets({ subnetGroupName: "Isolated" }),
    });

    // Create EC2 MESSAGES Privatelink
    new ec2.InterfaceVpcEndpoint(this, "Ec2MessagesVpcEndpoint", {
      vpc: vpc,
      service: ec2.InterfaceVpcEndpointAwsService.EC2_MESSAGES,
      subnets: vpc.selectSubnets({ subnetGroupName: "Isolated" }),
    });

    // // Create S3 Gateway
    new ec2.GatewayVpcEndpoint(this, "S3GatewayVpcEndpoint", {
      vpc: vpc,
      service: ec2.GatewayVpcEndpointAwsService.S3,
    });

    // Create Security Group
    const vpcSg = new ec2.SecurityGroup(this, "VpcSg", {
      allowAllOutbound: true,
      vpc: vpc,
    });
    vpcSg.addIngressRule(ec2.Peer.ipv4("10.0.0.0/16"), ec2.Port.allTraffic());

    // Create EC2 instance
    new ec2.Instance(this, `ProxyEc2Instance`, {
      machineImage: ec2.MachineImage.latestAmazonLinux({
        generation: ec2.AmazonLinuxGeneration.AMAZON_LINUX_2,
      }),
      instanceType: new ec2.InstanceType("t3.micro"),
      vpc: vpc,
      vpcSubnets: vpc.selectSubnets({
        subnetGroupName: "Public",
      }),
      securityGroup: vpcSg,
      role: ssmIamRole,
    });

    new ec2.Instance(this, `InspectorEc2Instance`, {
      machineImage: ec2.MachineImage.latestWindows(
        ec2.WindowsVersion.WINDOWS_SERVER_2019_JAPANESE_FULL_BASE
      ),
      instanceType: new ec2.InstanceType("t3.micro"),
      vpc: vpc,
      vpcSubnets: vpc.selectSubnets({
        subnetGroupName: "Isolated",
      }),
      securityGroup: vpcSg,
      role: ssmIamRole,
    });
  }
}

あとは、cdk deployを実行することで、各種リソースがデプロイされます。

Squidのインストールと設定

SSMセッションマネージャーで、プロキシサーバー用のEC2インスタンスにログインして、Squidをインストールします。

実際の操作ログは以下の通りです。

# squidのインストール
$ sudo yum install squid
Loaded plugins: extras_suggestions, langpacks, priorities, update-motd
Resolving Dependencies
--> Running transaction check
---> Package squid.x86_64 7:3.5.20-17.amzn2.6.1 will be installed
--> Processing Dependency: squid-migration-script for package: 7:squid-3.5.20-17.amzn2.6.1.x86_64
--> Processing Dependency: perl(Digest::MD5) for package: 7:squid-3.5.20-17.amzn2.6.1.x86_64
--> Processing Dependency: perl(Data::Dumper) for package: 7:squid-3.5.20-17.amzn2.6.1.x86_64
--> Processing Dependency: perl(DBI) for package: 7:squid-3.5.20-17.amzn2.6.1.x86_64
--> Processing Dependency: libltdl.so.7()(64bit) for package: 7:squid-3.5.20-17.amzn2.6.1.x86_64
--> Processing Dependency: libecap.so.3()(64bit) for package: 7:squid-3.5.20-17.amzn2.6.1.x86_64
--> Running transaction check
---> Package libecap.x86_64 0:1.0.0-1.amzn2.0.2 will be installed
---> Package libtool-ltdl.x86_64 0:2.4.2-22.2.amzn2.0.2 will be installed
---> Package perl-DBI.x86_64 0:1.627-4.amzn2.0.2 will be installed
--> Processing Dependency: perl(RPC::PlServer) >= 0.2001 for package: perl-DBI-1.627-4.amzn2.0.2.x86_64
--> Processing Dependency: perl(RPC::PlClient) >= 0.2000 for package: perl-DBI-1.627-4.amzn2.0.2.x86_64
---> Package perl-Data-Dumper.x86_64 0:2.145-3.amzn2.0.2 will be installed
---> Package perl-Digest-MD5.x86_64 0:2.52-3.amzn2.0.2 will be installed
--> Processing Dependency: perl(Digest::base) >= 1.00 for package: perl-Digest-MD5-2.52-3.amzn2.0.2.x86_64
---> Package squid-migration-script.x86_64 7:3.5.20-17.amzn2.6.1 will be installed
--> Running transaction check
---> Package perl-Digest.noarch 0:1.17-245.amzn2 will be installed
---> Package perl-PlRPC.noarch 0:0.2020-14.amzn2 will be installed
--> Processing Dependency: perl(Net::Daemon) >= 0.13 for package: perl-PlRPC-0.2020-14.amzn2.noarch
--> Processing Dependency: perl(Net::Daemon::Test) for package: perl-PlRPC-0.2020-14.amzn2.noarch
--> Processing Dependency: perl(Net::Daemon::Log) for package: perl-PlRPC-0.2020-14.amzn2.noarch
--> Processing Dependency: perl(Compress::Zlib) for package: perl-PlRPC-0.2020-14.amzn2.noarch
--> Running transaction check
---> Package perl-IO-Compress.noarch 0:2.061-2.amzn2 will be installed
--> Processing Dependency: perl(Compress::Raw::Zlib) >= 2.061 for package: perl-IO-Compress-2.061-2.amzn2.noarch
--> Processing Dependency: perl(Compress::Raw::Bzip2) >= 2.061 for package: perl-IO-Compress-2.061-2.amzn2.noarch
---> Package perl-Net-Daemon.noarch 0:0.48-5.amzn2 will be installed
--> Running transaction check
---> Package perl-Compress-Raw-Bzip2.x86_64 0:2.061-3.amzn2.0.2 will be installed
---> Package perl-Compress-Raw-Zlib.x86_64 1:2.061-4.amzn2.0.2 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

================================================================================================================================================================================================
 Package                                               Arch                                 Version                                              Repository                                Size
================================================================================================================================================================================================
Installing:
 squid                                                 x86_64                               7:3.5.20-17.amzn2.6.1                                amzn2-core                               3.1 M
Installing for dependencies:
 libecap                                               x86_64                               1.0.0-1.amzn2.0.2                                    amzn2-core                                21 k
 libtool-ltdl                                          x86_64                               2.4.2-22.2.amzn2.0.2                                 amzn2-core                                49 k
 perl-Compress-Raw-Bzip2                               x86_64                               2.061-3.amzn2.0.2                                    amzn2-core                                32 k
 perl-Compress-Raw-Zlib                                x86_64                               1:2.061-4.amzn2.0.2                                  amzn2-core                                58 k
 perl-DBI                                              x86_64                               1.627-4.amzn2.0.2                                    amzn2-core                               804 k
 perl-Data-Dumper                                      x86_64                               2.145-3.amzn2.0.2                                    amzn2-core                                48 k
 perl-Digest                                           noarch                               1.17-245.amzn2                                       amzn2-core                                23 k
 perl-Digest-MD5                                       x86_64                               2.52-3.amzn2.0.2                                     amzn2-core                                30 k
 perl-IO-Compress                                      noarch                               2.061-2.amzn2                                        amzn2-core                               260 k
 perl-Net-Daemon                                       noarch                               0.48-5.amzn2                                         amzn2-core                                51 k
 perl-PlRPC                                            noarch                               0.2020-14.amzn2                                      amzn2-core                                36 k
 squid-migration-script                                x86_64                               7:3.5.20-17.amzn2.6.1                                amzn2-core                                51 k

Transaction Summary
================================================================================================================================================================================================
Install  1 Package (+12 Dependent packages)

Total download size: 4.6 M
Installed size: 14 M
Is this ok [y/d/N]:y  
Downloading packages:
(1/13): libecap-1.0.0-1.amzn2.0.2.x86_64.rpm                                                                                                                             |  21 kB  00:00:00     
(2/13): libtool-ltdl-2.4.2-22.2.amzn2.0.2.x86_64.rpm                                                                                                                     |  49 kB  00:00:00     
(3/13): perl-Compress-Raw-Bzip2-2.061-3.amzn2.0.2.x86_64.rpm                                                                                                             |  32 kB  00:00:00     
(4/13): perl-Compress-Raw-Zlib-2.061-4.amzn2.0.2.x86_64.rpm                                                                                                              |  58 kB  00:00:00     
(5/13): perl-DBI-1.627-4.amzn2.0.2.x86_64.rpm                                                                                                                            | 804 kB  00:00:00     
(6/13): perl-Data-Dumper-2.145-3.amzn2.0.2.x86_64.rpm                                                                                                                    |  48 kB  00:00:00     
(7/13): perl-Digest-1.17-245.amzn2.noarch.rpm                                                                                                                            |  23 kB  00:00:00     
(8/13): perl-Digest-MD5-2.52-3.amzn2.0.2.x86_64.rpm                                                                                                                      |  30 kB  00:00:00     
(9/13): perl-Net-Daemon-0.48-5.amzn2.noarch.rpm                                                                                                                          |  51 kB  00:00:00     
(10/13): perl-IO-Compress-2.061-2.amzn2.noarch.rpm                                                                                                                       | 260 kB  00:00:00     
(11/13): perl-PlRPC-0.2020-14.amzn2.noarch.rpm                                                                                                                           |  36 kB  00:00:00     
(12/13): squid-migration-script-3.5.20-17.amzn2.6.1.x86_64.rpm                                                                                                           |  51 kB  00:00:00     
(13/13): squid-3.5.20-17.amzn2.6.1.x86_64.rpm                                                                                                                            | 3.1 MB  00:00:00     
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Total                                                                                                                                                            11 MB/s | 4.6 MB  00:00:00     
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : perl-Data-Dumper-2.145-3.amzn2.0.2.x86_64                                                                                                                                   1/13 
  Installing : perl-Digest-1.17-245.amzn2.noarch                                                                                                                                           2/13 
  Installing : perl-Digest-MD5-2.52-3.amzn2.0.2.x86_64                                                                                                                                     3/13 
  Installing : 7:squid-migration-script-3.5.20-17.amzn2.6.1.x86_64                                                                                                                         4/13 
  Installing : perl-Compress-Raw-Bzip2-2.061-3.amzn2.0.2.x86_64                                                                                                                            5/13 
  Installing : libecap-1.0.0-1.amzn2.0.2.x86_64                                                                                                                                            6/13 
  Installing : libtool-ltdl-2.4.2-22.2.amzn2.0.2.x86_64                                                                                                                                    7/13 
  Installing : perl-Net-Daemon-0.48-5.amzn2.noarch                                                                                                                                         8/13 
  Installing : 1:perl-Compress-Raw-Zlib-2.061-4.amzn2.0.2.x86_64                                                                                                                           9/13 
  Installing : perl-IO-Compress-2.061-2.amzn2.noarch                                                                                                                                      10/13 
  Installing : perl-PlRPC-0.2020-14.amzn2.noarch                                                                                                                                          11/13 
  Installing : perl-DBI-1.627-4.amzn2.0.2.x86_64                                                                                                                                          12/13 
  Installing : 7:squid-3.5.20-17.amzn2.6.1.x86_64                                                                                                                                         13/13 
  Verifying  : 1:perl-Compress-Raw-Zlib-2.061-4.amzn2.0.2.x86_64                                                                                                                           1/13 
  Verifying  : perl-IO-Compress-2.061-2.amzn2.noarch                                                                                                                                       2/13 
  Verifying  : perl-Net-Daemon-0.48-5.amzn2.noarch                                                                                                                                         3/13 
  Verifying  : perl-Digest-MD5-2.52-3.amzn2.0.2.x86_64                                                                                                                                     4/13 
  Verifying  : 7:squid-3.5.20-17.amzn2.6.1.x86_64                                                                                                                                          5/13 
  Verifying  : libtool-ltdl-2.4.2-22.2.amzn2.0.2.x86_64                                                                                                                                    6/13 
  Verifying  : perl-PlRPC-0.2020-14.amzn2.noarch                                                                                                                                           7/13 
  Verifying  : libecap-1.0.0-1.amzn2.0.2.x86_64                                                                                                                                            8/13 
  Verifying  : perl-Compress-Raw-Bzip2-2.061-3.amzn2.0.2.x86_64                                                                                                                            9/13 
  Verifying  : 7:squid-migration-script-3.5.20-17.amzn2.6.1.x86_64                                                                                                                        10/13 
  Verifying  : perl-Digest-1.17-245.amzn2.noarch                                                                                                                                          11/13 
  Verifying  : perl-DBI-1.627-4.amzn2.0.2.x86_64                                                                                                                                          12/13 
  Verifying  : perl-Data-Dumper-2.145-3.amzn2.0.2.x86_64                                                                                                                                  13/13 

Installed:
  squid.x86_64 7:3.5.20-17.amzn2.6.1                                                                                                                                                            

Dependency Installed:
  libecap.x86_64 0:1.0.0-1.amzn2.0.2       libtool-ltdl.x86_64 0:2.4.2-22.2.amzn2.0.2   perl-Compress-Raw-Bzip2.x86_64 0:2.061-3.amzn2.0.2  perl-Compress-Raw-Zlib.x86_64 1:2.061-4.amzn2.0.2   
  perl-DBI.x86_64 0:1.627-4.amzn2.0.2      perl-Data-Dumper.x86_64 0:2.145-3.amzn2.0.2  perl-Digest.noarch 0:1.17-245.amzn2                 perl-Digest-MD5.x86_64 0:2.52-3.amzn2.0.2           
  perl-IO-Compress.noarch 0:2.061-2.amzn2  perl-Net-Daemon.noarch 0:0.48-5.amzn2        perl-PlRPC.noarch 0:0.2020-14.amzn2                 squid-migration-script.x86_64 7:3.5.20-17.amzn2.6.1 

Complete!


# Squidのバージョンの確認
$ squid -v
Squid Cache: Version 3.5.20
Service Name: squid
configure options:  '--build=x86_64-koji-linux-gnu' '--host=x86_64-koji-linux-gnu' '--program-prefix=' '--prefix=/usr' '--exec-prefix=/usr' '--bindir=/usr/bin' '--sbindir=/usr/sbin' '--sysconfdir=/etc' '--datadir=/usr/share' '--includedir=/usr/include' '--libdir=/usr/lib64' '--libexecdir=/usr/libexec' '--sharedstatedir=/var/lib' '--mandir=/usr/share/man' '--infodir=/usr/share/info' '--disable-strict-error-checking' '--exec_prefix=/usr' '--libexecdir=/usr/lib64/squid' '--localstatedir=/var' '--datadir=/usr/share/squid' '--sysconfdir=/etc/squid' '--with-logdir=$(localstatedir)/log/squid' '--with-pidfile=$(localstatedir)/run/squid.pid' '--disable-dependency-tracking' '--enable-eui' '--enable-follow-x-forwarded-for' '--enable-auth' '--enable-auth-basic=DB,LDAP,MSNT-multi-domain,NCSA,NIS,PAM,POP3,RADIUS,SASL,SMB,SMB_LM,getpwnam' '--enable-auth-ntlm=smb_lm,fake' '--enable-auth-digest=file,LDAP,eDirectory' '--enable-auth-negotiate=kerberos' '--enable-external-acl-helpers=file_userip,LDAP_group,time_quota,session,unix_group,wbinfo_group,kerberos_ldap_group' '--enable-cache-digests' '--enable-cachemgr-hostname=localhost' '--enable-delay-pools' '--enable-epoll' '--enable-ident-lookups' '--enable-linux-netfilter' '--enable-removal-policies=heap,lru' '--enable-snmp' '--enable-ssl-crtd' '--enable-storeio=aufs,diskd,rock,ufs' '--enable-wccpv2' '--enable-esi' '--enable-ecap' '--with-aio' '--with-default-user=squid' '--with-dl' '--with-openssl' '--with-pthreads' '--disable-arch-native' 'build_alias=x86_64-koji-linux-gnu' 'host_alias=x86_64-koji-linux-gnu' 'CFLAGS=-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches    -m64 -mtune=generic -fpie' 'LDFLAGS=-Wl,-z,relro  -pie -Wl,-z,relro -Wl,-z,now' 'CXXFLAGS=-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches    -m64 -mtune=generic -fpie' 'PKG_CONFIG_PATH=:/usr/lib64/pkgconfig:/usr/share/pkgconfig'


# SquidがIPv4で、8080ポートでLISTENするように設定を変更
$ sudo cp -a /etc/squid/squid.conf /etc/squid/squid.conf.`date +"%Y%m%d"`
$ sudo vi /etc/squid/squid.conf
$ sudo diff -u /etc/squid/squid.conf.`date +"%Y%m%d"` /etc/squid/squid.conf
--- /etc/squid/squid.conf.20210913      2021-04-12 18:39:25.000000000 +0000
+++ /etc/squid/squid.conf       2021-09-13 06:48:08.321541104 +0000
@@ -56,7 +56,7 @@
 http_access deny all
 
 # Squid normally listens to port 3128
-http_port 3128
+http_port 0.0.0.0:8080
 
 # Uncomment and adjust the following to add a disk cache directory.
 #cache_dir ufs /var/spool/squid 100 16 256


# Squidの設定ファイルの表示
$ sudo cat /etc/squid/squid.conf
#
# Recommended minimum configuration:
#

# Example rule allowing access from your local networks.
# Adapt to list your (internal) IP networks from where browsing
# should be allowed
acl localnet src 10.0.0.0/8     # RFC1918 possible internal network
acl localnet src 172.16.0.0/12  # RFC1918 possible internal network
acl localnet src 192.168.0.0/16 # RFC1918 possible internal network
acl localnet src fc00::/7       # RFC 4193 local private network range
acl localnet src fe80::/10      # RFC 4291 link-local (directly plugged) machines

acl SSL_ports port 443
acl Safe_ports port 80          # http
acl Safe_ports port 21          # ftp
acl Safe_ports port 443         # https
acl Safe_ports port 70          # gopher
acl Safe_ports port 210         # wais
acl Safe_ports port 1025-65535  # unregistered ports
acl Safe_ports port 280         # http-mgmt
acl Safe_ports port 488         # gss-http
acl Safe_ports port 591         # filemaker
acl Safe_ports port 777         # multiling http
acl CONNECT method CONNECT

#
# Recommended minimum Access Permission configuration:
#
# Deny requests to certain unsafe ports
http_access deny !Safe_ports

# Deny CONNECT to other than secure SSL ports
http_access deny CONNECT !SSL_ports

# Only allow cachemgr access from localhost
http_access allow localhost manager
http_access deny manager

# We strongly recommend the following be uncommented to protect innocent
# web applications running on the proxy server who think the only
# one who can access services on "localhost" is a local user
#http_access deny to_localhost

#
# INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS
#

# Example rule allowing access from your local networks.
# Adapt localnet in the ACL section to list your (internal) IP networks
# from where browsing should be allowed
http_access allow localnet
http_access allow localhost

# And finally deny all other access to this proxy
http_access deny all

# Squid normally listens to port 3128
http_port 0.0.0.0:8080

# Uncomment and adjust the following to add a disk cache directory.
#cache_dir ufs /var/spool/squid 100 16 256

# Leave coredumps in the first cache dir
coredump_dir /var/spool/squid

#
# Add any of your own refresh_pattern entries above these.
#
refresh_pattern ^ftp:           1440    20%     10080
refresh_pattern ^gopher:        1440    0%      1440
refresh_pattern -i (/cgi-bin/|\?) 0     0%      0
refresh_pattern .               0       20%     4320


# Squidの自動起動の有効化
$ sudo systemctl enable squid
Created symlink from /etc/systemd/system/multi-user.target.wants/squid.service to /usr/lib/systemd/system/squid.service.


# Squidの起動
$ sudo systemctl start squid 
$ systemctl status squid
● squid.service - Squid caching proxy
   Loaded: loaded (/usr/lib/systemd/system/squid.service; enabled; vendor preset: disabled)
   Active: active (running) since Mon 2021-09-13 05:36:53 UTC; 16s ago
  Process: 2575 ExecStart=/usr/sbin/squid $SQUID_OPTS -f $SQUID_CONF (code=exited, status=0/SUCCESS)
  Process: 2569 ExecStartPre=/usr/libexec/squid/cache_swap.sh (code=exited, status=0/SUCCESS)
 Main PID: 2577 (squid)
   CGroup: /system.slice/squid.service
           ├─2577 /usr/sbin/squid -f /etc/squid/squid.conf
           ├─2579 (squid-1) -f /etc/squid/squid.conf
           └─2583 (logfile-daemon) /var/log/squid/access.log


# SquidがIPv4、8080ポートでLISTENしているか確認
$ sudo lsof -i:8080
COMMAND   PID  USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
squid   32101 squid   11u  IPv4  56218      0t0  TCP *:webcache (LISTEN)

SquidがIPv4、8080ポートでLISTENしていることを確認できたので、プロキシサーバーの準備は完了です。

Amazon Inspectorエージェントのインストール

Amazon InspectorエージェントのインストールはSSM Run Commandを使用して行います。

SSM Run Commandにて、AmazonInspector-ManageAWSAgentのコマンドドキュメントを選択します。続いて、インストール先のEC2インスタンスを選択します。その他のパラメーターはデフォルトで、実行をクリックします。

Amazon Inspectorエージェントのインストール 1

Amazon Inspectorエージェントのインストール 2

インストールが完了すると、ステップ名InstallInspectorOnWindowsのステータスが成功になり、OutputにもInstallation succeededと表示されていることが分かります。

Amazon Inspectorエージェントのインストールの確認

ちなみに、S3のVPCエンドポイントがない状態で、SSM Run Commandを使ってAmazon Inspectorエージェントをインストールしようとすると、Error while downloading installerとエージェントのインストールファイルがダウンロードできず、失敗します。

Amazon Inspectorエージェントのインストールの失敗

Amazon Inspectorエージェントのプロキシの設定

Amazon Inspectorエージェントのプロキシの設定をします。

AWS公式ドキュメントによると、Amazon Inspectorエージェントがプロキシをサポートしているのは1.0.0.59以降とのことです。そのため、インストールされたAmazon Inspectorエージェントのバージョンを確認します。

インストールされたAmazon Inspectorエージェントのバージョンの確認は、SSMセッションマネージャーでOSにログインして、C:/Program Files/Amazon Web Services/AWS Agent配下のAWSAgentStatus.exeを実行して確認します。

実際の操作ログは以下の通りです。

> cd "C:/Program Files/Amazon Web Services/AWS Agent"
> .\AWSAgentStatus.exe
Configuration file path : C:\ProgramData\Amazon Web Services\AWS Agent\agent.cfg
Configuration status :
Proxy In Use: false
Agent version : 1.0.264.0
System release : Windows Server 2019 x64 - 10.0.17763
Daemon : true
Max queue size : 157286400
Log File :
Msgs log max size : 33554432
Groups : false
Users : false
CodeModules : false
InstanceMetaData : false
PackageInfo : false
NetworkInterfaces : false
Terminals : false
ConfigurationInfo : false
Permissions : false
KernelModules : false
Oval : false
OpenPorts : false
PasswordPolicy : false
System performance : false
System performance update frequency : 0
System performance send frequency : 0
Process performance : false
Process performance update frequency : 0
Process performance send frequency : 0
Kernel module status : KernelModuleNotFound
Network connections : false
Listening ports : false
Code modules : false
Processes : false
Publisher type : Service
Registered : false
Endpoint :
Instance-Id : i-09ee167ae5bc26e80
Region : us-east-1
IpAddress : 10.0.0.60
MacAddress : 0e:2b:ba:d1:8c:2d
IpAddress : fe80::f49c:70f:64fc:4c08
MacAddress : 0e:2b:ba:d1:8c:2d
IpAddress : 127.0.0.1
MacAddress : 00:00:00:00:00:00
IpAddress : ::1
MacAddress : 00:00:00:00:00:00
Total events published : 0
Events published in last call : 0
Last registration attempt date : Tue 2021-09-14 01:26:39 協定世界時
Registration failure reason : Network connectivity failure: Encountered network error when sending http request
Config retrieval failure reason : Agent failed to register during config retrieval
Assessment ARN : <not provided by Inspector service>
---------- Messages statistic ---------
Enable  601:User, Count:0 (sent:0)
Enable  602:Group, Count:0 (sent:0)
Enable  603:PackageInfo, Count:0 (sent:0)
Enable  604:CodeModule, Count:0 (sent:0)
Disable 605:KernelModule, Count:0 (sent:0)
Enable  606:ProcessDuplicationStat, Count:0 (sent:0)
Enable  607:LoadImageInProcessStat, Count:0 (sent:0)
Disable 608:ProcessCloseStat, Count:0 (sent:0)
Enable  609:CreateProcess, Count:0 (sent:0)
Disable 610:DuplicateProcess, Count:0 (sent:0)
Enable  611:StopProcess, Count:0 (sent:0)
Enable  612:LoadImageInProcess, Count:0 (sent:0)
Enable  613:DynamicallyLoadedCodeModule, Count:0 (sent:0)
Disable 614:DNSEntry, Count:0 (sent:0)
Disable 615:NetworkInterface, Count:0 (sent:0)
Enable  616:TcpV4ListeningPort, Count:0 (sent:0)
Enable  617:TcpV6ListeningPort, Count:0 (sent:0)
Enable  618:UdpV4ListeningPort, Count:0 (sent:0)
Enable  619:UdpV6ListeningPort, Count:0 (sent:0)
Enable  620:ListeningPortInfo, Count:0 (sent:0)
Enable  621:TcpV4Connection, Count:0 (sent:0)
Enable  622:TcpV6Connection, Count:0 (sent:0)
Disable 623:InstanceMetaData, Count:0 (sent:0)
Disable 624:InboundTcpConnectionStat, Count:0 (sent:0)
Disable 625:OutboundTcpConnectionStat, Count:0 (sent:0)
Enable  626:AgentMsgStats, Count:0 (sent:0)
Enable  627:OperatingSystem, Count:0 (sent:0)
Enable  628:SplitMsgBegin, Count:0 (sent:0)
Enable  629:SplitMsgEnd, Count:0 (sent:0)
Enable  630:MonitoringStart, Count:0 (sent:0)
Enable  631:MonitoringEnd, Count:0 (sent:0)
Enable  632:Terminal, Count:0 (sent:0)
Enable  635:ConfigurationInfo, Count:0 (sent:0)
Disable 636:TcpV4ListeningPortClosure, Count:0 (sent:0)
Disable 637:TcpV6ListeningPortClosure, Count:0 (sent:0)
Disable 638:UdpV4ListeningPortClosure, Count:0 (sent:0)
Disable 639:UdpV6ListeningPortClosure, Count:0 (sent:0)
Disable 645:SystemPerformance, Count:0 (sent:0)
Disable 646:ProcessPerformance, Count:0 (sent:0)
Enable  647:TimeEvent, Count:0 (sent:0)
Disable 648:FileInfo, Count:0 (sent:0)
Enable  649:DirectoryInfo, Count:0 (sent:0)
Enable  650:Oval, Count:0 (sent:0)
Enable  651:Error, Count:0 (sent:0)
Disable 652:PasswordPolicy, Count:0 (sent:0)
Enable  653:RetrieverCompletionStatus, Count:0 (sent:0)
Enable  654:ProbeResultMsg, Count:0 (sent:0)
Enable  655:EventSubscriberStatusMsg, Count:0 (sent:0)
Enable  656:OpenPortsMsg, Count:0 (sent:0)
Enable  657:ProbeInfoMsg, Count:0 (sent:0)
Enable  658:OvalCVE, Count:0 (sent:0)
Enable  659:OvalCIS, Count:0 (sent:0)
------------------------
Dur Since last config load sec: 151
All Messages count: 0
All Messages size:  0
Messages successfully sent:0
Health Message: Count:0, Seconds from agent start: First:0 Last:0

インストールされたバージョンは1.0.264.0なので、プロキシの設定ができそうですね。

続いて、Amazon InspectorエージェントはWinHTTPプロキシの設定を参照するので、WinHTTPプロキシを設定します。

設定は以下の通り、SSMセッションマネージャーから実行しました。

# 現在のWinHTTPプロキシの設定確認
> netsh winhttp show proxy

現在の WinHTTP プロキシ設定:

    直接アクセス (プロキシ サーバーなし)。

# WinHTTPプロキシの設定
# プロキシサーバー用のEC2インスタンス(IPアドレス: 10.0.0.26)を指定する 
# インスタンスメタデータのIPアドレス(169.254.169.254)のバイパス設定も行う
> netsh winhttp set proxy proxy-server="10.0.0.26:8080" bypass-list="169.254.169.254"

現在の WinHTTP プロキシ設定:

    プロキシ サーバー:  10.0.0.26:8080
    バイパス一覧     : (なし)

最後に、Amazon InspectorエージェントがWinHTTPプロキシを参照するように設定します。

設定は以下の通り、SSMセッションマネージャーから実行しました。

# Amazon Inspectorエージェントのプロキシ設定用のレジストリキーを指定
> $RegPath = "HKLM:\SOFTWARE\Amazon Web Services\AWS Agent Updater"
> $RegKey = "UseProxy"
> $RegKeyType = "DWord"
> $RegKeyValue = 1

# レジストリの追加
> New-ItemProperty $RegPath -name $RegKey -PropertyType $RegKeyType -Value $RegKeyValue -Force


UseProxy     : 1
PSPath       : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Amazon Web Services\AWS Agent Updater
PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Amazon Web Services
PSChildName  : AWS Agent Updater
PSDrive      : HKLM
PSProvider   : Microsoft.PowerShell.Core\Registry


# サービスを再起動して、プロキシの設定を反映
> Restart-Service -Name "AWS Agent Service"
警告: サービス 'AWS Agent Service (AWSAgent)' の停止を待っています...
警告: サービス 'AWS Agent Service (AWSAgent)' の停止を待っています...
警告: サービス 'AWS Agent Service (AWSAgent)' の停止を待っています...
> Restart-Service -Name "AWS Agent Updater Service"

# サービス再起動後のエージェントの状態の確認
> .\AWSAgentStatus.exe
Configuration file path : C:\ProgramData\Amazon Web Services\AWS Agent\agent.cfg
Configuration status :
Proxy host: 10.0.0.26
Proxy port: 8080
System HTTPS Proxy Setting: 10.0.0.26:8080
System Bypass Proxy Setting:
Proxy status: HTTPS Proxy config parsed successfully
Proxy In Use: true
Agent version : 1.0.264.0
System release : Windows Server 2019 x64 - 10.0.17763
Daemon : true
Max queue size : 157286400
Log File :
Msgs log max size : 33554432
Groups : false
Users : false
CodeModules : false
InstanceMetaData : false
PackageInfo : false
NetworkInterfaces : false
Terminals : false
ConfigurationInfo : false
Permissions : false
KernelModules : false
Oval : false
OpenPorts : false
PasswordPolicy : false
System performance : false
System performance update frequency : 0
System performance send frequency : 0
Process performance : false
Process performance update frequency : 0
Process performance send frequency : 0
Kernel module status : KernelModuleNotFound
Network connections : false
Listening ports : false
Code modules : false
Processes : false
Publisher type : Service
Registered : true
Endpoint :
Instance-Id : i-09ee167ae5bc26e80
Region : us-east-1
IpAddress : 10.0.0.60
MacAddress : 0e:2b:ba:d1:8c:2d
IpAddress : fe80::f49c:70f:64fc:4c08
MacAddress : 0e:2b:ba:d1:8c:2d
IpAddress : 127.0.0.1
MacAddress : 00:00:00:00:00:00
IpAddress : ::1
MacAddress : 00:00:00:00:00:00
Total events published : 0
Events published in last call : 0
AgentId : i-09ee167ae5bc26e80
Collecting : false
Last registration attempt date : Tue 2021-09-14 01:28:45 協定世界時
Last registration date : Tue 2021-09-14 01:28:45 協定世界時
Last config retrieval attempt date : Tue 2021-09-14 01:28:50 協定世界時
Last config retrieval date : Tue 2021-09-14 01:28:50 協定世界時
Assessment ARN : <not provided by Inspector service>
---------- Messages statistic ---------
Enable  601:User, Count:0 (sent:0)
Enable  602:Group, Count:0 (sent:0)
Enable  603:PackageInfo, Count:0 (sent:0)
Enable  604:CodeModule, Count:0 (sent:0)
Disable 605:KernelModule, Count:0 (sent:0)
Enable  606:ProcessDuplicationStat, Count:0 (sent:0)
Enable  607:LoadImageInProcessStat, Count:0 (sent:0)
Disable 608:ProcessCloseStat, Count:0 (sent:0)
Enable  609:CreateProcess, Count:0 (sent:0)
Disable 610:DuplicateProcess, Count:0 (sent:0)
Enable  611:StopProcess, Count:0 (sent:0)
Enable  612:LoadImageInProcess, Count:0 (sent:0)
Enable  613:DynamicallyLoadedCodeModule, Count:0 (sent:0)
Disable 614:DNSEntry, Count:0 (sent:0)
Disable 615:NetworkInterface, Count:0 (sent:0)
Enable  616:TcpV4ListeningPort, Count:0 (sent:0)
Enable  617:TcpV6ListeningPort, Count:0 (sent:0)
Enable  618:UdpV4ListeningPort, Count:0 (sent:0)
Enable  619:UdpV6ListeningPort, Count:0 (sent:0)
Enable  620:ListeningPortInfo, Count:0 (sent:0)
Enable  621:TcpV4Connection, Count:0 (sent:0)
Enable  622:TcpV6Connection, Count:0 (sent:0)
Disable 623:InstanceMetaData, Count:0 (sent:0)
Disable 624:InboundTcpConnectionStat, Count:0 (sent:0)
Disable 625:OutboundTcpConnectionStat, Count:0 (sent:0)
Enable  626:AgentMsgStats, Count:0 (sent:0)
Enable  627:OperatingSystem, Count:0 (sent:0)
Enable  628:SplitMsgBegin, Count:0 (sent:0)
Enable  629:SplitMsgEnd, Count:0 (sent:0)
Enable  630:MonitoringStart, Count:0 (sent:0)
Enable  631:MonitoringEnd, Count:0 (sent:0)
Enable  632:Terminal, Count:0 (sent:0)
Enable  635:ConfigurationInfo, Count:0 (sent:0)
Disable 636:TcpV4ListeningPortClosure, Count:0 (sent:0)
Disable 637:TcpV6ListeningPortClosure, Count:0 (sent:0)
Disable 638:UdpV4ListeningPortClosure, Count:0 (sent:0)
Disable 639:UdpV6ListeningPortClosure, Count:0 (sent:0)
Disable 645:SystemPerformance, Count:0 (sent:0)
Disable 646:ProcessPerformance, Count:0 (sent:0)
Enable  647:TimeEvent, Count:0 (sent:0)
Disable 648:FileInfo, Count:0 (sent:0)
Enable  649:DirectoryInfo, Count:0 (sent:0)
Enable  650:Oval, Count:0 (sent:0)
Enable  651:Error, Count:0 (sent:0)
Disable 652:PasswordPolicy, Count:0 (sent:0)
Enable  653:RetrieverCompletionStatus, Count:0 (sent:0)
Enable  654:ProbeResultMsg, Count:0 (sent:0)
Enable  655:EventSubscriberStatusMsg, Count:0 (sent:0)
Enable  656:OpenPortsMsg, Count:0 (sent:0)
Enable  657:ProbeInfoMsg, Count:0 (sent:0)
Enable  658:OvalCVE, Count:0 (sent:0)
Enable  659:OvalCIS, Count:0 (sent:0)
------------------------
Dur Since last config load sec: 11
All Messages count: 2
All Messages size:  0
Messages successfully sent:0
Health Message: Count:2, Seconds from agent start: First:1 Last:6
 {"t":1631582930294,"proxy":0,"o":"Windows Server 2019 x64","k":"10.0.17763","s":0,"d":0,"l":0,"m":0}

プロキシの設定追加後に.\AWSAgentStatus.exeを実行した結果、Proxy status: HTTPS Proxy config parsed successfullyとあることから、Amazon Inspectorエージェントはプロキシを認識していることが確認できます。

Amazon Inspectorの実行

それでは、本当にAmazon Inspectorエージェントはプロキシを経由して通信できているかを確認します。

Amazon Inspectorコンソールを開き、評価ターゲットを作成します。

Amazon Inspector評価ターゲット

Amazon InspectorエージェントをインストールしたEC2インスタンスが評価対象になるように、Nameタグを使って評価ターゲットを作成します。

Amazon Inspector評価ターゲットをの作成画面

評価ターゲット作成後、Preview Targetをクリックすると、Amazon InspectorエージェントをインストールしたEC2インスタンスのステータスがHEALTHYになっていることが確認できます。どうやら正しくプロキシを経由して通信できていそうですね。

Amazon Inspectorの評価ターゲットの確認

Amazon InspectorのPreview Targetの確認

続いて、評価テンプレートを作成及び、実行をします。

Amazon Inspector 評価テンプレートの作成

先ほど作成した評価ターゲットに対して、Amazon Inspectorで提供されている全てのルールパッケージで評価します。また、結果をすぐに知りたいので、所要時間は15分で設定しました。各種設定が完了したら作成及び、実行をクリックします。

Amazon Inspector 評価テンプレートの作成及び、実行

しばらく待つと、ステータスが分析完了になり、4つ検知項目があったことが分かります。

Amazon Inspector 評価の実行確認

結果を確認すると、確かに4件検知されていることが確認できます。

Amazon Inspector 評価の確認

SSM Run Commandを使って一気にプロキシの設定することも可能

Amazon Inspectorをプロキシ経由で使用する方法をまとめてみました。

今回は、SSMセッションマネージャーでWinHTTPプロキシやレジストリの設定、サービスの再起動を行いましたが、いずれもSSM Run Commandで実行できます。

そのため、大量のEC2インスタンスに対して、プロキシの設定を行いたい場合は、SSM Run Command経由で実行すると、非常に簡単に設定が完了すると思われます。

この記事が誰かの助けになれば幸いです。

以上、AWS事業本部 コンサルティング部の のんピ(@non____97)でした!