Home > Article > Backend Development > PHP application security, PHP application security_PHP tutorial
Whether during development, during interviews or during technical discussions, security needs to be in-depth Understand and master.
Objective
The goal of this tutorial is to give you an understanding of how to secure the web applications you build. Learn how to protect against the most common security threats: SQL injection, manipulation of GET and POST variables, buffer overflow attacks, cross-site scripting attacks, in-browser data manipulation, and remote form submission.
A quick introduction to security
What is the most important part of a web application? Depending on who answers the question, the answer to this question may vary. Business people need reliability and scalability. IT support teams need robust and maintainable code. End users require beautiful user interfaces and high performance in performing tasks. However, if the answer is “security”, then everyone will agree that it is important for web applications.
However, most discussions stop there. Although security is on the project checklist, often it is not addressed until the project is delivered. The number of web application projects that take this approach is staggering. Developers worked for months, adding security features only at the end to make the web application available to the public.
The result is often a mess or even a need for rework because the code has been inspected, unit tested, and integrated into a larger framework before security features were added to it. After adding security, major components may stop working. The integration of security adds an extra burden or step to an otherwise smooth (but unsafe) process.
This tutorial provides a great way to integrate security into your PHP web application. It discusses several general security topics and then dives into major security vulnerabilities and how to plug them. After completing this tutorial, you will have a better understanding of security.
Topics include:
SQL injection attacks
Manipulating GET strings
Buffer overflow attacks
Cross-site scripting attacks (XSS)
In-browser data manipulation
Remote Forms Submit
Web Security 101
Before discussing the details of implementing security, it is best to discuss web application security from a high-level perspective. This section introduces some basic tenets of security philosophy that should be kept in mind no matter what kind of web application you are creating. Some of these ideas come from Chris Shiflett (whose book on PHP security is an invaluable treasure trove), some from Simson Garfinkel (see Related topics), and some from years of accumulated knowledge.
Rule 1: Never trust external data or input
The first thing you must realize about web application security is that external data should not be trusted. External data includes any data that is not entered directly by the programmer into the PHP code. Any data from any other source (such as GET variables, form POST, databases, configuration files, session variables, or cookies) cannot be trusted until steps are taken to ensure security.
For example, the following data elements can be considered safe because they are set in PHP.
Listing 1. Safe and flawless code
define("GREETING", 'hello there' . $myUsername); [/php]
However, the following data elements are flawed.
Listing 2. Unsafe, flawed code
', 'tommy'); //tainted!
define("GREETING", 'hello there' . $myUsername); //tainted! [/php]
Why is the first variable $myUsername defective? of? Because it comes directly from the form POST. Users can enter any string into this input field, including malicious commands to clean files or run previously uploaded files. You might ask, "Can't you avoid this danger by using a client-side (JavaScript) form validation script that only accepts the letters A-Z?" Yes, this is always a beneficial step, but as we'll see later , anyone can download any form to their machine, modify it, and resubmit whatever they need.
The solution is simple: the sanitization code must be run on $_POST['username']. If you don't do this, you risk polluting these objects any other time you use $myUsername (such as in an array or constant).
A simple way to sanitize user input is to use regular expressions to process it. In this example, only letters are expected to be accepted. It might also be a good idea to limit the string to a specific number of characters, or require all letters to be lowercase.
Listing 3. Making user input safe
$arrayUsers = array($myUsername, 'tom', 'tommy'); //clean!
define("GREETING", 'hello there' . $myUsername); //clean!
function cleanInput($ input){
$clean = strtolower($input);
$clean = preg_replace(”/[^a-z]/”, “”, $clean);
$clean = substr($clean, 0,12);
return $clean;
}[/php]
Rule 2: Disable PHP settings that make security difficult to implement
You already know that user input cannot be trusted, and you should know that The way PHP is configured on the machine should not be trusted. For example, make sure register_globals is disabled. If register_globals is enabled, it's possible to do careless things like use a $variable to replace a GET or POST string with the same name. By disabling this setting, PHP forces you to reference the correct variable in the correct namespace. To use variables from a form POST, $_POST['variable'] should be quoted. This way you won't mistake this particular variable for a cookie, session, or GET variable.
The second setting to check is the error reporting level. During development, you want to get as many error reports as possible, but when you deliver the project, you want the errors to be logged to a log file rather than displayed on the screen. Why? Because malicious hackers can use error reporting information (such as SQL errors) to guess what the application is doing. This kind of reconnaissance can help hackers breach the application. To close this vulnerability, edit the php.ini file to provide a suitable destination for the error_log entries and set display_errors to Off.
Rule 3: If you can’t understand it, you can’t protect it
Some developers use strange syntax, or organize statements very tightly, resulting in short but ambiguous code. This approach may be efficient, but if you don't understand what the code is doing, you can't decide how to protect it.
For example, which of the following two pieces of code do you like?
Listing 4. Make the code easy to protect
”);
//unobfuscated code
$input = ”;
if (isset($_POST['username'])){
$input = $_POST['username'];
}else{
$input = ”;
}[/php]
In the second clearer code snippet, it is easy to see that $input is flawed and needs Clean it up before processing it safely
Rule 4: “Defense in depth” is the new magic
This tutorial will use examples to show how to protect online forms while taking the necessary measures in the PHP code that handles the form. . Likewise, even if you use PHP regex to ensure that GET variables are entirely numeric, you can still take steps to ensure that SQL queries use escaped user input.
Defense in depth is not just a good idea, it will ensure that you don't get into serious trouble.
Now that the basic rules have been discussed, let’s look at the first threat: SQL injection attacks
Preventing SQL injection attacks
In SQL. In an injection attack, the user adds information to a database query by manipulating a form or GET query string. For example, consider a simple login database. Each record in this database has a username field and a password field. Build a login form to allow users to log in
Listing 5. Simple login form
title>