脆弱性診断につかえるツール集

# 概要

自宅サーバのセキュリティチェックをして見た。

# 脆弱性診断ツール

## nikto

niktoは、Web アプリケーションセキュリティスキャナー。

```bash
$ sudo apt install nikto -y
$ nikto -h localhost
- Nikto v2.1.5
---------------------------------------------------------------------------
+ Target IP:          127.0.0.1
+ Target Hostname:    localhost
+ Target Port:        80
+ Start Time:         2019-08-23 22:26:00 (GMT9)
---------------------------------------------------------------------------
+ Server: nginx/1.17.1
+ The anti-clickjacking X-Frame-Options header is not present.
+ No CGI Directories found (use '-C all' to force check all possible dirs)
+ 6544 items checked: 0 error(s) and 1 item(s) reported on remote host
+ End Time:           2019-08-23 22:26:08 (GMT9) (8 seconds)
---------------------------------------------------------------------------
+ 1 host(s) tested
```


**参考サイト**

- [脆弱性スキャナー Nikto](https://qiita.com/bezeklik/items/12643654dc0c45f4eb29)

## OpenVAS (GVM)

OpenVASは汎用的な脆弱性診断ツール。
現在は、OpenVASではなくGVM (Greenbone Security Assistant) という名前に変わっている。

Ubuntuへのインストールは以下の流れ。

### インストール

まずPPAを追加してインストール。

```bash:OpenVASのインストール
sudo add-apt-repository ppa:mrazavi/gvm
sudo apt install gvm
```

### 脆弱性データベース更新

次に、脆弱性データベースを更新する。

```bash:OpenVASの脆弱性データベース更新
sudo greenbone-nvt-sync
sudo greenbone-scapdata-sync
sudo greenbone-certdata-sync
```

### OpenVAS起動確認

次にOpenVASのサービスが起動していることを確認する。

```bash:OpenVASの起動確認
systemctl status gvmd
systemctl status openvas-scanner
systemctl status gsad
```

### OpenVAS実行

最後にOpenVASの画面 https://localhost:4000 にログインする。
ユーザ名とパスワードは以下の通り。

- ユーザ名: admin
- パスワード: admin

Scans > Tasks > Task Wizard > Start Scan で脆弱性スキャンのタスク作成
![task_2.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/114392/a00268b9-0e50-3cf2-0de5-efb5a841376d.png)

Scans > Results でスキャン結果を確認
![result.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/114392/93e92daf-4e0f-872b-6ee4-6475e4bdc5bb.png)

**参考サイト**

- [脆弱性スキャナー OpenVAS](https://qiita.com/bezeklik/items/a64cad37eb03a1db2de4)

## vuls

### ログ出力先ディレクトリ作成

```bash:ディレクトリ作成
cd /path/to/working/dir
mkdir go-cve-dictionary-log goval-dictionary-log gost-log
```

### データベース作成

ネット上から脆弱性情報をかき集めて、脆弱性データベースを作成する。

ここでは、NVD(米国の脆弱性情報)、JVN(日本の脆弱性情報)、OVAL、exploitdbをつかう。

```bash:NVDダウンロード
for i in `seq 2002 $(date +"%Y")`; do \
  docker run --rm -it \
    -v $PWD:/vuls \
    -v $PWD/go-cve-dictionary-log:/var/log/vuls \
    vuls/go-cve-dictionary fetchnvd -years $i; \
done
```

```bash:JVNダウンロード
for i in `seq 2002 $(date +"%Y")`; do \
  docker run --rm -it \
    -v $PWD:/vuls \
    -v $PWD/go-cve-dictionary-log:/var/log/vuls \
    vuls/go-cve-dictionary fetchjvn -years $i; \
done
```

```bash:OVALダウンロード
docker run --rm -it \
    -v $PWD:/vuls \
    -v $PWD/goval-dictionary-log:/var/log/vuls \
    vuls/goval-dictionary fetch-ubuntu 12 14 16 18 19
```

```bash:exploitdbダウンロード
docker run --rm -it \
  -v $PWD:/vuls \
  -v $PWD/go-exploitdb-log:/var/log/vuls \
  princechrismc/go-exploitdb fetch exploitdb
```

### SSH接続設定

Dockerコンテナからホストマシンをスキャンする場合、コンテナからホストへSSH接続する必要がある。

```bash:SSH鍵生成と登録
ssh-keygen -t rsa
ssh-copy-id your_server_ip
```

### 設定ファイル作成

設定ファイルを作成する。

ここでは、スキャンに使う脆弱性データベース `cveDict` とスキャン対象のサーバ情報 `servers.localhost` を設定している。

```toml:config.toml
[servers]

[servers.localhost]
host               = "your_server_ip"
port               = "22"
user               = "your_user"
keyPath            = "/root/.ssh/id_rsa"

[cveDict]
type = "sqlite3"
SQLite3Path = "/vuls/cve.sqlite3"

[ovalDict]
type = "sqlite3"
SQLite3Path = "/vuls/oval.sqlite3"

[exploit]
type = "sqlite3"
SQLite3Path = "/vuls/go-exploitdb.sqlite3"
```

### 設定ファイルのテスト

設定ファイルのテストを行う。エラーが出なければOK。

```bash:設定ファイルのテスト
docker run --rm -it\
    -v ~/.ssh:/root/.ssh:ro \
    -v $PWD:/vuls \
    -v $PWD/vuls-log:/var/log/vuls \
    vuls/vuls configtest \
    -config=./config.toml
```

```bash:実行結果
[Aug 25 14:40:17]  INFO [localhost] Validating config...
[Aug 25 14:40:17]  INFO [localhost] Detecting Server/Container OS... 
[Aug 25 14:40:17]  INFO [localhost] Detecting OS of servers... 
[Aug 25 14:40:18]  INFO [localhost] (1/1) Detected: localhost: ubuntu 18.04
[Aug 25 14:40:18]  INFO [localhost] Detecting OS of static containers... 
[Aug 25 14:40:18]  INFO [localhost] Detecting OS of containers... 
[Aug 25 14:40:18]  INFO [localhost] Checking Scan Modes...
[Aug 25 14:40:18]  INFO [localhost] Checking dependencies...
[Aug 25 14:40:18]  INFO [localhost] Dependencies... Pass
[Aug 25 14:40:18]  INFO [localhost] Checking sudo settings...
[Aug 25 14:40:18]  INFO [localhost] sudo ... No need
[Aug 25 14:40:18]  INFO [localhost] It can be scanned with fast scan mode even if warn or err messages are displayed due to lack of dependent packages or sudo settings in fast-root or deep scan mode
[Aug 25 14:40:18]  INFO [localhost] Scannable servers are below...
localhost 
```

### スキャン

脆弱性のスキャンを実行する。

```bash:スキャン実行
docker run --rm -it \
    -v ~/.ssh:/root/.ssh:ro \
    -v $PWD:/vuls \
    -v $PWD/vuls-log:/var/log/vuls \
    -v /etc/localtime:/etc/localtime:ro \
    -v /etc/timezone:/etc/timezone:ro \
    vuls/vuls scan \
    -config=./config.toml
```

```bash:実行結果
[Aug 25 23:37:34]  INFO [localhost] Start scanning
[Aug 25 23:37:34]  INFO [localhost] config: ./config.toml
[Aug 25 23:37:34]  INFO [localhost] Validating config...
[Aug 25 23:37:34]  INFO [localhost] Detecting Server/Container OS... 
[Aug 25 23:37:34]  INFO [localhost] Detecting OS of servers... 
[Aug 25 23:37:35]  INFO [localhost] (1/1) Detected: your_server_name: ubuntu 18.04
[Aug 25 23:37:35]  INFO [localhost] Detecting OS of static containers... 
[Aug 25 23:37:35]  INFO [localhost] Detecting OS of containers... 
[Aug 25 23:37:35]  INFO [localhost] Checking Scan Modes... 
[Aug 25 23:37:35]  INFO [localhost] Detecting Platforms... 
[Aug 25 23:37:36]  INFO [localhost] (1/1) your_server_name is running on other
[Aug 25 23:37:36]  INFO [localhost] Detecting IPS identifiers... 
[Aug 25 23:37:36]  INFO [localhost] (1/1) your_server_name has 0 IPS integration
[Aug 25 23:37:36]  INFO [localhost] Scanning vulnerabilities... 
[Aug 25 23:37:36]  INFO [localhost] Scanning vulnerable OS packages...
[Aug 25 23:37:36]  INFO [your_server_name] Scanning in fast mode


One Line Summary
================
your_server_name	ubuntu18.04	2316 installed





To view the detail, vuls tui is useful.
To send a report, run vuls report -h.
```

### レポート確認

脆弱性をレポートで確認する。

```bash:レポート確認
docker run --rm -it \
    -v ~/.ssh:/root/.ssh:ro \
    -v $PWD:/vuls \
    -v $PWD/vuls-log:/var/log/vuls \
    -v /etc/localtime:/etc/localtime:ro \
    vuls/vuls report \
    -format-list \
    -config=./config.toml
```

```bash:実行結果
[Aug 26 00:13:24]  INFO [localhost] Validating config...
[Aug 26 00:13:24]  INFO [localhost] Loaded: /vuls/results/2019-08-26T00:13:11+09:00
[Aug 26 00:13:24]  INFO [localhost] Validating db config...
INFO[0000] -cvedb-type: sqlite3, -cvedb-url: , -cvedb-path: /vuls/cve.sqlite3 
INFO[0000] -ovaldb-type: sqlite3, -ovaldb-url: , -ovaldb-path: /vuls/oval.sqlite3 
INFO[0000] -gostdb-type: sqlite3, -gostdb-url: , -gostdb-path: /vuls/gost.sqlite3 
INFO[0000] -exploitdb-type: sqlite3, -exploitdb-url: , -exploitdb-path: /vuls/go-exploitdb.sqlite3 
[Aug 26 00:13:24]  WARN [localhost] --gostdb-path=/vuls/gost.sqlite3 is not found. If the scan target server is Debian, RHEL or CentOS, it's recommended to use gost to improve scanning accuracy. To use gost database, see https://github.com/knqyf263/gost#fetch-redhat
INFO[08-26|00:13:24] Opening Database.                        db=sqlite3
INFO[08-26|00:13:24] Migrating DB.                            db=sqlite3
[Aug 26 00:13:24]  INFO [localhost] localhost: 0 CVEs are detected with Library
[Aug 26 00:13:24]  INFO [localhost] OVAL is fresh: ubuntu 18.04 
[Aug 26 00:13:25]  INFO [localhost] localhost: 378 CVEs are detected with OVAL
[Aug 26 00:13:25]  INFO [localhost] localhost: 0 CVEs are detected with CPE
[Aug 26 00:13:25]  INFO [localhost] localhost: 0 CVEs are detected with GitHub Security Alerts
[Aug 26 00:13:25]  INFO [localhost] localhost: 0 unfixed CVEs are detected with gost
[Aug 26 00:13:25]  INFO [localhost] Fill CVE detailed information with CVE-DB
[Aug 26 00:13:26]  INFO [localhost] Fill exploit information with Exploit-DB
[Aug 26 00:13:26]  INFO [localhost] localhost: 6 exploits are detected
[Aug 26 00:13:26]  INFO [localhost] localhost: en: 0, ja: 0 alerts are detected
localhost (ubuntu18.04)
=======================
Total: 378 (High:63 Medium:290 Low:25 ?:0), 0/378 Fixed, 2317 installed, 6 exploits, en: 0, ja: 0 alerts

+------------------+---------+------+------+----+------+---------------------------------------------------+
|      CVE-ID      |  FIXED  | CERT | CVSS | AV | POC  |                        NVD                        |
+------------------+---------+------+------+----+------+---------------------------------------------------+
| CVE-yyyy-nnnn    | unfixed |      | 10.0 |  L |      | https://nvd.nist.gov/vuln/detail/CVE-yyyy-nnnn    |
etc...
+------------------+---------+------+------+----+------+---------------------------------------------------+
```

あらやだ、いっぱい出てきた。

### TUI起動

TUI (Terminal User Interface) は、ターミナルでレポートを閲覧するツール。

```bash:TUI起動
docker run --rm -it \
    -v ~/.ssh:/root/.ssh:ro \
    -v $PWD:/vuls \
    -v $PWD/vuls-log:/var/log/vuls \
    -v /etc/localtime:/etc/localtime:ro \
    vuls/vuls tui \
    -config=./config.toml
```

実行結果

![tui.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/114392/4d0be9fd-5a6c-ee5f-a1fc-1c362a3f9d5a.png)

### VulsRepo起動

レポートをWeb UI上で閲覧するツールVulsRepoを起動する。

```bash:VulsRepo起動
docker run -dt \
    -v $PWD:/vuls \
    -p 5111:5111 \
    vuls/vulsrepo
```

**参考サイト**

- [脆弱性診断ツールVulsをDockerで運用する](https://qiita.com/ohhara_shiojiri/items/a1157472446b9847b863)
- [Tutorial - Scan using Docker](https://vuls.io/docs/ja/tutorial-docker.html)

# ツール

脆弱性診断ツールではないが、診断に活用できるツール。

## nmap

nmapは、ポートスキャンツール。

```bash
$ sudo apt install nmap -y
$ nmap localhost

Starting Nmap 7.60 ( https://nmap.org ) at 2019-08-23 22:21 JST
Nmap scan report for localhost (127.0.0.1)
Host is up (0.000090s latency).
Not shown: 994 closed ports
PORT      STATE SERVICE
22/tcp    open  ssh
80/tcp    open  http
111/tcp   open  rpcbind
443/tcp   open  https
631/tcp   open  ipp
10082/tcp open  amandaidx

Nmap done: 1 IP address (1 host up) scanned in 0.04 seconds
```

[一般的なポート](http://web.mit.edu/rhel-doc/4/RH-DOCS/rhel-sg-ja-4/ch-ports.html) と比較するに、妥当なポートだけオープンにしているので、OK。

**参考サイト**

- [ポートスキャンツールnmapについて](https://qiita.com/SotaAtos/items/29b10a875b0371518d3c)

## lsof

lsofは、ポート番号からポートを使っているプログラムを逆引きするツール。

```bash
$ lsof -i:TO_PORT
COMMAND   PID    USER   FD   TYPE   DEVICE SIZE/OFF NODE NAME
chrome  XXXXXX ???????   XXX  IPv6 XXXXXXXX      XXX  TCP ip6-localhost:XXXXX->ip6-localhost:TO_PORT (ESTABLISHED)
```

**参考サイト**

- [開いているファイルのプロセスを特定（lsofコマンド）](https://qiita.com/yusabana/items/fd03ee4c90a0d1e0a8c6)

## iftop

iftopは、通信の状況をCUIで確認できるコマンド。

```bash
$ sudo iftop

                12.5Kb           25.0Kb          37.5Kb           50.0Kb     62.5Kb
└───────────────┴────────────────┴───────────────┴────────────────┴────────────────
your_server_name            => _gateway                        0b   1.63Kb  1.77Kb
                            <=                                 0b   2.56Kb  2.46Kb
255.255.255.255             => xxx.xxx.xxx.xxx                 0b      0b      0b
                            <=                                 0b    518b    324b
```

**参考サイト**

- [iftopコマンドの使い方](https://qiita.com/hana_shin/items/bbf8e2f705d0237874b3)

# Dockerイメージ診断ツール

Dockerイメージ用の脆弱性診断ツール。

<!--

 Dockle

https://qiita.com/tomoyamachi/items/8e042e4269427bb3b326

 Clair

https://kazuhira-r.hatenablog.com/entry/2019/01/12/224956

https://github.com/quay/clair/blob/master/Documentation/running-clair.md

![](https://cloud.githubusercontent.com/assets/343539/21630809/c1adfbd2-d202-11e6-9dfe-9024139d0a28.png)


```shell
$ curl -L https://raw.githubusercontent.com/coreos/clair/master/docker-compose.yaml.sample -o $PWD/docker-compose.yaml
$ mkdir $PWD/clair_config
$ curl -L https://raw.githubusercontent.com/coreos/clair/master/config.yaml.sample -o $PWD/clair_config/config.yaml
$ docker-compose -f docker-compose.yaml up -d
```

```shell
$ wget https://github.com/arminc/clair-scanner/releases/download/v12/clair-scanner_linux_amd64 -O clair-scanner
$ chmod a+x clair-scanner
$ ./clair-scanner 
Error: incorrect usage

Usage: clair-scanner [OPTIONS] IMAGE

Scan local Docker images for vulnerabilities with Clair

Arguments:
  IMAGE=""     Name of the Docker image to scan

Options:
  -w, --whitelist=""                    Path to the whitelist file
  -t, --threshold="Unknown"             CVE severity threshold. Valid values; 'Defcon1', 'Critical', 'High', 'Medium', 'Low', 'Negligible', 'Unknown'
  -c, --clair="http://127.0.0.1:6060"   Clair URL
  --ip="localhost"                      IP address where clair-scanner is running on
  -l, --log=""                          Log to a file
  --all, --reportAll=true               Display all vulnerabilities, even if they are approved
  -r, --report=""                       Report output file, as JSON
  --exit-when-no-features=false         Exit with status code 5 when no features are found for a particular image
```

```shell
$ ./clair-scanner -c http://127.0.0.1:6060/ --ip=localhost nginx:1.17.4
```

エラーの嵐。
-->

## trivy

コンテナ内のOSとアプリの依存関係の脆弱性を検出できるツール。対応OSとアプリは以下の通り。

- OS packages
    - Alpine
    - Red Hat Universal Base Image
    - Red Hat Enterprise Linux
    - CentOS
    - Oracle Linux
    - Debian
    - Ubuntu
    - Amazon Linux
    - openSUSE Leap
    - SUSE Enterprise Linux
    - Photon OS
    - Distroless
- Application dependencies
    - Bundler
    - Composer
    - Pipenv
    - Poetry
    - npm
    - yarn
    - Cargo

以下のCIとも連携しやすい。

- Travis CI
- CircleCI
- Jenkins

```shell:実行例
$ docker run --rm -v /var/run/docker.sock:/var/run/docker.sock \
    -v $(pwd)/caches:/root/.cache/ aquasec/trivy nginx:1.17.4

2020-06-07T08:45:39.480Z	INFO	Detecting Debian vulnerabilities...

nginx:1.17.4 (debian 10.1)
==========================
Total: 144 (UNKNOWN: 0, LOW: 102, MEDIUM: 37, HIGH: 5, CRITICAL: 0)

+-----------------+---------------------+----------+------------------------+---------------------------+----------------------------------------+
|     LIBRARY     |  VULNERABILITY ID   | SEVERITY |   INSTALLED VERSION    |       FIXED VERSION       |                 TITLE                  |
+-----------------+---------------------+----------+------------------------+---------------------------+----------------------------------------+
| apt             | CVE-2020-3810       | MEDIUM   | 1.8.2                  | 1.8.2.1                   | Missing input validation in            |
|                 |                     |          |                        |                           | the ar/tar implementations of          |
...
|                 | TEMP-0290435-0B57B5 |          |                        |                           |                                        |
+-----------------+---------------------+----------+------------------------+---------------------------+----------------------------------------+
```


参考サイト

- https://github.com/aquasecurity/trivy#docker
- https://qiita.com/knqyf263/items/dc179f9223fc31b5a51c

## docker-bench-security

[docker-bench-security](https://github.com/docker/docker-bench-security) は、Docker 公式のセキュリティ診断ツールである。 [CISベンチマーク](https://learn.cisecurity.org/benchmarks) にインスパイアされて作成したツールとのこと。

```shell:実行例
$ docker run -it --net host --pid host --userns host --cap-add audit_control \
    -e DOCKER_CONTENT_TRUST=$DOCKER_CONTENT_TRUST \
    -v /etc:/etc:ro \
    -v /lib/systemd/system:/lib/systemd/system:ro \
    -v /usr/bin/containerd:/usr/bin/containerd:ro \
    -v /usr/bin/runc:/usr/bin/runc:ro \
    -v /usr/lib/systemd:/usr/lib/systemd:ro \
    -v /var/lib:/var/lib:ro \
    -v /var/run/docker.sock:/var/run/docker.sock:ro \
    --label docker_bench_security \
    docker/docker-bench-security
# ------------------------------------------------------------------------------
# Docker Bench for Security v1.3.4
#
# Docker, Inc. (c) 2015-
#
# Checks for dozens of common best-practices around deploying Docker containers in production.
# Inspired by the CIS Docker Community Edition Benchmark v1.1.0.
# ------------------------------------------------------------------------------

Initializing Sun Jun  7 08:41:59 UTC 2020


[INFO] 1 - Host Configuration
...
[INFO] Checks: 105
[INFO] Score: 11
```


参考: [Docker 公式のセキュリティ診断ツール「Docker Bench for Security」を試した](https://kakakakakku.hatenablog.com/entry/2019/01/21/080009)