Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / New
Stats: 3,143,235 members, 7,780,447 topics. Date: Thursday, 28 March 2024 at 02:34 PM

Writing Secure PHP - Webmasters - Nairaland

Nairaland Forum / Science/Technology / Webmasters / Writing Secure PHP (2499 Views)

Google To Promote Secure Websites (HTTPS) In Search Results / How To Secure A Blog / Forum - Suspension, Ban Or Hellban? / Wordpress 3.2.1 Is Not Secure So Do Not Upgrade. (2) (3) (4)

(1) (Reply) (Go Down)

Writing Secure PHP by Nobody: 7:49am On Feb 28, 2009
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.
$check = mysql_query("SELECT username, password FROM users WHERE Username = '".$_POST['username']."' and Password = '".$_POST['password']."'"wink;


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).
Re: Writing Secure PHP by Nobody: 7:02pm On Feb 28, 2009
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:

' 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. Immagine!!
Re: Writing Secure PHP by ztyle(m): 7:11pm On Feb 28, 2009
*Sippinq* Coka Cola, . . DHTML and Javascript.
Re: Writing Secure PHP by Nobody: 7:15pm On Feb 28, 2009
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."'"wink;

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.
Re: Writing Secure PHP by Nobody: 7:26pm On Feb 28, 2009
ztyle:

*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.
Re: Writing Secure PHP by Nobody: 7:30pm On Feb 28, 2009
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.
Re: Writing Secure PHP by Nobody: 7:33pm On Feb 28, 2009
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.
Re: Writing Secure PHP by Nobody: 7:36pm On Feb 28, 2009
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.
Re: Writing Secure PHP by Nobody: 7:48pm On Feb 28, 2009
** Pauses to take a deep breath, looks at the time, wondering when the invited guests will start arriving, then strolls off to play ludo ****
Re: Writing Secure PHP by uspry1(f): 8:05am On Mar 01, 2009
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!!!
Re: Writing Secure PHP by Nobody: 8:31am On Mar 01, 2009
uspry1:

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?
Re: Writing Secure PHP by uspry1(f): 8:16pm On Mar 01, 2009
dhtml:

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:

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

https://www.nairaland.com/nigeria/topic-126853.0.html
Re: Writing Secure PHP by nitation(m): 10:52am On Mar 02, 2009
Yea am back after a long weekend.

@DHTML

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
Re: Writing Secure PHP by Nobody: 12:22pm On Mar 02, 2009
@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.
Re: Writing Secure PHP by nitation(m): 2:49pm On Mar 02, 2009
Big boys! ok am sorry. i still fall in the category of the small ones. No vex for me abeg.

Cheers!
Re: Writing Secure PHP by quadrillio(m): 3:02pm On Mar 03, 2009
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.
Re: Writing Secure PHP by Nobody: 9:47pm On Mar 03, 2009
THanks for the contribution quadrillo, me too, i like takin the easy way out, i am tryin to change now anyway.
Re: Writing Secure PHP by Slyr0x: 1:54pm On May 22, 2011
Bump!
Re: Writing Secure PHP by Nobody: 10:13pm On May 22, 2011
whatcha doing digging up mis archivos again? oya, add to this now before i flog you tongue
Re: Writing Secure PHP by Slyr0x: 6:17am On May 23, 2011
I will bro. .buh that will be later wink
Re: Writing Secure PHP by Nobody: 11:00am On May 23, 2011
i will keep pinging this thread until then. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Re: Writing Secure PHP by Slyr0x: 11:24am On May 23, 2011
^^^hahaha. .No P. Ping? Pin?
Re: Writing Secure PHP by sisqology(m): 5:30pm On Feb 07, 2012
*walks around*
Re: Writing Secure PHP by Nobody: 5:39pm On Feb 07, 2012
<p.i.n.g>
Re: Writing Secure PHP by iGuru1(m): 6:16pm On Feb 07, 2012
thanks for these info.
Where are my fellow class mates.
Re: Writing Secure PHP by Nobody: 6:18pm On Feb 07, 2012
^^^Hidin' unda the cocoyam leaves i presuppose.

(1) (Reply)

Webhostilla.com: Buy Domains from #1600 , Unlimited Webhosting From #2400/year / Lets Share And Exchange Dreamweaver Extensions / My Sojourn Into Blogging - A First Hand Experience For Intending Bloggers!!!

(Go Up)

Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health
religion celebs tv-movies music-radio literature webmasters programming techmarket

Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)

Nairaland - Copyright © 2005 - 2024 Oluwaseun Osewa. All rights reserved. See How To Advertise. 52
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.