Writing Secure PHP

Welcome. Please Login, Register, Or Activate! 
type your username and password to login
Date: November 23, 2009, 11:50 PM
431567 members and 298583 Topics
Latest Member: Unpaketanteem
Nairaland [Nigerian Forum] Home Help Search Who is currently online? Login Register
Nairaland Forum  |  Technology  |  Webmasters (Moderators: OmniPotens, yawa-ti-de)  |  Writing Secure PHP
Pages: (1) Go Down Send this topic Notify of replies
Author Topic: Writing Secure PHP  (Read 308 views)
*dhtml
Writing Secure PHP
« on: February 28, 2009, 07:49 AM »

Now with all these great tutorials going on. Javascript logins, php logins, spoofing, cookie soiling,

Time to take action. This is going to be an interactive session. Contributions are welcome
because on the grounds we are threading, there are lots of controversies.
I am not here to argue that i am berra than u and stuffs like that. If you know any better method than
whatever i post, please say it, if there are shortcomings (i do have lots of shortcomings - no need to rub it in),
please say it. Just dont criticize my codes without providing corrections (most important) and think i will
let you just walk away like that!

This is a favorite php login script.
Code:
$check = mysql_query("SELECT username, password FROM users WHERE Username = '".$_POST['username']."' and Password = '".$_POST['password']."'");

As an introduction, i want to know why that method is not safe, and if it is not, what do we do about it.

And i will welcome participation from the other php programmers here: yawatide, webdezzi, nitation, quadrillo, omnipotens and
others too.
And i will also like to apologize for my loud mouth in the previous thread (guess i need to develop a thicker skin afterall).
I really need you guyz to contribute here positively especially nitation (this i think is one of your strong points).

*dhtml
Re: Writing Secure PHP
« #1 on: February 28, 2009, 07:02 PM »

The php / mysql code stated above is not secure at all. It may look harmless but it is very risk thing to use.

The problem with this code is that it can be hacked very easily through what is called SQL Injection

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:


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:

Quote
' OR 1=1 #
The query that is going to be executed will now look like this:

Quote
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. Immagine!!

ztyle (m)
Re: Writing Secure PHP
« #2 on: February 28, 2009, 07:11 PM »

*Sippinq* Coka Cola, . . DHTML and Javascript.
*dhtml
Re: Writing Secure PHP
« #3 on: February 28, 2009, 07:15 PM »

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:

Quote
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:

Quote
$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 #".

Quote
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.

*dhtml
Re: Writing Secure PHP
« #4 on: February 28, 2009, 07:26 PM »

Quote from: ztyle on February 28, 2009, 07:11 PM
*Sippinq* Coka Cola, . . DHTML and Javascript.
how dare you dare you dare you sip coka cola on my thread?? huh??
If i had the gunz like seun, ama gonna blaze you right outta this thread!!

Phew, tough isn't it. Lemme continue while we await the other invitees.
We will be talking next about file manipulation bugs and fixes.
*dhtml
Re: Writing Secure PHP
« #5 on: February 28, 2009, 07:30 PM »

File Manipulation

Some sites currently running on the web today have URLs that look like this:

index.php?page=about.html
The "index.php" file then simply includes the "about.html" file, and the site appears to work. However, the user can very easily change the "about.html" bit to anything they like. For example, if you are using Apache's mod_auth to protect files and have saved your password in a file named ".htpasswd" (the conventional name), then if a user were to visit the following address, the script would output your username and password:

index.php?page=.htpasswd
By changing the URL, on some systems, to reference a file on another server, they could even run PHP that they have written on your site. Scared? You should be. Fortunately, again, this is reasonably easy to protect against. First, make sure you have correctly set "open_basedir" in your php.ini file, and have set "allow_url_fopen" to "off". That will prevent most of these kinds of attacks by preventing the inclusion of remote files and system files. Next, if you can, check the file requested against a list of valid files. If you limit the files that can be accessed using this script, you will save yourself a lot of aggravation later.
*dhtml
Re: Writing Secure PHP
« #6 on: February 28, 2009, 07:33 PM »

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.

This happens with some cms applications.
*dhtml
Re: Writing Secure PHP
« #7 on: February 28, 2009, 07:36 PM »

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.
*dhtml
Re: Writing Secure PHP
« #8 on: February 28, 2009, 07:48 PM »

** Pauses to take a deep breath, looks at the time, wondering when the invited guests will start arriving, then strolls off to play ludo ****
uspry1 (f)
Re: Writing Secure PHP
« #9 on: March 01, 2009, 08:05 AM »

Dhtml, I am glad you have now learned the depth of SQL Injection from other forum you saw.

Keep up your PHP programming skills!

Psssst! Give you a hint which forum I talk about! By the time when you turn 40s, there will be hologram generation! Smile!!!
*dhtml
Re: Writing Secure PHP
« #10 on: March 01, 2009, 08:31 AM »

Quote from: uspry1 on March 01, 2009, 08:05 AM
Dhtml, I am glad you have now learned the depth of SQL Injection from other forum you saw.

Keep up your PHP programming skills!

Psssst! Give you a hint which forum I talk about! By the time when you turn 40s, there will be hologram generation! Smile!!!
You have no idea . . .

@everyone:
The thing about this thread is that, everything i have talked about can be done by an average php programmer, just that some of us (like me), usually prefer to take the easy way out.
There is really no new codes here, just an application of what is already existing. Though i have used some of these techniques to spoof before - like the http referer for instance - which i used to think was the easy way out - never knew browser strings/headers can be faked.

I actually created this thread as a sequela of my thread on Form Validation Tutorial Using Javascript, Php And Ajax!, which i just completed. because i did not talk about security in that thread, i decided to make this a reference point in some of my other threads.

And there is still something i have not been able to understand how to protect against. Session cookies being sniffed over the network - how do we protect against those ones? Please someone should enlighten me.

Now i am wondering why the invited guests are not yet around sef, is the lagos traffick dat bad?? or the invitations don lost for road?
uspry1 (f)
Re: Writing Secure PHP
« #11 on: March 01, 2009, 08:16 PM »

Quote from: dhtml on February 28, 2009, 07:30 PM
File Manipulation

Some sites currently running on the web today have URLs that look like this:

index.php?page=about.html
The "index.php" file then simply includes the "about.html" file, and the site appears to work. However, the user can very easily change the "about.html" bit to anything they like. For example, if you are using Apache's mod_auth to protect files and have saved your password in a file named ".htpasswd" (the conventional name), then if a user were to visit the following address, the script would output your username and password:

index.php?page=.htpasswd
By changing the URL, on some systems, to reference a file on another server, they could even run PHP that they have written on your site. Scared? You should be. Fortunately, again, this is reasonably easy to protect against. First, make sure you have correctly set "open_basedir" in your php.ini file, and have set "allow_url_fopen" to "off". That will prevent most of these kinds of attacks by preventing the inclusion of remote files and system files. Next, if you can, check the file requested against a list of valid files. If you limit the files that can be accessed using this script, you will save yourself a lot of aggravation later.

There is other way to hide "about.html" not to display public is Apache mod_rewrite. Here are existing posts as follow below:

http://www.nairaland.com/nigeria/topic-131075.0.html

http://www.nairaland.com/nigeria/topic-126853.0.html
nitation (m)
Re: Writing Secure PHP
« #12 on: March 02, 2009, 10:52 AM »

Yea am back after a long weekend.

@DHTML
Code:
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 soilers 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.

I sincerely believe you haven't soiled before for whichever reason. No offense though. A potential hacker would first of all scan your IP before laying any attack. He/she would do this to record any open ports available on your system (site).

The attacker would crawl for website for all available files/folders directories etcetera. So there wouldn't be a need to manually type folder names to the url for name guessing.

Lastly, I would strongly advice you to teach your "students" about hashes. MD5- salting etc.

Again folks, welcome back ~

-nitation
*dhtml
Re: Writing Secure PHP
« #13 on: March 02, 2009, 12:22 PM »

@nitation, notice that i emboldened your name in the first post. This area is for the big boys. Now about the encryption systems, we will still get to that one later.
@uspry, thanks for the contribution too.

@everyone especially newbies, hope you are watching. So beyond validation, submission and all that, there is still more to it. We will continue this later.
nitation (m)
Re: Writing Secure PHP
« #14 on: March 02, 2009, 02:49 PM »

Big boys! ok am sorry. i still fall in the category of the small ones. No vex for me abeg.

Cheers!
quadrillio (m)
Re: Writing Secure PHP
« #15 on: March 03, 2009, 03:02 PM »

I first had about SQL injection when I started learning MYSQL (I didn't take it much serious, cos like u said earlier WE ALWAYS WANT TO FIND A SHORTCUT), but when u mentioned it.

I decided to make more research on ways to protect my database.

hopefully I will start a thread on my findings and other ways which we had endanger our data.

and also advised fellow webmasters on the best way out

Nice Job.
*dhtml
Re: Writing Secure PHP
« #16 on: March 03, 2009, 09:47 PM »

THanks for the contribution quadrillo, me too, i like takin the easy way out, i am tryin to change now anyway.
 .ng Domain And General Aparthy  Nairahost.com? Anyone?  Nigeria Facebook Developers Garage  Page 2
Pages: (1) Go Up Send Topic to Friend by E-mail Reply 


Sections: Autos/Cars (2) Jobs/Vacancies (2) (3) Career Talk Education General(2) Politics Romance Computers Phones Travel
Sports Fashion Health Religion Celebrities TV/Movies (2) Music/Radio (2) Books Webmasters Programming

Links: Page1 Page2 Page3 Page4 Page5 Page6 Page7 Page8 Page9 Page10

Nairaland is owned by Oluwaseun Osewa. See also: Nairalist Classified Ads
Nairaland Forum | Powered by SMF 1.0.12.
© 2001-2005, Lewis Media. All Rights Reserved.