Discussion on PHP security _php tutorial

Source: Internet
Author: User
Tags ereg php server
One, Apache server security settings

1, to nobody users to run

In general, Apache is installed and run by root. If the Apache server process has root user privileges, it poses a significant threat to the security of the system and should ensure that the Apache server process runs with the most likely low-privileged users. By modifying the following options in the httpd.conf file to nobody users to run Apache for relative security purposes.
User Nobody
group#-1

2. Permissions of the ServerRoot directory

To ensure that all configurations are appropriate and secure, access to the Apache home directory needs to be tightly controlled so that non-superuser cannot modify the contents of the directory. Apache's home directory corresponds to the server root control of the Apache server profile httpd.conf, which should be:
Server Root/usr/local/apache

3, the configuration of SSI

The includes NO exec option is added to the options directive in the configuration file access.conf or httpd.conf to disable the execution function in Apache Server. To prevent users from directly executing the Apache server execution program, resulting in the public server system.

Options includes Noexec


4. Prevent users from modifying system settings

The following settings are set in the Apache server's configuration file to prevent users from creating and modifying. htaccess files to prevent users from exceeding the system security features that can be defined.

Allowoveride None
Options None
Allow from all

The specific directories are then configured appropriately.

5, change the Apache server default Access characteristics

Apache's default settings only guarantee a certain degree of security, if the server can find the file through normal mapping rules, then the client will get the file, such as Http://local host/~ root/will allow users to access the entire file system. Add the following to the server file:

Order Deny,ellow
Deny from all

Default access to the file system is forbidden.

6. Security Considerations for CGI scripts

A CGI script is a series of programs that can be run through a Web server. In order to ensure the security of the system, you should ensure that the CGI author is trustworthy. For CGI, it is best to limit it to a specific directory, such as Cgi-bin, easy to manage, but also to ensure that the CGI directory files are not writable, to avoid some deceptive programs to reside or mingle with it, if you can provide users with a security good CGI program module as a reference, It may reduce many unnecessary troubles and security risks, and remove all non-business application scripts under the CGI directory to prevent abnormal information leaks.

7. SSL Link Encryption

These common measures can give Apache Server a basic security operating environment, obviously in the implementation of the further refinement of the decomposition, to develop a practical application of the Security Configuration scheme.

Second, PHP security settings

The server does not block all security issues, such as program vulnerability issues, user input form issues, PHP file permissions issues, and so on.
You can also use some means to confuse hackers or people with ulterior motives.
1, program code Vulnerability issues

Many PHP programs have a major weakness is not the PHP language itself, but the programmer's security awareness is not high. Therefore, you must always be aware of the possible problems with each piece of code to discover the possible impact of incorrect data submissions.
Copy CodeThe code is as follows:
Unlink ($evil _var);
Fwrite ($fp, $evil _var);
System ($evil _var);
EXEC ($evil _var);
?>

You must always keep an eye on your code to ensure that every variable submitted from the client is properly checked, and then ask yourself the following questions:

Does this script affect only the files that you expect?
Can the abnormal data be brought into effect after being submitted?
Can this script be used for unplanned purposes?
Can this script be combined with other scripts to do bad things?
Have all the transactions been fully documented?
Ask yourself these questions when you write your code, or you might want to rewrite the code later to add security. Paying attention to these problems may not be enough to keep the system safe, but at least it can improve security.

You can also consider turning off register_globals,magic_quotes or other settings that make programming easier but will make a variable more legitimate, the source, and its value being messed up.

2. User input form problem

Validate any data entered by the user to ensure the security of the PHP code.
Note that 1:js is just a tool for improving the experience of visiting users rather than validating them. Because any visiting user may or may inadvertently disable the execution of client script, this layer of validation is skipped. So we have to test this data on the PHP server-side program.
Note 2: Do not use $_server[' http_referer ' This super variable to check the source address of the data, a very small novice hacker will use tools to forge this variable data, as far as possible, using MD5, or Rand and other functions to generate a token, verify the source, Verify that the token matches.

3, PHP file permissions issues

PHP is designed to access the file system at the user level, so it is entirely possible to write a piece of PHP code to read system files such as/ETC/PASSWD, change the network connection, send a lot of print tasks, and so on. Therefore, you must make sure that the PHP code reads and writes the appropriate file. Take a look at the following code, where the user wants to delete a file from their home directory. Assuming this is the case with the Web interface to manage the file system, Apache users have the right to delete files from the user directory.
Copy CodeThe code is as follows:
$username = $_post[' user_submitted_name ');
$homedir = "/home/$username";
$file _to_delete = "$userfile";
Unlink ("$homedir/$userfile");
echo "$file _to_delete has been deleted!";
?>

Since the username variable can be submitted through the user table forms, you can submit someone else's user name and file name, and delete the file. In this case, it is necessary to consider other ways of certification:

Only give PHP Web users a limited amount of permissions.
Check all the submitted variables.
The following are more secure validation and checking of file names and variables:
Copy CodeThe code is as follows:
$username = $_server[' Remote_user ');
$homedir = "/home/$username";

if (!ereg (' ^[^./][^/]*$ ', $userfile))
Die (' bad filename ');

if (!ereg (' ^[^./][^/]*$ ', $username))
Die (' bad username ');
?>


4. Hide PHP Extensions

Generally speaking, improving safety by means of concealment is considered a less useful practice. But in some cases, it is worthwhile to add as much security as possible.

Some simple ways to help hide PHP can make it more difficult for attackers to find weaknesses in the system. Setting expose_php = off in the php.ini file reduces the useful information they can get.

Another strategy is to have the Web server parse different extensions with PHP. Whether you are using a. htaccess file or an Apache configuration file, you can set the file name extension that can mislead the attacker:



# make PHP look like other programming languages
AddType application/x-httpd-php. asp. py. pl


# make PHP look like an unknown file type
AddType application/x-httpd-php. Bop. Foo. 133t

# make the PHP code look like an HTML page
AddType application/x-httpd-php. htm. html

For this method to take effect, you must change the extension of the PHP file to the extension above. This improves security by hiding, albeit with a low defensive capability and a few drawbacks.

third, MySQL database security settings

PHP itself does not protect the security of the database. The following sections simply describe how to use PHP scripts for basic access and operation of the database. Remember a simple principle: go deep into your defenses. The more measures to protect a database, the more difficult it is for an attacker to obtain and use the information in the database. Properly designing and applying databases can reduce the fear of being attacked.

1, Database design issues

The application never uses the database owner or Superuser account to connect to the database, because these accounts can perform arbitrary operations, such as modifying the database structure (for example, deleting a table) or emptying the contents of the entire database. The following user settings are dangerous.


You should create different database accounts for each aspect of your program and give you very limited permissions on database objects. Assign only the permissions that are required to complete its functionality, and avoid the same user being able to complete another user's business. This way, even if an attacker exploits a program vulnerability to gain access to a database, it can only do the same extent as the program.

2. Database Connectivity Issues
The connection is built on the SSL encryption technology to increase the security of client and server-side communication, or SSH can be used to encrypt the connection between the client and the database. If these techniques are used, it is difficult for an attacker to monitor the server's communication or obtain information from the database.

3. Encryption of database data

Ssl/ssh can protect data exchanged between the client and the server, but Ssl/ssh does not protect the data that is already in the database. SSL is just a protocol for encrypting network traffic.

If an attacker obtains a license to access the database directly (bypassing the Web server), sensitive data can be exposed or abused, unless the database itself protects the information. Encrypting data within a database is an effective way to mitigate such risks, but only a small number of databases provide these encryption capabilities.

For this problem, there is a simple solution, is to create their own encryption mechanism, and then use it in the PHP program, the most common example is the password after MD5 encrypted hash stored in the database to replace the original plaintext password.

Copy CodeThe code is as follows:
$query = sprintf ("INSERT into Users (name,pwd) VALUES ('%s ', '%s ');",
Addslashes ($username), MD5 ($password));
$result = Pg_query ($connection, $query);
$query = sprintf ("Select 1 from Users WHERE name= '%s ' and pwd= '%s ';",
Addslashes ($username), MD5 ($password));
$result = Pg_query ($connection, $query);
if (Pg_num_rows ($result) > 0) {
Echo ' Welcome, $username! ';
} else {
Echo ' Authentication failed for $username. ';
}
?>


4. SQL injection problem

Direct SQL command injection is a common technique used by attackers to create or modify existing SQL statements to achieve hidden data, or to overwrite critical values, or even perform database host operating system commands. This is achieved by using the application to obtain user input and combine it with static parameters into SQL queries. Here are some real examples.

Copy CodeThe code is as follows:
$query = "SELECT ID, name, inserted, size from products
WHERE size = ' $size '
ORDER by $order LIMIT $limit, $offset; ";
$result = Odbc_exec ($conn, $query);
?>


You can add another SELECT query based on the original query to get the password:
Union select ' 1 ', concat (uname| | ' -'|| passwd) as name, ' 1971-01-01 ', ' 0 ' from usertable;
If the above statement (using ' and--) is added to any of the variables in the $query, then it will be troublesome.

These attacks are always based on the discovery of code that is not strong in security awareness. Therefore, never trust the data entered by the outside world, especially from the client, including selection boxes, form hidden fields, and cookies. As in the first example above, even a normal query can cause disaster.

Never use a superuser or owner account to connect to a database. Account with restricted permissions.
Checks whether the input data has the desired data format. PHP has many functions that can be used to check input, from simple variable functions and character type functions (such as is_numeric (), Ctype_digit ()) to complex Perl-compatible regular expression functions.

If the program waits for a number to be entered, consider using Is_numeric () to check it, or use Settype () directly to convert it, or use sprintf () to format it as a number.

A more secure way to prevent the paging of SQL injection:

Copy CodeThe code is as follows:
Settype ($offset, ' Integer ');
$query = "SELECT ID, name from the products ORDER by name, OFFSET $offset;";
$query = sprintf ("Select ID, name from the products ORDER by name, OFFSET%d;",
$offset);
?>

http://www.bkjia.com/PHPjc/325517.html www.bkjia.com true http://www.bkjia.com/PHPjc/325517.html techarticle One, Apache server security settings 1, in order to nobody users run under normal circumstances, Apache is installed and run by root. If the Apache server process has root user privileges, it will ...

  • 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.