Top 10 PHP Security Tips for Linux Admins

PHP is one of the most used server scripting programming languages. The market share speaks volumes about its dominance. The fact that PHP 7 is already out makes the programming language more appealing to current developers. Even though the changes have come out, many developers are skeptical about PHP’s future. One reason is PHP security.

PHP security is a primary concern for developers. PHP offers robust security inside out, but it is in the hands of developers to implement them correctly. In this article, we will look at some PHP security tips for Linux admins. The tips will help you secure your Web application and ensure proper functioning in the long run.

Before we start, understanding the system we are working with is necessary. For demonstration purposes, we are using Fedora. However, the tips should work fine with the Ubuntu version or any other Linux distro. Check your OS distro manual for more information.

Let’s go through some of the key files of our setup. In your case, they should be similar or equivalent to the following:

  • Default Web server: Apache
  • DocumentRoot: /var/www/html
  • PHP configuration file: /etc/php.ini
  • Extensions config directory: /etc/php.d/
  • Security file: /etc/php.d/security.ini
  • These tricks will help you protect your Web site from different

types of common attacks, such as SQL injection, XSS, sea-surf attacks, eval(), File uploads, and so forth. Check the common attack list here.

1. Get Rid of Unnecessary Modules

PHP comes with built-in PHP modules. They are useful for many tasks, but not every project requires them. You can view the available PHP modules by typing the following command:

# php – m

Once you get hold of the list, you now can get rid of the unnecessary modules. The reduced number of modules will help you to ramp up the performance and security of the Web application you are working on.

2. Restrict PHP Information Leakage

It is common for platforms to leak vital information. For example, PHP releases information such as versions and the fact that it is installed on the server. This is done through the expose_php directive. To prevent the leak, you need to set the directive to off in /etc/php.d/security.ini.

expose_php=Off

If anyone needs to know the version and its state, a simple run of the Curl command over the Web site address will produce this information.

Curl - I http://www.livecoding.tv/index.php

The preceding command will return the following information:

HTTP/1.1 200 OK
X-Powered-By: PHP/7.0.10
Content-type: text/html; charset=UTF-8

3. Disable Remote Code Execution

Remote code execution is one of the common security flaws in PHP security. By default, remote code execution is enabled on your system. The “allow_url_fopen” directive allows functions such as require, include, or URL-aware fopen wrappers to get direct access to the PHP files. The remote access is done by using HTTP or FTP protocol and can cause the system to be defenseless against the code injection vulnerabilities.

To ensure that your system is secure from remote code execution, you can set the directive “Off”, as shown below:

Allow_url_fopen=Off
allow_url_include=Off

4. Log PHP Errors

Another simple way of tightening the security of your Web applications is to not show errors to the visitors. This will ensure that the hacker in no way can compromise the security of the Web site. The edit needs to be done in the /etc/php.d/security.ini file.

display_errors=Off

Now, you’re probably wondering after this, “How can a developer debug without the help of errors?” Developers can use the log_errors directive for debugging purposes. All they need to do is enable thelog_errors directive to “On” in the security.ini file.

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

5. Control Resources Properly

Controlling resources is important for making your app secure. To ensure proper execution and security, you need to set the limit for PHP script execution. Furthermore, you also may want to set a limit on the time spent on parsing request data. With execution time under control, other resources such as the memory usage by a script should also be configured accordingly. All of these metrics can be managed by editing the security.ini file.

# set in seconds
max_execution_time = 25
max_input_time = 25
memory_limit = 30M

6. Disable Dangerous PHP Functions

PHP comes with useful functions for developmental purposes, but it is also plagued with functions that can be used by hackers to exploit the Web app. Disabling the functions can improve the overall security and ensure that you are not affected by dangerous PHP functions.

To do so, you first need to edit the php.ini file. Once there, find the disable_functions directive and set the dangerous functions in it. You can do it by just copy/pasting the following code.

disable_functions =exec,passthru,
shell_exec,system,proc_open,popen,curl_exec,
curl_multi_exec,parse_ini_file,show_source

You can read more about disabling dangerous PHP functions here.

7. Upload Files

If your app doesn’t require uploading any files, disabling the functionality to upload files can lead to better security. To disable file uploading from users, you need to edit the security.ini file in the /etc/php.d/ directory and set the file_uploads directive to Off.

file_uploads=Off

8. Keep Things Up to Date

Developers are working 24/7 to patch the technology that you are using. PHP is no different. With an open source community surrounding it, patches and bug fixes are released frequently. The updates also offer security fixes for first-day exploits and other security vulnerabilities. If you are serious about the security of your app, always keep your PHP solution up to date. Also, keeping the other associated technology to the latest patch will ensure maximum security.

9. Control File System Access

By default, PHP can access files by using functions such as fopen(). The open_basedir directive provides the access. For starters, always keep the open_basedir directive set to the /var/www/htmldirectory. Setting it to any other directory can lead to security issues.

open_basedir="/var/www/html/"

10. Control the POST Size

Our last PHP security tip is to control the POST size function. The HTTP POST function uses the client’s browser to send data to the Web server. For example, a user can upload a certificate and send it to the Web browser for processing purposes. Everything works fine until one day a hacker attempts to send a huge file size to clog the server resources. This can easily lead to crashes or slow responses from the server. To protect your server from this exploit, you need to set the POST size. The POST size can be set in the /etc/php.d/security.ini file.

post_max_size=1k

Conclusion

Security is one of the biggest concerns for Web developers and Linux administrators. With the preceding tips, you are sure to harden the security around the development environment and the PHP Web app. If you think we missed something important, don’t forget to comment below and let us know.

About the Author

Damian Wolf is an author and tech enthusiast with articles published on top technology & coding Web sites such as InfoWorld, DZone, HongKiat, and more. In addition to working with PHP Web apps, he loves trying out new things: apps, software, and trends, and will gladly share his views.

Top 10 PHP Security Vulnerabilities

Security is not a list of things you do. Security is a way of thinking, a way of looking at things, a way of dealing with the world that says “I don’t know how they’ll do it, but I know they’re going to try to screw me” and then, rather than dissolving into an existential funk, being proactive to prevent the problem.

But, you can’t buck statistics. Nobody is going to read an article entitled “Coding for Security.” Everyone wants an article with a number in it: “The 8 Most Common PHP Security Attacks and How to Avoid Them”, “23 Things Not to Say to a Super Model”, and “15 Reasons to Avoid Radiation Poisoning.” So, here goes, the “Top 10 PHP Security Vulnerabilities.”

SQL Injection

Number one on the hit list is the SQL injection attack. In this case, someone enters an SQL fragment (the classic example is a drop database statement, although there are many possibilities that don’t include deletions which could be just as destructive) as a value in your URL or web form. Never mind now how he knows what your table names are; that’s another problem entirely. You are dealing with an insidious and resourceful foe.

So, what can you do to avoid this? First and foremost you need to be suspicious of any input you accept from a user. Believe everyone is nice? Just look at your spouse’s family… they’re weird and freaky, some dangerously so.

The way to prevent this sort of thing is to use PDO Prepared Statements. I don’t want to go through a full discussion of PDO now. Suffice to say prepared statements separate the data from the instructions. In doing so, it prevents data from being treated as anything other than data. For more info, you might want to check out the article Migrate from the MySQL Extension to PDO by Timothy Boronczyk.

XSS (Cross Site Scripting)

Curse the black hearts who thrive on this type of deception. Parents, talk to you children today lest they become evil XSS’ers!

The essence of any XSS attack is the injection of code (usually JavaScript code but it can be any client-side code) into the output of your PHP script. This attack is possible when you display input that was sent to you, such as you would do with a forum posting for example. The attacker may post JavaScript code in his message that does unspeakable things to your site. Please don’t make me go into detail; my heart weeps at what these brigands are capable of.

For more information and how to protect yourself, I suggest reading these fine articles on PHPMaster:

Source Code Revelation

This one has to do with people being able to see the names and content of files they shouldn’t in the event of a breakdown in Apache’s configuration. Yeah, I dig it, this is unlikely to happen, but it could and it’s fairly easy to protect yourselves, so why not?

We all know that PHP is server side – you can’t just do a view source to see a script’s code. But if something happens to Apache and all of a sudden your scripts are served as plain text, people see source code they were never meant to see. Some of that code might list accessible configuration files or have sensitive information like database credentials.

The solution centers around how you set up the directory structure for your application. That is, it isn’t so much a problem that bad people can see some code, it’s what code they can see if sensitive files are kept in a public directory. Keep important files out of the publicly-accessible directory to avoid the consequences of this blunder.

For more information on this, including a sample of what your directory structure might look like, see point 5 in this article. For additional discussion on this topic, see this forum discussion.

Remote File Inclusion

Hang on while I try to explain this: remote file inclusion is when remote files get included in your application. Pretty deep, eh? But why is this a problem? Because the remote file is untrusted. It could have been maliciously modified to contain code you don’t want running in your application.

Suppose you have a situation where your site at http://www.myplace.com includes the library http://www.goodpeople.com/script.php. One night, http://www.goodpeople.com is compromised and the contents of the file is replaced with evil code that will trash your application. Then someone visits your site, you pull in the updated code, and Bam! So how do you stop it?

Fortunately, fixing this is relatively simple. All you have to do is go to your php.ini and check the settings on these flags.

  • allow_url_fopen – indicates whether external files can be included. The default is to set this to ‘on’ but you want to turn this off.
  • allow_url_include – indicates whether the include(), require(), include_once(), and require_once() functions can reference remote files. The default sets this off, and setting allow_url_fopen off forces this off too.

Session Hijacking

Session hijacking is when a ne’er-do-well steals and use someone else’s session ID, which is something like a key to a safe deposit box. When a session is set up between a client and a web server, PHP will store the session ID in a cookie on the client side probably called PHPSESSID. Sending the ID with the page request gives you access to the session info persisted on the server (which populates the super global $_SESSION array).

If someone steals a session key, is that bad? And the answer is: if you aren’t doing anything important in that session then the answer is no. But if you are using that session to authenticate a user, then it would allow some vile person to sign on and get into things. This is particularly bad if the user is important and has a lot of authority.

So how do people steal these session IDs and what can decent, God-fearing folk like us do about it?

Session IDs are commonly stolen via a XSS attack, so preventing those is a good thing that yields double benefits. It’s also important to change the session ID as often as is practical. This reduces your theft window. From within PHP you can run the session_regenerate_id() function to change the session ID and notify the client.

For those using PHP5.2 and above (you are, aren’t you?), there is a php.ini setting that will prevent JavaScript from being given access to the session id (session.cookie.httponly). Or, you can use the function session_set_cookie_parms().

Session IDs can also be vulnerable server-side if you’re using shared hosting services which store session information in globally accessible directories, like /tmp. You can block the problem simply by storing your session ID in a spot that only your scripts can access, either on disk or in a database.

Cross Site Request Forgery

Cross Site Request Forgery (CSRF), also known as the Brett Maverick, or Shawn Spencer, Gambit, involves tricking a rather unwitting user into issuing a request that is, shall we say, not in his best interest. But rather than me going on and on about CSRF attacks, refer to an outstanding example of just what kind of content we have here on PHPMaster: Preventing Cross-Site Request Forgeries by Martin Psinas.

Directory Traversal

This attack, like so many of the others, looks for for a site where the security is not all that it should be, and when if finds one, it causes files to be accessed that the owner did not plan to make publicly accessible. It’s also known as the ../ (dot, dot, slash) attack, the climbing attack, and the backtracking attack.

There are a few ways to protect against this attack. The first is to wish really, really hard that it won’t happen to you. Sometimes wishing on fairies and unicorns will help. Sometimes it doesn’t. The second is to define what pages can be returned for a given request using whitelisting. Another option is to convert file paths to absolute paths and make sure they’re referencing files in allowed directories.

Summary

Those are the top 10 issues that, if you aren’t careful to avoid, can allow your PHP application to be breached. Yep, 10. Count them… 1, 2, 3… What? You only counted 8? Okay, maybe 7. Well then that shows you just how easily you can be fooled, and I’m not even one of the bad guys!

Leave a comment