PHP Code Audit

Source: Internet
Author: User
Tags html comment md5 encryption session id php file upload phpinfo readfile
The document did last year, supposedly should be updated, not well written, some did not write the whole, referring to a lot of documents.

Say Owasp Codereview, also should out 2.0.

The cows were passing by, giving some advice.

Directory

1. Overview 3

2. Input verification and output display 3

2.1 Command Injection 4
2.2 Cross-Site Scripting 4
2.3 file contains 5
2.4 Code Injection 5
2.5 SQL Injection 6
2.6 XPath Injection 6
2.7 HTTP response Split 6

2.8 File Management 6
2.9 File uploads 7
2.10 Variable override 7
2.11 Dynamic Functions 7

3. Session Security 8

3.1 HttpOnly Settings 8
3.2 Domain Settings 8
3.3 Path Setting 8
3.4 Cookies Duration 8
3.5 Secure Settings 8
3.6 Session Fixed 9
3.7 CSRF 9

4. Encryption 9

4.1 PlainText Storage Password 9
4.2 Weak password Encryption 9
4.3 Password stored in the attacker can access the file 9

5. Certifications and authorizations 10

5.1 User authentication 10
5.2 Unauthenticated call to function or file 10
5.3 Password hard-coded 10

6. Random function 10

6.1 rand () 10
6.2 Mt_srand () and Mt_rand () 11

7. Special characters and multibyte encodings 11

7.1 Multi-byte encoding 11

8. PHP Dangerous function 11

8.1 Buffer Overflow 11
8.2 Session_destroy () Delete File Vulnerability 12
8.3 unset ()-zend_hash_del_key_or_index Vulnerability 12

9. Information Disclosure 13

9.1 Phpinfo 13

PHP Environment 13

10.1 Open_basedir Settings 13
10.2 Allow_url_fopen Settings 13
10.3 Allow_url_include Settings 13
10.4 Safe_mode_exec_dir Settings 14
10.5 MAGIC_QUOTE_GPC Settings 14
10.6 register_globals Settings 14
10.7 Safe_mode Settings 14
10.8 Session_use_trans_sid Settings 14
10.9 display_errors Settings 14
10.10 expose_php Settings 14

1. Overview

Code auditing is the work of systematically checking application source code. It is designed to find and fix some of the vulnerabilities or procedural logic errors that exist during the development phase of the application, and to avoid unnecessary risks to the enterprise by exploiting the vulnerability of the program.

Code auditing is not a simple check of code, the reason for auditing code is to ensure that the code is secure enough to protect information and resources, so familiarity with the entire application's business processes is important to control the potential risks. Auditors can use questions like the following to interview developers to gather application information.

What types of sensitive information is included in the application and how does the application protect that information?

Does the application provide services internally or externally? Who will use them, and are they all trusted users?

Where is the application deployed?

How important is the application to the enterprise?

The best way is to do a checklist and let the developer fill it out. Checklist can be a more intuitive reflection of the application's information and the developer's coding security, it should cover the potentially serious vulnerabilities of the module, such as: Data validation, authentication, session management, authorization, encryption, error handling, logging, security configuration, network architecture.

2. Input validation and output display

Most of the vulnerabilities are due to the fact that the input data is not securely verified or the output data is not securely processed, the more rigorous data validation methods are:

1. Exact matching of data
2. Accepted Whitelist data
3. Rejection of blacklisted data
4. Encode the data that matches the blacklist

The list of variables that can be entered by the user in PHP is as follows:

$_server

$_get

$_post

$_cookie

$_request

$_files

$_env

$_http_cookie_vars

$_http_env_vars

$_http_get_vars

$_http_post_files

$_http_post_vars

$_http_server_vars

We should check these input variables

1. Command injection

The following functions are available for PHP execution system commands: System, EXEC, PassThru, ", Shell_exec, Popen, Proc_open, pcntl_exec
By searching for these functions in all program files, we determine whether the parameters of the function will change due to external commits, and check if they are handled safely.

Precautionary approach:

1. Use a custom function or library to override the functionality of an external command

2. Use the Escapeshellarg function to handle command parameters

3. Use Safe_mode_exec_dir to specify the path to the executable file

2. Cross-site Scripting

Reflective cross-site often occurs after the user submits the variable accepts the processing, the direct output displays to the client; the storage cross-site often occurs when a user-submitted variable is processed, stored in a database, and then read from the database to the client. Output functions are often used: echo, print, printf, vprintf, <%= $test%>

For a reflective cross-site, because the output is immediately displayed to the client, the current PHP page should check if the variable is submitted by the customer immediately after the display, in the process of whether the variable has been security check.

For a storage-type cross-site, check that the variables are stored in the input, and the output shows that the variables are checked during the security check.

Precautionary approach:

1. If the input data contains only letters and numbers, any special characters should block

2. Strictly match the input data, such as the message format, the user name contains only English or Chinese, underline, hyphen

3. HTML encoding of the output, code specification

< < > >

( (

) )

# #

& &

” “

‘ ‘

'%60

3. The file contains

PHP may appear in the file contains functions: Include, include_once, require, require_once, Show_source, Highlight_file, ReadFile, file_get_contents , fopen, File

Precautionary approach:

1. Exact matching of input data, such as determining language en.php and cn.php based on the value of the variable, then these two files are placed in the same directory ' language/'. $_post[' Lang '. PHP ', then check whether the submitted data is en or CN is the most stringent, check whether it contains only the letter is also good

2. By filtering the parameters in the/、.. Equal characters

4. Code Injection

PHP may have code injection functions: eval, preg_replace+/e, Assert, Call_user_func, Call_user_func_array, create_function

Find out where these functions are used in programs in your program, check that the commit variable is user-controllable, have no input validation

Precautionary approach:

1. Exact Match of input data

2. White-list filtering of executable functions

5.SQL Injection

SQL injection because you want to manipulate the database, it is common to look for SQL statement keywords: INSERT, delete, update, select, see if the passed variable parameter is user-controllable, whether it has been handled safely or not.

Precautionary approach:

Using parameterized queries

6.XPath Injection

XPath is used to manipulate XML, and we parse it by searching the XPath to see if the arguments submitted to the XPath function are handled safely

Precautionary approach:

Exact matching of data

7.HTTP Response Split

The case in PHP that can cause an HTTP response to be split is: Use the header function and use the $_server variable. Note that a high version of PHP prevents newline characters from appearing in the HTTP header, which can be skipped directly from this test.

Precautionary approach:

1. Exact Match of input data

2. Check the input input if there is \ R or \ n, reject directly

8. File Management

PHP for file management functions, if the input variables can be submitted by the user, the program does not do data validation, may become a high-risk vulnerability. We should search for the following functions in the program: Copy, RmDir, unlink, delete, fwrite, chmod, fgetc, Fgetcsv, fgets, fgetss, file, file_get_contents, Fread, ReadFile, Ftruncate, File_put_contents, Fputcsv, fputs, but usually every file manipulation function in PHP can be dangerous.

http://ir.php.net/manual/en/ref.filesystem.php

Precautionary approach:

1. Strict matching of submission data

2. Directory with restricted file operation

9. File Upload

PHP file upload will usually use move_uploaded_file, can also find the file upload program for specific analysis

Precautionary approach:

1. detecting file suffixes using whitelist

2. After uploading, the file name can be generated by time algorithm.

3. Upload directory script file is not executable

4. Note%00 truncation

10. Variable override

PHP variable overrides appear in the following situations:

1. Iterating through the initialization variables

Cases:

foreach ($_get as $key = $value)

$ $key = $value;

2. Function override variables: Parse_str, MB_PARSE_STR, Import_request_variables

When 3.register_globals=on, the get-mode commit variable is overwritten directly

Precautionary approach:

1. Set Register_globals=off

2. Do not use these functions to get the variables

11. Dynamic functions

When using dynamic functions, if the user is controllable on the variable, it can cause an attacker to execute arbitrary functions.

Cases:

< php $myfunc = $_get[' MyFunc '); $myfunc ();?>

Defense methods:

Do not use functions like this

3. Session security

1.HTTPOnly settings

Session.cookie_httponly = ON, client script (JavaScript, etc.) cannot access the cookie, and opening the instruction can effectively prevent the hijacking of the session ID through XSS attacks

2.domain settings

Check if Session.cookie_domain contains only this domain, and if it is a parent domain, other subdomains will be able to obtain cookies from this domain

3.path settings

Check Session.cookie_path that if the Web site itself is applied to/app, the path must be set to/app/to ensure security

4.cookies duration

Check Session.cookie_lifetime, if the time setting process is too long, even if the user closes the browser, the attacker can also compromise the security of the account

5.secure settings

If you use HTTPS, you should set up Session.cookie_secure=on to make sure that you use HTTPS to transfer cookies

6.session fixed

If the permission level changes (for example, after verifying the user name and password, the normal user is promoted to the administrator), we should modify the session ID that is about to regenerate, or the program will be at risk of a session fixed attack.

7.CSRF

A cross-site request forgery attack is an attacker who forges a malicious request link that, when accessed by a normal user in various ways, performs these malicious requests as a user. We should review the more important program modules, such as modifying the user's password, adding the user's function, and checking for the use of a one-time token to defend against CSRF attacks.

4. Encryption

1. Storing passwords in plaintext

Storing passwords in plaintext can be a serious threat to users, applications, and system security.

2. Weak password encryption

Using an easy-to-crack encryption algorithm, MD5 encryption has been partially exploited by the MD5 hack website to crack

3. Passwords are stored in files that attackers can access

For example: Save the password in txt, INI, conf, Inc, XML, etc., or write it directly in the HTML comment

5. Certifications and authorizations

1. User authentication

Check the location of the code for user authentication, and whether it can bypass authentication, for example: There may be form injection in the login code.

Check the login code for the use of verification code, etc., to prevent violent cracking means

2. Unauthenticated calls to functions or files

Some administration pages prohibit access by ordinary users, and sometimes developers forget to verify permissions on these files, causing the vulnerability to occur

Some pages use parameters to invoke functions without permission validation, such as Index.php?action=upload

3. Password hard-coded

Some programs will link the database account and password, directly to the database link function.

6. Random functions

1.rand ()

RAND () The maximum random number is 32767, when using Rand to process the session, the attacker can easily crack the session, it is recommended to use Mt_rand ()

2.mt_srand () and Mt_rand ()

PHP4 and php5<5.2.6, these two functions are unsafe for handling data. In Web applications, many use Mt_rand to deal with random sessions, such as password retrieval, which is the result of malicious use of the attacker to directly modify the password.

7. Special characters and multibyte encoding

1. Multi-byte encoding

8.PHP Hazard function

1. Buffer Overflow

Confirm_phpdoc_compiled

Impact Version:

Phpdocumentor Phpdocumentor 1.3.1

Phpdocumentor Phpdocumentor 1.3 RC4

Phpdocumentor Phpdocumentor 1.3 RC3

Phpdocumentor Phpdocumentor 1.2.3

Phpdocumentor Phpdocumentor 1.2.2

Phpdocumentor Phpdocumentor 1.2.1

Phpdocumentor Phpdocumentor 1.2

Mssql_pconnect/mssql_connect

Impact Version: PHP < = 4.4.6

Crack_opendict

Impact Version: PHP = 4.4.6

Snmpget

Impact version: PHP <= 5.2.3

Ibase_connect

Impact Version: PHP = 4.4.6

Unserialize

Impact version: Php 5.0.2, php 5.0.1, php 5.0.0, php 4.3.9, php 4.3.8, php 4.3.7, php 4.3.6, php 4.3.3, php 4.3.2, php 4.3.1, php 4.3.0, PHP 4.2 .3, PHP 4.2.2, php 4.2.1, php 4.2.0, php 4.2-dev, php 4.1.2, php 4.1.1, php 4.1.0, PHP 4.1, php 4.0.7, php 4.0.6, php 4.0.5, PHP 4.0.4 , PHP 4.0.3pl1, php 4.0.3, php 4.0.2, php 4.0.1pl2, php 4.0.1pl1, PHP 4.0.1

2.session_destroy () Delete file vulnerability

Impact version: Ominous, requires specific testing

The test code is as follows:

01

02 Session_save_path ('./');

03 Session_Start ();

04 if ($_get[' del ']) {

05 Session_unset ();

06 Session_destroy ();

07 }else{

08 $_session[' do ']=1;

09 Echo (session_id ());

10 Print_r ($_session);

11 }

12 ?>

When we submit cookie:phpsessionid=/. /1.php, the equivalent of deleting this file

3.unset ()-zend_hash_del_key_or_index Vulnerability

Zend_hash_del_key_or_index PHP4 less than 4.4.3 and PHP5 less than 5.1.3, may cause the Zend_hash_del to delete the wrong element. When PHP's unset () function is called, it blocks the variable from being unset.

9. Information Disclosure

1.phpinfo

If an attacker can browse to a program to invoke the environment information displayed by Phpinfo, it will facilitate further attacks

10.PHP Environment

1.open_basedir settings

Open_basedir can restrict the directory that the application can access, check whether the Open_basedir is set, and of course some are set by the Web server, for example: Apache php_admin_value,nginx+ fcgi using CONF to control PHP settings

2.allow_url_fopen settings

If Allow_url_fopen=on, then PHP can read remote files to operate, this is easily exploited by attackers

3.allow_url_include settings

If Allow_url_include=on, then PHP can contain remote files that can cause serious vulnerabilities

4.safe_mode_exec_dir settings

This option controls the directory of external commands that can be called by PHP, and if the PHP program has an external command, the directory that specifies the external command, the risk of controlling the program

5.MAGIC_QUOTE_GPC settings

This option escapes the special characters that are submitted to the parameter, and it is recommended to set Magic_quote_gpc=on

6.register_globals settings

Turning on this option will cause PHP to register all externally committed variables as global variables, which can be quite serious.

7.safe_mode settings

Safe_mode is an important security feature of PHP, it is recommended to open

8.session_use_trans_sid settings

If SESSION.USE_TRANS_SID is enabled, it causes PHP to pass the session ID through a URL, which makes it easier for an attacker to hijack the current session, or to trick the user into using an existing session that has been controlled by the attacker.

9.display_errors settings

If this option is enabled, PHP will output all error or warning messages that an attacker can use to obtain sensitive information such as the Web root path.

10.expose_php settings

If the expose_php option is enabled, each response generated by the PHP interpreter will contain the version of PHP installed on the host system. Knowing the version of PHP running on a remote server allows an attacker to enumerate known exploits against the system, greatly increasing the chances of a successful attack.

Paper:
Http://0xsec.org/paper/phpfuzz.html

Reference Documentation:

Https://www.fortify.com/vulncat/zh_CN/vulncat/index.html

Http://secinn.appspot.com/pstzine/read?issue=3&articleid=6

Http://riusksk.blogbus.com/logs/51538334.html

Http://www.owasp.org/index.php/Category:OWASP_Code_Review_Project

  • Related Article

    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.