Build your php semi-automated code audit tool

Source: Internet
Author: User
Tags nikic
Build your own php semi-automated code audit tool 0x00 PHP extension for code analysis (dynamic analysis) I. Basic Environment
#!bashapt-get install php5apt-get install php5-devapt-get install apacheapt-get install mysql
II. use PHPTracert
#!bashmkdir godheadwget https://github.com/Qihoo360/phptrace/archive/v0.3.0.zipunzip v0.3.0.zipcd ./phptrace-0.3.0/extensionphpize5./configure --with-php-config=/usr/bin/php-configmake & make installcd ../cmdtoolmake 

Edit php. ini and add:

#!bashextension=trace.so
III. test
#!php
 
CLI
#!shellphp test.php &ps -axu|grep php./phptrace -p pid
Apache
#!bashcurl 127.0.0.1/test.phpps -aux|grep apache./phptrace -p pid
IV. phptrace analysis

The executed code is as follows:

#!php
 

The execution sequence is:

#!basha>b>c>echo

Parameter description:

Name Value Meaning
Seq Int | number of times the function is executed
Type 1/2 1 indicates the function to be called, 2 indicates the function to be returned
Level -10 Execution depth. for example, if function a Calls function B, the level of a is 1, and the level of B is 2.
Func Eval Name of the called function
St 1448387651119460 Timestamp
Params String Function parameters
File C. php Executed file
Lineno 1 The row number corresponding to this function.

Log output:

#!js{"seq":0, "type":1, "level":1, "func":"{main}", "st":1448387651119445, "params":"", "file":"/var/www/html/2.php", "lineno":11 }{"seq":1, "type":1, "level":2, "func":"a", "st":1448387651119451, "params":"", "file":"/var/www/html/2.php", "lineno":11 }{"seq":2, "type":1, "level":3, "func":"b", "st":1448387651119452, "params":"", "file":"/var/www/html/2.php", "lineno":9 }{"seq":3, "type":1, "level":4, "func":"c", "st":1448387651119453, "params":"", "file":"/var/www/html/2.php", "lineno":6 }{"seq":4, "type":2, "level":4, "func":"c, "st":1448387651119457, "return":"NULL", "wt":4, "ct":4, "mem":48, "pmem":144 }{"seq":5, "type":2, "level":3, "func":"b, "st":1448387651119459, "return":"NULL", "wt":7, "ct":6, "mem":48, "pmem":144 }{"seq":6, "type":2, "level":2, "func":"a, "st":1448387651119459, "return":"NULL", "wt":8, "ct":8, "mem":80, "pmem":176 }{"seq":7, "type":2, "level":1, "func":"{main}, "st":1448387651119460, "return":"1", "wt":15, "ct":14, "mem":112, "pmem":208 }
V. Logic Analysis 1. parse monitoring process

Start a background process and refresh the process List. if a process without tracer appears, it is hosted immediately.

2. json extraction

By extracting the json of each file, the extraction process is as follows:

  1. Facilitate all files
  2. Read files
  3. Extract json and sort by seq
  4. Extract the merging of type = 2 and type = 1
  5. Sort the parent-child relationship and store the same dictionary according to the level
  6. Sort by seq and extract the header function for output.
  7. Extract malicious functions to extract level up until level = 0

The function corresponds to the following:

#!pythonlist1={     level1:[seq,type,func,param,return]     level2:[seq,type,func,param,return]     level3:[seq,type,func,param,return] #eval      level4:[seq,type,func,param,return]}list2=
3. View data

Track dangerous functions, sort out the relationships before their functions are executed, and then manually review them.

Put on demo

6. use XDEBUG

Install

#!bashapt-get install php5-xdebug

Modify php. ini

#!bash[xdebug]zend_extension = "/usr/lib/php5/20131226/xdebug.so"xdebug.auto_trace = onxdebug.auto_profile = onxdebug.collect_params = onxdebug.collect_return = onxdebug.profiler_enable = onxdebug.trace_output_dir = "/tmp/ad/xdebug_log"xdebug.profiler_output_dir = "/tmp/ad/xdebug_log"

Put several demo images:

VII. Advantages and disadvantages

Human intervention is very strong, and manual operations cannot be performed independently.

Advantages

High accuracy. you can analyze object-oriented and process-oriented code.

0x01 syntax analysis (static analysis)

Case:

  • Http://php-grinder.com/
  • Http://rips-scanner.sourceforge.net/
I. use php-parser

Introduction:

  • Http://www.oschina.net/p/php-parser
  • Https://github.com/nikic/PHP-Parser/
II. Installation
#!shellgit clone https://github.com/nikic/PHP-Parser.git & cd PHP-Parsercurl -sS https://getcomposer.org/installer | php

PHP >=5.3; for parsing PHP 5.2 to PHP 5.6

#!bashphp composer.phar require nikic/php-parser

PHP >=5.4; for parsing PHP 5.2 to PHP 7.0

#!bashphp composer.phar require nikic/php-parser 2.0.x-dev
III. test
#!php
 ';$parser = (new ParserFactory)->create(ParserFactory::PREFER_PHP7);try {    $stmts = $parser->parse($code);    print_r($stmts);    // $stmts is an array of statement nodes} catch (Error $e) {    echo 'Parse Error: ', $e->getMessage();}

The output is as follows:

#!jsArray(    [0] => PhpParser\Node\Expr\Eval_ Object        (            [expr] => PhpParser\Node\Expr\ArrayDimFetch Object                (                    [var] => PhpParser\Node\Expr\Variable Object                        (                            [name] => _POST                            [attributes:protected] => Array                                (                                    [startLine] => 1                                    [endLine] => 1                                )                        )                    [dim] => PhpParser\Node\Expr\ConstFetch Object                        (                            [name] => PhpParser\Node\Name Object                                (                                    [parts] => Array                                        (                                            [0] => c                                        )                                    [attributes:protected] => Array                                        (                                            [startLine] => 1                                            [endLine] => 1                                        )                                )                            [attributes:protected] => Array                                (                                    [startLine] => 1                                    [endLine] => 1                                )                        )                    [attributes:protected] => Array                        (                            [startLine] => 1                            [endLine] => 1                        )                )            [attributes:protected] => Array                (                    [startLine] => 1                    [endLine] => 1                )        ))

We need to extract

#!js[0] => PhpParser\Node\Expr\Eval_ Object[name] => _POST[parts] => Array                                        (                                            [0] => c                                        )

After splicing, we can find that the original statement is:

#!phpeval($_POST[c][/c])
4. logic analysis code analysis
  1. Use this library for syntax analysis
  2. Extract results
  3. Dangerous function extraction
  4. Extract the variables in the dangerous function
  5. Extract the value assignment method of this variable from the above text
  6. Analyze controllable results
  7. Output result
V. Advantages and disadvantages

The analysis of object-oriented programs is relatively weak.

Advantages

Suitable for automatic analysis in large batches and independent execution without manual operations

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.