PHP code audit

Source: Internet
Author: User
Tags account security
PHP code audit documents were updated last year. they were not well written, and some were not fully written. I have referenced many documents.

The owasp codereview should also be 2.0.

Let's give some suggestions.

Directory

1. Overview 3

2. input verification and output display 3

2.1 Command Injection 4
2.2 XSS 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 splitting 6

2.8 File management 6
2.9 file Upload 7
2.10 variable overwrite 7
2.11 dynamic functions 7

3. session Security 8

3.1 HTTPOnly setting 8
3.2 domain settings 8
3.3 path setting 8
3.4 cookie 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 passwords are stored in files accessible to attackers 9

5. authentication and authorization 10

5.1 User Authentication 10
5.2 unauthenticated calls to functions or files 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 multi-byte encoding 11

7.1 multi-byte encoding 11

8. PHP dangerous functions 11

8.1 buffer overflow 11
8.2 session_destroy () file deletion vulnerability 12
8.3 unset ()-zend_hash_del_key_or_index vulnerability 12

9. information leakage 13

9.1 phpinfo 13

10. PHP Environment 13

10.1 open_basedir settings 13
10.2 allow_url_fopen settings 13
10.3 set allow_url_include 13
10.4 set safe_mode_exec_dir to 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 review is a systematic check of the application source code. It aims to find and fix some vulnerabilities or program logic errors in the application development stage, so as to prevent the illegal exploitation of program vulnerabilities from bringing unnecessary risks to the enterprise.

Code review is not a simple code check. the reason for reviewing the code is to ensure that the code can be securely protected by sufficient information and resources, therefore, it is very important to be familiar with the business process of the entire application to control potential risks. Reviewers can use questions similar to the following to interview developers to collect application information.

What types of sensitive information does an application contain and how does the application protect it?

Does an application provide internal services or external services? Who will use it? are they all trusted users?

Where is the application deployed?

What is the importance of applications for enterprises?

The best way is to make a checklist for developers to fill in. Checklist can intuitively reflect application information and coding security done by developers. it should cover modules that may have severe vulnerabilities, such: data verification, identity authentication, session management, authorization, encryption, error processing, logs, security configuration, and network architecture.

2. input verification and output display

Most vulnerabilities are caused by the absence of security verification on input data or the absence of security processing on output data. strict data verification methods are as follows:

1. exact data matching
2. accept data from the whitelist
3. reject blacklist data
4. encode the data that matches the blacklist

In PHP, the list of variables that users can enter 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

PHP can use the following functions to execute system commands: system, exec, passthru, ", shell_exec, popen, proc_open, and pcntl_exec.
By searching for these functions in all program files, we can determine whether the function parameters will change due to external submissions and check whether these parameters have been safely processed.

Defense methods:

1. Use a user-defined function or function library to replace the functions of external commands

2. use the escapeshellarg function to process command parameters

3. use safe_mode_exec_dir to specify the path of the executable file

2. cross-site scripting

Reflected cross-site variables are often processed after they are submitted by the user, and are directly output to the client. stored cross-site variables are often processed after they are submitted by the user, stored in the database, and then read the information from the database and output it to the client. Output functions are often used: echo, print, printf, vprintf, <% = $ test %>

For cross-site reflection, because the output is immediately displayed to the client, check whether the variable is immediately displayed after the client submits the variable on the current php page, whether the variables have been checked for security during this process.

For the storage-type cross-site, check whether the variables have passed the security check during the input and output of the input variables.

Defense methods:

1. if the input data only contains letters and numbers, any special characters should be blocked.

2. strictly match the entered data. for example, in the mail format, the user name can only contain English letters, Chinese characters, underscores, and hyphens.

3. encode the output in HTML format.

<>

((

))

##

&&

""

''

'% 60

3. file inclusion

PHP may contain functions including include, include_once, require, require_once, show_source, highlight_file, readfile, file_get_contents, fopen, and file.

Defense methods:

1. accurately match the input data, for example, determining the language en based on the value of the variable. php, cn. php, then the two files are placed in the same directory 'language /'. $ _ POST ['Lang ']. '. php ', check whether the submitted data is en or cn is the strictest, and check whether it only contains letters.

2. filter the/,..., and other characters in the parameter.

4. code injection

PHP may have code injection functions: eval, preg_replace +/e, assert, call_user_func, call_user_func_array, create_function

Find the places where these functions are used in the program, and check whether the submission variables are controllable and whether input verification is performed.

Defense methods:

1. exact match of input data

2. filter executable functions by whitelist

5. SQL injection

Because SQL injection is required to operate the database, it generally finds keywords of SQL statements: insert, delete, update, and select to check whether the passed variable parameters are controllable and whether they have been safely processed.

Defense methods:

Use parameterized query

6. XPath injection

Xpath is used to operate xml. we search for xpath to analyze whether the parameters submitted to the xpath function are processed safely.

Defense methods:

Exact data matching

7. HTTP response splitting

In PHP, the HTTP response splitting may be caused by the use of the header function and the $ _ SERVER variable. Note that PHP later versions will disable line breaks in the HTTP header. you can skip this test directly.

Defense methods:

1. exact match of input data

2. check whether \ r or \ n is input.

8. file management

PHP functions for file management. if the input variables can be submitted by the user, no data verification is performed in the program, which 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, however, every file operation function in PHP may be dangerous.

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

Defense methods:

1. strictly match the submitted data

2. restrict accessible directories of files

9. file Upload

For PHP file uploads, move_uploaded_file is usually used. you can also find the file upload program for detailed analysis.

Defense methods:

1. use the whitelist method to check the file suffix

2. generate file names by time algorithm after uploading

3. the uploaded directory script file cannot be executed.

4.% 00 truncation

10. variable overwrite

PHP variable overwrite may occur in the following situations:

1. Traverse initialization variables

Example:

Foreach ($ _ GET as $ key => $ value)

$ Key = $ value;

2. function override variables: parse_str, mb_parse_str, and import_request_variables

3. when Register_globals = ON, the variables submitted in GET mode will be overwritten directly.

Defense methods:

1. set Register_globals = OFF

2. do not use these functions to obtain variables.

11. dynamic functions

When dynamic functions are used, attackers can execute arbitrary functions if the variables are controllable.

Example:

<? Php $ myfunc =$ _ GET ['myfunc']; $ myfunc ();?>

Defense method:

Do not use functions like this

3. session Security

1. HTTPOnly settings

Session. cookie_httponly = ON, the client script (JavaScript, etc.) cannot access this cookie. enabling this command can effectively prevent session ID hijacking through XSS attacks.

2. domain settings

Check whether session. cookie_domain only contains this domain. if it is a parent domain, other subdomains can obtain cookies of this domain.

3. path settings

Check session. cookie_path. if the website is applied to/app, the path must be set to/app/to ensure security.

4. cookie duration

Check session. cookie_lifetime. if the time setting process is too long, even if the user closes the browser, attackers may also endanger account security.

5. secure settings

If HTTPS is used, set session. cookie_secure = ON to ensure that HTTPS is used to transmit cookies.

6. Fixed session

If the permission level changes (for example, after verifying the user name and password, the common user is promoted to the administrator), we should modify the session ID to be re-generated, otherwise, the program may face the risk of session fixation attacks.

7. CSRF

The cross-site request forgery attack allows an attacker to forge a malicious request link. after a normal user accesses the link in various ways, the attacker will execute these malicious requests as a user. We should review important program modules, such as modifying user passwords, adding user functions, and check whether one-time tokens are used to defend against csrf attacks.

4. Encryption

1. plaintext storage password

Storing passwords in plain text seriously threatens the security of users, applications, and systems.

2. weak password encryption

Using an easy-to-crack encryption algorithm, MD5 encryption can be used to crack websites.

3. passwords are stored in files accessible to attackers.

For example, save the password in txt, ini, conf, inc, xml, or other files, or directly write it in HTML comments.

5. authentication and authorization

1. user authentication

Check the location where the code performs user authentication and whether the authentication can be bypassed. for example, a form injection may exist in the login code.

Check whether the logon code uses verification codes or other methods to prevent brute-force cracking.

2. unauthenticated call of functions or files

Some management pages prohibit access by common users. Sometimes developers forget to verify the permissions of these files, resulting in a vulnerability.

Some pages use the parameter call function without permission verification, such as index. php? Action = upload

3. hardcoded passwords

Some programs directly write the database linked account and password to the database linked function.

6. random functions

1. rand ()

The maximum random number of rand () is 32767. When rand is used to process the session, attackers can easily crack the session. mt_rand () is recommended ()

2. mt_srand () and mt_rand ()

PHP4 and PHP5 <5.2.6, these two functions are not safe to process data. In many web applications, mt_rand is used to process random sessions, such as the password retrieval function. The consequence is that attackers maliciously exploit the vulnerability to directly change the password.

7. special characters and multi-byte encoding

1. multi-byte encoding

8. PHP dangerous functions

1. Buffer Overflow

Confirm_phpdoc_compiled

Affected versions:

Php?entor php=entor 1.3.1

Php?entor php=entor 1.3 RC4

Php?entor php=entor 1.3 RC3

Php?entor php=entor 1.2.3

Php?entor php=entor 1.2.2

Php?entor php=entor 1.2.1

Phpbench entor 1.2

Mssql_pconnect/mssql_connect

Affected versions: PHP <= 4.4.6

Crack_opendict

Affected versions: PHP = 4.4.6

Snmpget

Affected versions: PHP <= 5.2.3

Ibase_connect

Affected versions: PHP = 4.4.6

Unserialize

Affected versions: 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 () file deletion vulnerability

Affected versions: ominous, specific tests required

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 the cookie: PHPSESSIONID =/../1.php, this file is deleted.

3. unset ()-zend_hash_del_key_or_index vulnerability

Zend_hash_del_key_or_index PHP4 is smaller than 4.4.3 and PHP5 is smaller than 5.1.3, which may cause zend_hash_del to delete the incorrect element. When the PHP unset () function is called, it will prevent the variable from being unset.

9. information leakage

1. phpinfo

If attackers can browse the environment information displayed by calling phpinfo in the program, further attacks will be facilitated.

10. PHP environment

1. open_basedir settings

Open_basedir can restrict the directories accessible to applications and check whether open_basedir is configured. of course, some are set through the web server. for example, apache php_admin_value, nginx + fcgi uses conf to control php settings.

2. allow_url_fopen settings

If allow_url_fopen = ON, php can read remote files for operations, which is easily exploited by attackers.

3. set allow_url_include

If allow_url_include = ON, php can contain remote files, which may cause serious vulnerabilities.

4. safe_mode_exec_dir settings

This option can control the directory of php callable external commands. if the PHP program calls external commands, you can specify the directory of external commands to control program risks.

5. magic_quote_gpc settings

This option can escape special characters submitted to the parameter. we recommend that you set magic_quote_gpc = ON

6. register_globals settings

Enabling this option will cause php to register all external submitted variables as global variables with serious consequences.

7. safe_mode settings

Safe_mode is an important security feature of PHP. we recommend that you enable it.

8. session_use_trans_sid settings

If session. use_trans_sid is enabled, PHP will pass the session ID through the URL, which makes it easier for attackers to hijack the current session or fool users to use the existing session that has been controlled by attackers.

9. display_errors settings

If this option is enabled, PHP will output all error or warning information. Attackers can exploit this information 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 PHP version installed on the host system. After learning about the PHP version running on the remote server, attackers can exploit the known theft methods of the system enumeration to greatly increase the chance of launching a successful attack.

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

Reference:

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

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.