Home >Backend Development >PHP Tutorial >Securing PHP Applications, Securing PHP Applications_PHP Tutorial
Before you begin
In this tutorial, you will learn how to add security to your own PHP web application sex. This tutorial assumes you have at least one year of experience writing PHP web applications, so basic knowledge of the PHP language (conventions or syntax) is not covered here. The goal is to give you an understanding of how to secure the web applications you build.
Objectives
This tutorial explains how to defend 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.
Prerequisites
This tutorial is written for PHP developers with at least one year of programming experience. You should understand PHP's syntax and conventions; these are not explained here. Developers with experience using other languages such as Ruby, Python, and Perl will also benefit from this tutorial, as many of the rules discussed here apply to other languages and environments as well.
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, 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 are 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
'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
Now that you can’t trust user input, you should also know that you shouldn’t trust the PHP configuration on the machine. Way. 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 variables 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 a SQL injection attack, the user passes through. Manipulate the form or GET query string to add information to the database query. For example, suppose you have a simple login database. Each record in this database has a username field and a password field. Let's build a login form. The user can log in.
Listing 5. Simple login form
;/head>