Some Tips For Securing PHP

In IT world, sometimes the developer is in ‘not good’ condition when he is doing his job, Maybe he is having problems in his family, or is under pressure from his job. But in the other hand, hacker is always in a good mood when he is doing his job.

Securing web applications from all sorts of forged attacking attempts is the ultimate duty of a web developer. You should build your web apps protective enough to have no security issues or loopholes, thus eradicating the possibility of any malicious attack. In most cases, the developers must take the responsibility and put in every possible effort to identify the vulnerabilities and propose solutions, if any to address the issues prevailing in the apps.

PHP is a popular language for web development. It is so popular that In some cases companies do run few bounty programs in which they invite different security experts to analyze their application from the core and suggest critical PHP security best practices for it.

Table of Content

I think PHP is one of the best scripting language and widely used by the developer and has many framework that can help developer for creating applications. The verdict has some ground too because PHP is the oldest and widely used language for web app development. But for a long time since PHP 5.6, we haven’t seen any major updates regarding security and hence the language faces some security issues.

Popular CMS like WordPress, Joomla, Magento, and Drupal are built in PHP and according to Sucuri, most of the vulnerabilities in PHP CMS came to light during the year 2017:

  • WordPress security issues rose from 74% in 2016 Q3 to 83% in 2017.
  • Joomla security issues have dropped from 17% in 2016 Q3 to 13.1% in 2017.
  • Magento security issues rose marginally from 6% in Q3 2016 to 6.5% in 2017.
  • Drupal security issues dropped slightly from 2% in Q3 2016 to 1.6% in 2017.

And this is sucuri report for year 2018/2019 about the infections of the CMS

Based on the data above, the current situation is not good enough, but thanks to open source contributors, who are trying hard to overcome the problems and we have seen some drastic changes in PHP of late. PHP 7.x with various updates and fixes. The best thing about PHP 7.x relates to the security upgradations which truly revamped the security protocol of the language.

What This PHP Security Tips Contains?

This writting, i collected from many sources, and i have applied to my system. Therefore, the main aim of this PHP security tips is to make you aware about the best practices for security in PHP web applications. I will be defining the the following problems and mentioning possible solutions for them.

  • Update PHP Regularly
  • Cross site scripting (XSS)
  • SQL Injection Attacks
  • Cross site request forgery XSRF/CSRF
  • Session Hijacking
  • Hide Files from the Browser
  • Securely Upload Files
  • Use SSL Certificates For HTTPs
  • Deploy PHP Apps on Clouds

Note: please do not consider it as a complete cheat sheet. There must be better ways and more unique solutions developers would be applying on the their applications to make it perfectly secured.

Okey… Let’s Start…….

1. Update PHP Regularly

Right now, the most stable and latest version of PHP available is PHP 7.2.8. I recommend that you must update your PHP application to this new one. If you are still using PHP 5.6 then you will be having a lot of deprecations while upgrading PHP apps. You will also need to update your code and change some functional logics like password hashing etc. There are also some tools available to check the deprecation of your code and help you in migrating those. I have listed some tools below:

  1. PHP 7 Compatibility Checker
  2. PHP 7 MAR
  3. Phan

If you are using PHPStorm then you can use PHP 7 Compatibility Inspection, that will show you which code will cause you issues.

2. Cross-site scripting (XSS)

Cross site scripting is a type of malicious web attack in which an external script is injected into the website’s code or output. The attacker can send infected code to the end user while browser can not identify it as a trusted script. This attack occurs mostly on the places where user has the ability to input and submit data. The attack can access cookies, sessions and other sensitive information about the browser. Let’s look at the example of a GET request which is sending some data through URL:

URL: http://example.com/search.php?search=<script>alert('test')</script>

$search = $_GET['search'] ?? null;

echo 'Search results for '.$search;

You can figure out this attack by using htmlspecialchars. Also by using ENT_QUOTES, you can escape single and double quotes.

$search = htmlspecialchars($search, ENT_QUOTES, 'UTF-8');

echo 'Search results for '.$search;

Meanwhile, XSS attacks can also execute via attributes, encoded URI schemes and code encoding.

3. SQL Injection Attacks

The SQL injection is the most common attack in PHP scripting. A single query can compromise the whole application. In SQL injection attack, the attacker tries to alter the data you are passing via queries. Suppose you are directly processing user data in SQL queries, and suddenly, an anonymous attacker secretly uses different characters to bypass it. See the below-mentioned SQL query:

$sql = "SELECT * FROM users WHERE username = '" . $username . "';

The $username can contain altered data which can damage the database including deleting the whole database in the blink of an eye. So, what’s the solution? PDO. I recommend that you always use prepared statements. PDO helps you in securing SQL queries.

p>Let’s look at another example in which GET data is sent through URL: http://example.com/get-user.php?id=1 OR id=2;

$id = $_GET['id'] ?? null;

The connection between the database and application is made with the below statement:

$dbh = new PDO('mysql:dbname=testdb;host=127.0.0.1', 'dbusername', 'dbpassword');

You can select username based on the above ID but wait! Here SQL code ‘GET data’ gets injected in your query. Be careful to avoid such coding and use prepared statements instead:

$sql = "SELECT username, email FROM users WHERE id = ".$id." ;

foreach ($dbh->query($sql) as $row) {

   printf ("%s (%s)\n", $row['username'], $row['email']);

}

Now you can avoid the above SQL injection possibility by using

$sql = "SELECT username, email FROM users WHERE id = :id";

$sth = $dbh->prepare($sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);

$sth->execute([':id' => $id]);

$users = $sth->fetchAll();

Also, a good practice is to use ORM like doctrine or eloquent, as there is the least possibility of injecting SQL queries in them.

4.Cross site request forgery XSRF/CSRF

The CSRF attack is quite different to XSS attacks. In CSRF attack, the end user can perform unwanted actions on the authenticated websites and can transfer malicious commands to the site to execute any undesirable action. CSRF can’t read the request data and mostly targets the state changing request by sending any link or altered data in HTML tags. It can force the user to perform state changing requests like transferring funds, changing their email addresses etc. Let’s see this URL in which GET requests is sending money to another account:

GET http://bank.com/transfer.do?acct=TIM&amount=100 HTTP/1.1

Now if someone wants to exploit the web application he/she will change the URL with name and amount like this

http://bank.com/transfer.do?acct=Sandy&amount=100000

Now this URL can be sent via email in any file, Image etc and the attacker might ask you to download the file or click on the image. And as soon as you do that, you instantly end up with sending huge amount of money you never know about.

5. Securely Upload Files

File uploading is a necessary part of any user data processing application. But remember at some points, files are also used for XSS attacks as I have already explained above in the article. Returning to the basics, always use the POST request in the form and declare the property enctype=”multipart/form-data” in <form> tag. Then validate the file type using finfo class like this:

$finfo = new finfo(FILEINFO_MIME_TYPE);
$fileContents = file_get_contents($_FILES['some_name']['tmp_name']);

$mimeType = $finfo->buffer($fileContents);

Developers can create their own custom and ultra-secure file validation rules, but some frameworks like Laravel, Symfony and codeigniter already have pre-defined methods to validate file types.

Let’s look at another example. The HTML of form should be like this:

<form method="post" enctype="multipart/form-data" action="upload.php">

   File: <input type="file" name="pictures[]" multiple="true">

   <input type="submit">

</form>

And upload.php contains the following code:

foreach ($_FILES['pictures']['error'] as $key => $error) {

   if ($error == UPLOAD_ERR_OK) {

       $tmpName = $_FILES['pictures']['tmp_name'][$key];

       $name = basename($_FILES['pictures']['name'][$key]);

       move_uploaded_file($tmpName, "/var/www/project/uploads/$name");

   }

}

6. Properly declaring the UPLOAD_ERR and basename() may prevent directory traversal attacks, but few other validations – like file size, file rename and store uploaded files in private location – are also required to strengthen the security of the applications.

7. Use SSL Certificates For HTTPS

All the modern browsers like Google Chrome, Opera, Firefox and others, recommend to use HTTPS protocol for web applications. HTTPs provides a secured and encrypted accessing channel for untrusted sites. You must include HTTPS by installing SSL certificate into your website. It also strengthens your web applications against XSS attacks and prevents the hackers to read transported data using codes.

7. Document Root Setup

The document root for PHP applications on any server must be set to var/www/html so that users can access your website via the browser. But in some cases, when you are developing APIs with frameworks like Laravel, Symfony, and Slim, you need to update the webroot to `/public folder.

/public serves the output of application similar to simple PHP website with index.php file. The purpose to set the webroot to var/www/html/public is to hide the sensitive files like .htaccess and .env which contain the environment variables and credentials of database, mail, payment APIs.

Also, frameworks like Laravel, Symfony recommend to not move all of your files to root folder, instead creating a nice directory structure to save related files like view, models and controllers is a more reasonable approach.

8.Log all Errors and Hide in Production

Once you have developed the website and deployed on live server. The first thing you must do is disable the display of errors, because hackers might get same valuable information from the errors. Set this parameter in your php.ini file:

display_errors=Off

Now, after making display off, log PHP errors to a specific file for future needs:

log_errors=On 
error_log=/var/log/httpd/php_scripts_error.log

Obviously, you can change file name as you want.

9. Whitelist Public IP for Mysql

When working with PHP apps you frequently need to setup mysql database in internal scripts as well as in mysql clients. Most clients are used to set up MySQL remote connection which needs the IP address or other hostname provide by hosting server to create connection.

The public IP for the remote Mysql connection must be whitelisted in your hosting server so that an anonymous user can not get access to the database.

h3>Q: How to test PHP security?

A: There are few code scanner tools available in the market that can help you analyse the code quality and security of your PHP applications. PHP Malware Finder (PMF) is one of the top security testing tools that helps to find malicious codes in the files. You can also use RIPS as well, which is a popular code analysis tool that helps to find code vulnerabilities in real-time.

Q: How to ensure PHP database security?

A: To ensure database security, you should always use practices like SQL injection protection, database firewalls, regular data encryptions and similar others.

Q: Which PHP security cheat sheet is best to follow on?

A: You can find many security cheat sheets available in the community, but this checklist might be the perfect one you can find anywhere as it lists some of the most known PHP security practices.
https://www.sqreen.com/checklists/php-security-checklist