Jump to content

[Guide] Secure PHP Coding


L2Αpollon

Recommended Posts

PHP is a very easy language to learn, and many people without any sort of background in programming learn it as a way to add interactivity to their web sites. Unfortunately, that often means PHP programmers, especially those newer to web development, are unaware of the potential security risks their web applications can contain. Here are a few of the more common security problems and how to avoid them.

 

Rule Number One: Never, Ever, Trust Your Users

 

It can never be said enough times, you should never, ever, ever trust your users to send you the data you expect. I have heard many people respond to that with something like "Oh, nobody malicious would be interested in my site". Leaving aside that that could not be more wrong, it is not always a malicious user who can exploit a security hole - problems can just as easily arise because of a user unintentionally doing something wrong.

 

So the cardinal rule of all web development, and I can't stress it enough, is: Never, Ever, Trust Your Users. Assume every single piece of data your site collects from a user contains malicious code. Always. That includes data you think you have checked with client-side validation, for example using JavaScript. If you can manage that, you'll be off to a good start. If PHP security is important to you, this single point is the most important to learn.

 

SQL Injection

 

One of PHP's greatest strengths is the ease with which it can communicate with databases, most notably MySQL. Many people make extensive use of this, and a great many sites, including this one, rely on databases to function.

 

However, as you would expect, with that much power there are potentially huge security problems you can face. Fortunately, there are plenty of solutions. The most common security hazard faced when interacting with a database is that of SQL Injection - when a user uses a security glitch to run SQL queries on your database.

 

Let's use a common example. Many login systems feature a line that looks a lot like this when checking the username and password entered into a form by a user against a database of valid username and password combinations, for example to control access to an administration area:

$check = mysql_query("SELECT Username, Password, UserLevel FROM Users WHERE Username = '".$_POST['username']."' and Password = '".$_POST['password']."'");

Look familiar? It may well do. And on the face of it, the above does not look like it could do much damage. But let's say for a moment that I enter the following into the "username" input box in the form and submit it:

' OR 1=1 #

The query that is going to be executed will now look like this:

SELECT Username, Password FROM Users WHERE Username = '' OR 1=1 #' and Password = ''

The hash symbol (#) tells MySQL that everything following it is a comment and to ignore it. So it will actually only execute the SQL up to that point. As 1 always equals 1, the SQL will return all of the usernames and passwords from the database. And as the first username and password combination in most user login databases is the admin user, the person who simply entered a few symbols in a username box is now logged in as your website administrator, with the same powers they would have if they actually knew the username and password.

 

With a little creativity, the above can be exploited further, allowing a user to create their own login account, read credit card numbers or even wipe a database clean.

 

Fortunately, this type of vulnerability is easy enough to work around. By checking for apostrophes in the items we enter into the database, and removing or neutralising them, we can prevent anyone from running their own SQL code on our database. The function below would do the trick:

function make_safe($variable) { $variable = mysql_real_escape_string(trim($variable)); return $variable; }

Now, to modify our query. Instead of using _POST variables as in the query above, we now run all user data through the make_safe function, resulting in the following code:

$username = make_safe($_POST['username']); $password = make_safe($_POST['password']); $check = mysql_query("SELECT Username, Password, UserLevel FROM Users WHERE Username = '".$username."' and Password = '".$password."'");

Now, if a user entered the malicious data above, the query will look like the following, which is perfectly harmless. The following query will select from a database where the username is equal to "\' OR 1=1 #".

SELECT Username, Password, UserLevel FROM Users WHERE Username = '\' OR 1=1 #' and Password = ''

Now, unless you happen to have a user with a very unusual username and a blank password, your malicious attacker will not be able to do any damage at all. It is important to check all data passed to your database like this, however secure you think it is. HTTP Headers sent from the user can be faked. Their referral address can be faked. Their browsers User Agent string can be faked. Do not trust a single piece of data sent by the user, though, and you will be fine.

 

Using Defaults

 

When MySQL is installed, it uses a default username of "root" and blank password. SQL Server uses "sa" as the default user with a blank password. If someone finds the address of your database server and wants to try to log in, these are the first combinations they will try. If you have not set a different password (and ideally username as well) than the default, then you may well wake up one morning to find your database has been wiped and all your customers' credit card numbers stolen. The same applies to all software you use - if software comes with default username or password, change them.

Leaving Installation Files Online

 

Many PHP programs come with installation files. Many of these are self-deleting once run, and many applications will refuse to run until you delete the installation files. Many however, will not pay the blindest bit of attention if the install files are still online. If they are still online, they may still be usable, and someone may be able to use them to overwrite your entire site.

 

Predictability

 

Let us imagine for a second that your site has attracted the attention of a Bad Person. This Bad Person wants to break in to your administration area, and change all of your product descriptions to "This Product Sucks". I would hazard a guess that their first step will be to go to http://www.yoursite.com/admin/ - just in case it exists. Placing your sensitive files and folders somewhere predictable like that makes life for potential hackers that little bit easier.

 

With this in mind, make sure you name your sensitive files and folders so that they are tough to guess. Placing your admin area at http://www.yoursite.com/jsfh8sfsifuhsi8392/ might make it harder to just type in quickly, but it adds an extra layer of security to your site. Pick something memorable by all means if you need an address you can remember quickly, but don't pick "admin" or "administration" (or your username or password). Pick something unusual.

 

The same applies to usernames and passwords. If you have an admin area, do not use "admin" as the username and "password" as the password. Pick something unusual, ideally with both letters and numbers (some hackers use something called a "dictionary attack", trying every word in a dictionary as a password until they find a word that works - adding a couple of digits to the end of a password renders this type of attack useless). It is also wise to change your password fairly regularly (every month or two).

 

Finally, make sure that your error messages give nothing away. If your admin area gives an error message saying "Unknown Username" when a bad username is entered and "Wrong Password" when the wrong password is entered, a malicious user will know when they've managed to guess a valid username. Using a generic "Login Error" error message for both of the above means that a malicious user will have no idea if it is the username or password he has entered that is wrong.

 

File Systems

 

Most hosting environments are very similar, and rather predictable. Many web developers are also very predictable. It doesn't take a genius to guess that a site's includes (and most dynamic sites use an includes directory for common files) is an www.website.com/includes/. If the site owner has allowed directory listing on the server, anyone can navigate to that folder and browse files.

 

Imagine for a second that you have a database connection script, and you want to connect to the database from every page on your site. You might well place that in your includes folder, and call it something like connect.inc. However, this is very predictable - many people do exactly this. Worst of all, a file with the extension ".inc" is usually rendered as text and output to the browser, rather than processed as a PHP script - meaning if someone were to visit that file in a browser, they'll be given your database login information.

 

Placing important files in predictable places with predictable names is a recipe for disaster. Placing them outside the web root can help to lessen the risk, but is not a foolproof solution. The best way to protect your important files from vulnerabilities is to place them outside the web root, in an unusually-named folder, and to make sure that error reporting is set to off (which should make life difficult for anyone hoping to find out where your important files are kept). You should also make sure directory listing is not allowed, and that all folders have a file named "index.html" in (at least), so that nobody can ever see the contents of a folder.

 

Never, ever, give a file the extension ".inc". If you must have ".inc" in the extension, use the extension ".inc.php", as that will ensure the file is processed by the PHP engine (meaning that anything like a username and password is not sent to the user). Always make sure your includes folder is outside your web root, and not named something obvious. Always make sure you add a blank file named "index.html" to all folders like include or image folders - even if you deny directory listing yourself, you may one day change hosts, or someone else may alter your server configuration - if directory listing is allowed, then your index.html file will make sure the user always receives a blank page rather than the directory listing. As well, always make sure directory listing is denied on your web server (easily done with .htaccess or httpd.conf).

 

I will update guide from time to time with more information as i work in that part of systems engineering, especially php developing.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



  • Posts

    • Instead of using encedc on it, try renaming it to "Icon.u" instead of "Icon.utx", and put it in your System folder. If it still crashes, the problem might be with your unrealed.
    • How's the project doing? Is there any news? It really interesting 🤔
    • thx for answer, i tried and woks encrypting, but i still having crashes 😞 i changed the icon in skillgrp.dat from "icon.skill0003" to "Myicons.misil" as i saved the file before endec and nothing. this is the report i got
    • New Season coming May 2024! First post updated      Website: L2Kain.net  Discord: https://discord.gg/l2kain  Wiki: https://info.kain.ws/   Important Dates   Server Start: TBD  Open Beta Test: 10th of May 2024!   Basic Information     Briefly about the concept of the server! We decided to move away from the standard Mid-Rate server concept and keep the mechanics of our beloved Lineage 2 that everyone loves! Massive battles for epic bosses, battles for profitable farming locations, resource spoilage and equipment crafting, daily instances, a balanced economy and much more. This server is build as a Craft-PvP concept. The goal is to gather players with a variety of preferences in the game and make a high-quality and interesting server with alternative character development options. We are well aware that "grinding" is an integral part of the game, but we diluted the boring and the same type of farming with interesting solutions and non-standard mechanics!   We have prepared a new High Five x25 on Modern Client for you. This server will be another step in the development of the platform and the project as a whole! Your appeals to those. support was not ignored, which means the new server will be even better than the previous one!      ⭐ Promotions and Bonuses for new players!     ⭐ Events and Giveaways daily!   ⭐ Rewards for Voting!   ℹ️ Server Rates Learn more about server rates! Server rates are configured in such a way that farming is best rewarded. Adena, drops, quests, various rewards and prices in the game store are well balanced among themselves!   Basic Server Rates:  ⭐ Experience & Skill Points - x25  ⭐ Adena Drop - x15 & Fixed Chance 66%  ⭐ Drop Rates - x10  ⭐ Spoil Rates - x10   Crafting keys, recipes drop & spoil with fixed amount from 2 to 3 and increased chances on all locations and quests  related to farm them.  ⭐ Quest Rates - x5  ⭐ Fortresses & Sieges - x5  ⭐ Raid Bosses & Epic Bosses - x1  ⭐ Weight Limit - x10      Connect with Us:  Discord: https://discord.gg/l2kain  Facebook: https://www.facebook.com/KainLineage2  TikTok: https://www.tiktok.com/@l2kain.net  YouTube: https://www.youtube.com/@Lineage2Kain
  • Topics

×
×
  • Create New...