Php implements troubleshooting and hardening of Linux server Trojans

Source: Internet
Author: User
This article describes how to use php to troubleshoot and reinforce Linux server Trojans. This article describes how to search for, search for recently modified files, and modify php based on the pattern. ini, modify nginx. conf and other methods. if you need a friend, can you refer to the website frequently infected with Trojans? After some improvements, we can basically solve this problem. because discuz x and other programs have vulnerabilities, they are uploaded to websehll. each time they are deleted for a while, they come out again and finally find all the Trojans.

Find and strengthen the following aspects (if you can not enable the Member function, do not give any Upload entry, protect the background password, and reinforce PHP, it is generally no problem ).

1. search by signature:

Php Trojans generally contain

The code is as follows:


<? Php eval ($ _ POST [cmd]);?>


Or

The code is as follows:


<? Php assert ($ _ POST [cmd]);?>

Find/wwwroot/*-type f-name "*. php" | xargs grep "eval (">/wwwroot/scan.txt

The result shows that many obvious webshells are found to be hidden in directories such as attachment.

2. use a php code on the Internet to search for recently modified files

Scandir. php
The content is as follows:

The code is as follows:


<? Php
Set_time_limit (0); // prevent timeout
/**
*
* Enhanced version of php directory scanning monitoring
*
* @ Author lssbing (lssbing # gmail.com)
* @ Date 2010-1-18
* @ License BSD
* @ Version 1.0
*
The following variables need to be manually set before use
*
**/
/* = ======= */
$ Pass = "12345"; // Set the password
$ Jkdir = ". "; // Set the monitoring scan Directory. the current directory is '. ', the upper-level directory is '.. ', you can also set an absolute path without a slash. the default value is the current directory.
$ Logfilename = "./m. log"; // you can specify the path for storing logs.
$ Exclude = array ('data', 'images'); // exclude a directory
$ Danger = 'eval | cmd | passthru | gzuncompress '; // you can specify a function to identify a trojan file.
$ Suffix = 'php | Inc'; // you can specify the suffix of the file to be scanned.
/* = ======= */

$ Filename = $ _ GET ['filename'];
$ Check = $ _ GET ['check'];
$ Jumpoff = false;
$ Url = $ _ SERVER ['php _ SELF '];
$ Thisfile = end (explode ('/', $ url ));
$ Jump = "{$ thisfile} |". implode ('|', $ exclude );
$ Jkdir_num = $ file_num = $ danger_num = 0;
Define ('m _ path', $ jkdir );
Define ('m _ log', $ logfilename );
If ($ check = 'check ')
{
$ Safearr = explode ("|", $ jump );
$ Start_time = microtime (true );
Safe_check ($ jkdir );
$ End_time = microtime (true );
$ Total = $ end_time-$ start_time;
$ File_num = $ file_num-$ jkdir_num;
$ Message = "number of files:". $ file_num;
$ Message. = "number of folders:". $ jkdir_num;
$ Message. = "number of suspicious files:". $ danger_num;
$ Message. = "Execution time:". $ total;
Echo $ message;
} Else {
If ($ _ GET ['M'] = "del") Delete (); // process file deletion
// Read the file content
If (isset ($ _ GET ['readfile']) {
// View the password. the file content is output after the password is verified correctly.
If (emptyempty ($ _ POST ['passchack']) {
Echo ""
."";
Exit;
} Elseif (isset ($ _ POST ['passchack']) & $ _ POST ['passchack'] ==$ pass ){
$ Code = file_get_contents ($ _ GET ['readfile']);
Echo"{$ Code}";
Exit;
} Else {
Exit;
}

} Else {
Record_md5 (M_PATH );
If (file_exists (M_LOG )){
$ Log = unserialize (file_get_contents (M_LOG ));
} Else {
$ Log = array ();
}

If ($ _ GET ['savethis '] = 1 ){
// Save the md5 value of the current file to the log file
@ Unlink (M_LOG );
File_put_contents (M_LOG, serialize ($ file_list ));
Echo "Saved! Click to return ";
Exit;
}
If (emptyempty ($ log )){
Echo "no log file has been created currently! Click [save current] to create a log file! ";
} Else {
If ($ file_list = $ log ){
Echo "this folder has not been changed! ";
} Else {
If (count ($ file_list)> 0 ){
Foreach ($ file_list as $ file => $ md5 ){
If (! Isset ($ log [$ file]) {
Echo "New File :". $ file. "". "created :". date ("Y-m-d H: I: s", filectime ($ file )). "Modification time :". date ("Y-m-d H: I: s", filemtime ($ file )). "Source Code deletion
";
} Else {
If ($ log [$ file]! = $ Md5 ){
Echo "modify File :". $ file. "". "created :". date ("Y-m-d H: I: s", filectime ($ file )). "Modification time :". date ("Y-m-d H: I: s", filemtime ($ file )). "Source Code
";

Unset ($ log [$ file]);
} Else {
Unset ($ log [$ file]);
}
}
}
}
If (count ($ log)> 0 ){
Foreach ($ log as $ file => $ md5 ){
Echo "delete file:". $ file ."
";
}
}
}
}
}
}

// Calculate md5
Function record_md5 ($ jkdir ){
Global $ file_list, $ exclude;
If (is_dir ($ jkdir )){
$ File = scandir ($ jkdir );
Foreach ($ file as $ f ){
If ($ f! = '.' & $ F! = '..'&&! In_array ($ f, $ exclude )){
$ Path = $ jkdir. '/'. $ f;
If (is_dir ($ path )){
Record_md5 ($ path );
} Else {
$ File_list [$ path] = md5_file ($ path );
}
}
}
}
}

Function Safe_Check ($ jkdir) // traverses a file
{
Global $ danger, $ suffix, $ jkdir_num, $ file_num, $ danger_num;

$ Hand = @ dir ($ jkdir) or die ('folder does not exist ');
While ($ file = $ hand-> read ())
{
$ Filename = $ jkdir. '/'. $ file;
If (! $ Jumpoff ){
If (Jump ($ filename) continue;
}
If (@ is_dir ($ filename) & $ file! = '.' & $ File! = '..' & $ File! = './..')
{$ Jkdir_num ++;
Safe_Check ($ filename );
}
If (preg_match_all ("/\. ($ suffix)/I", $ filename, $ out ))
{

$ Str = '';
$ Fp = @ fopen ($ filename, 'r') or die ('No authorization ');
While (! Feof ($ fp ))
{
$ Str. = fgets ($ fp, 1024 );
}
Fclose ($ fp );
If (preg_match_all ("/($ danger) [\ r \ n \ t] {0,} ([\ [\ (])/I", $ str, $ out ))
{
Echo "suspicious file: {$ filename }". "created :". date ("Y-m-d H: I: s", filectime ($ filename )). "Modification time :". date ("Y-m-d H: I: s", filemtime ($ filename ))."View codeDelete
";
$ Danger_num ++;
}
}
$ File_num ++;
}
}
Function Edit () // view suspicious files
{
Global $ filename;
$ Filename = str_replace ("..", "", $ filename );
$ File = $ filename;
$ Content = "";
If (is_file ($ file ))
{
$ Fp = fopen ($ file, "r") or die ('No authorization ');
$ Content = fread ($ fp, filesize ($ file ));
Fclose ($ fp );
$ Content = htmlspecialchars ($ content );

}
Echo"$ Content\ R \ n ";
Exit ();
}
Function Delete () // Delete an object
{Global $ filename, $ pass;
If (emptyempty ($ _ POST ['passchack']) {
Echo ""
."";
Exit;
} Elseif (isset ($ _ POST ['passchack']) & $ _ POST ['passchack'] ==$ pass ){
(Is_file ($ filename ))? ($ Mes = unlink ($ filename )? 'Deleted successfully': 'failed to delete View authorization '):'';
Echo $ mes;
Exit ();
} Else {
Echo 'incorrect password! ';
Exit;
}
}
Function Jump ($ file) // skip the file
{
Global $ jump, $ safearr;
If ($ jump! = '')
{
Foreach ($ safearr as $ v)
{
If ($ v = '') continue;
If (eregi ($ v, $ file) return true;
}
}
Return false;
}
?>
[View file changes] | [save the current file fingerprint] | [scan suspicious files]

After the execution, you can see the recently modified file, which is of great value.

3. modify php. ini to restrict the following functions:

The code is as follows:


Disable_functions = phpinfo, passthru, exec, system, chroot, chgrp, chown, shell_exec, proc_open, primary, ini_alter, ini_alter, primary, dl, pfsockopen, openlog, syslog, readlink, symlink, popepassthru, stream_socket_server, fsocke, popen, proc_close, curl_exec, curl_multi_exec, parse_ini_file, show_source, dl, escapeshellarg, escapeshellcmd

4. modify nginx. conf to restrict the execution of PHP files in some directories.

The code is as follows:


Server
{
Listen 80;
Server_name www. ****. com;
Index index.htm index.html index. php;
Root/wwwroot /;



Rewrite ^ ([^ \.] *)/topic-(. +) \. html $1/portal. php? Mod = topic & topic = $2 last;
Rewrite ^ ([^ \.] *)/article-([0-9] +)-([0-9] + )\. html $1/portal. php? Mod = view & aid = $2 & page = $3 last;
Rewrite ^ ([^ \.] *)/forum-(\ w +)-([0-9] +) \. html $1/forum. php? Mod = forumdisplay & fid = $2 & page = $3 last;
Rewrite ^ ([^ \.] *)/thread-([0-9] +)-([0-9] +)-([0-9] + )\. html $1/forum. php? Mod = viewthread & tid = $2 & extra = page % 3D $4 & page = $3 last;
Rewrite ^ ([^ \.] *)/group-([0-9] +)-([0-9] + )\. html $1/forum. php? Mod = group & fid = $2 & page = $3 last;
Rewrite ^ ([^ \.] *)/space-(username | uid)-(. +) \. html $1/home. php? Mod = space & $2 = $3 last;
Rewrite ^ ([^ \.] *)/([a-z] +)-(. +) \. html $1/$ 2.php? Rewrite = $3 last;
Rewrite ^ ([^ \.] *)/topic-(. +) \. html $1/portal. php? Mod = topic & topic = $2 last;


Location ~ ^/Images/. * \. (php | php5) $
{
Deny all;
}

Location ~ ^/Static/. * \. (php | php5) $
{
Deny all;
}

Location ~ * ^/Data/(attachment | avatar)/. * \. (php | php5) $
{
Deny all;
}

Location ~ . * \. (Php | php5 )? $
{
Fastcgi_pass 127.0.0.1: 9000;
Fastcgi_index index. php;
Fcinclude GI. conf;
}



Error_page 400/404 .html;
Error_page 403/404 .html;
Error_page 404/404 .html;
Error_page 405/404 .html;
Error_page 408/404 .html;
Error_page 410/404 .html;
Error_page 411/404 .html;
Error_page 412/404 .html;
Error_page 413/404 .html;
Error_page 414/404 .html;
Error_page 415/404 .html;
Error_page 500/404 .html;
Error_page 501/404 .html;
Error_page 502/404 .html;
Error_page 503/404 .html;
Error_page 506/404 .html;


Log_format acclog "$ remote_addr $ request_time $ http_x_readtime [$ time_local] \" $ request_method http: // $ host $ request_uri \ "$ status $ body_bytes_sent \" $ http_referer \ "\" $ http_user_agent \"";
Access_log/logs/access. log acclog;
}

Note that

The code is as follows:


Location ~ ^/Images/. * \. (php | php5) $
{
Deny all;
}

Restrictions on these directories must be written in

The code is as follows:


Location ~ . * \. (Php | php5 )? $
{
Fastcgi_pass 127.0.0.1: 9000;
Fastcgi_index index. php;
Fcinclude GI. conf;
}

.

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.