Slashdot Log In
PHP and SQL Security
Posted by
CmdrTaco
on Tue Apr 27, 2004 09:38 AM
from the getting-your-edumacation dept.
from the getting-your-edumacation dept.
An anonymous reader writes "PHP and SQL
Security are being proven more weak every day. Uberhacker.Com is running a PHP
and SQL security research
project to raise awareness of secure scripting. The site hosts guides
to secure PHP programming, forums, and scripting
challenges to see who can create the most secure scripts."
This discussion has been archived.
No new comments can be posted.
The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
A bad workman blames his tools (Score:5, Insightful)
Re:A bad workman blames his tools (Score:5, Insightful)
The same is valid for programming languages, with some it's just easier to shoot yourself in the foot when you make a mistake. One example are buffer overflows and C: it's so easy to mistakenly write code that produces one, while in other languages like Ada or Perl it's virtually impossible.
The same goes for PHP and SQL, which is shown everyday on the usual mailing lists like Bugtraq or full-disclosure.
Parent
Re:A bad workman blames his tools (Score:3, Informative)
Yes, of course. A good workman would never willingly use such a dangerous tool!
That being said, as far as SQL security goes, PHP fares far better than its competitor, ASP.
Indeed, by default, PHP comes with gpc_magic_quotes enabled, which prevents the more obvious SQL injection attacks. Of course, nothing is 100% foolproof, but we're nowhere near the sieve that
Re:A bad workman blames his tools (Score:4, Informative)
No, no, no, no, no!
magic_quotes_gpc is totally broken. For those unfamiliar, it escapes all HTTP GET and POST strings MySQL-style. But this is stupid. How you want your strings escaped (if you do at all!) depends on where you are sending them to, not where you are getting them from. Consider these things you might be doing with the strings:
PHP has a shiny red button that you never want to press. This is one of many reasons that I say PHP is a broken tool.
Parent
Re:A bad workman blames his tools (Score:3, Insightful)
I would if he ignored the instructions telling him to protect himself before using it after hearing the horror stories from the large collection of one armed men (watch out Dr Richard Kimble) in the building!
Re:A bad workman blames his tools (Score:3, Funny)
I wonder if anyone else watches Norm that reads
Re: cutting off an arm (Score:5, Interesting)
Or would you blame the workman who cuts off his arm with the buzz saw's totally unprotected blade?
Yes, I would: he was obviously doing something with the saw that was inappropriate; what saw-oriented task [when done correctly] involves waving it at one's own arm?* The fact that the blade was unprotected is irrelevant since he should have known it was unprotected and therefore dangerous. All tools can be used stupidly, and oddly enough the results really can be the fault of the operator. It is also possible for fault to lie in more than one area.
Yes, I know the traditional definition of 'hacking' includes making $ITEM do something it was not intended to do, but there are limits.
* I'm guessing that 'buzz-saw' == 'circular saw'.
Parent
Re: cutting off an arm (Score:5, Insightful)
> Yes, I would: he was obviously doing something with the saw that was inappropriate
Yeah, that's pretty much the line of the discredited 19th century factory-owners. They all insisted that worker injureries were due to carelessness on the part of the worker. Then people began to noticed that eventually almost all workers became completely disabled. About that time folks began to realize that a tool that requires you to be perfect 100% of the time is a flawed tool. Or a self-mutilation device, you pick.
And the same arguement keeps resurfacing, btw. Not just among factory owners trying to preserve maximum profitability. But also amoung techies trying to defend crappy products:
- RTFM
- can't get a printer to work with cups? must be a newbie
blah, blah, blah
Then in the late 90s Usability and Information Architecture really took off. These guys saw a a few patterns:
- the jack-assed argument that difficulty with a tool was the user's fault - resulted in lost users, lost sales, lost revenue. Those who insisted on blaming the workman rather than the tool - thankfully went out of business.
- usability challenges also caused security vulnerabilities - when users couldn't figure out how to secure a device it became a liability to everyone. So, in this case the tool harmed the entire community not just one workman.
The only interesting thing in the above comment is that you actually got modded-up for repeating a completely discredited notion. Sigh, probably just a clever troll and I fell for it...
Parent
Re:Blame should be shared between coder and langua (Score:3, Insightful)
They're called stored procedures. They've existed for at least 20 years.
No. (Score:5, Insightful)
Essentially, the problem is with those making insecure scripts, not the whole PHP and SQL system.
Re:No. (Score:3, Insightful)
Re:No. (Score:5, Insightful)
Security comes from simplicity, not complexity. And security should start at the DBMS level, not be left to applications.
Parent
Bind variables (Score:3, Insightful)
Writing al=execute_query("SELECT access_level FROM user WHERE user=? AND password=?", user, password) is naturally so much more secure than al=execute_query("SELECT access_level FROM user WHERE user='"+user+"' AND password='"+password+"'");
Nowadays, most database products worth their salt (Oracle, Postgresql, and even my Mysql!) support bind variables. And even if you have an old version of Mysql (which doesn't support them), Perl D
Re:No. (Score:5, Insightful)
No! No, no, no. You don't look for characters that "could lead to injection" and block (or escape) them, you look for input patterns that you know to be safe (ones that can't lead to injection) and only allow those. Trying to guess every possible input that can cause problems is not a good security practice. Please reread Writing Secure Code.
Parent
Hoppity Hop (Score:3, Informative)
One of the problems is that PHP has kept changing the way it handles session variables such that if you move your site you may encounter problems (it takes some sites a while to upgrade their PHP interpreter). One solution is to make your own set of session var functions (scalar only) to wrap the changes or per-site differences, or simply live with register_globals on.
Maybe in a few years it will settle down, but the recent changes have gu
Re:No. (Score:4, Informative)
I've got a couple of rules I try to abide by - can anyone confirm if they're good programming practice? If they are, then they might prove useful to other people.
Parent
Re:No. (Score:5, Informative)
Good. You are off to the right start, but with better function programming, you will find yourself writing more feature code than purification code.
Things to look for:
Protects against SELECT SQL injection attacks.
> becomes >
< becomes <
$data = base64_encode(gzdeflate($data));
This will prevent the problems with escaping quotes and apostrophes for SQL, and it will kill any SQL injections in your data.
if($this) {perform action}... will limit your chances of having to cope with scipt injections because you are only testing for the existence of a condition, and not the value of the data.
> Always escape text which is going into an SQL query
/tmp/, because that narrows down hack attempts, making it all the more harder to compromise the system.
I prefer to write my own SQL text, based on input values. That way you are never using data submitted for the SQL query. The only time they would really submit values would be when they are sending in a username and password, but in that case, you should be extremely stringent in purification by only accepting alphanumeric usernames and passwords (ie: run the alphabet function above, but erase all non-alphanumeric chars from the $ALPHABET var).
> Use htmlspecialchars() on any text that's being output, to stop users putting rogue HTML
htmlspecialchars() doesn't always work. I prefer using the example above, by limiting the characters allowed and disallowing HTML in the form of post body/subject data. Converting everything to base64 will make it nearly impossible to script attack the database, too.
> Put database usernames, passwords, pathnames and other similarly important but site-specific data in a define()
I disagree, because I use the $_SESSION array instead, which can not be changed by a user if the session cookie is server-side. Sessions can be scooped by sniffers, but that can be managed by your host's security, to prevent it. Certainly change the locale for session data from
> Never include() or require() something that isn't a hard-coded string
To me, this isn't totally required if you have suitable purification, but that extra bit of paranoia is welcomed, because it shows true fear and that is acceptable in any kind of programming. That sort of humility is welcomed because it demonstrates a compassion for the task at hand.
> Be hugely care
Parent
Re:No. (Score:5, Informative)
every thing that comes from the user needs to be scrubbed, bleached, hammered and then finally used when you know it is 100% safe. and it must be used in a safe manner.
what blows my mind is those that use the DB column name in a webform to be passed.. Oh nice. select from that drop down item_number and simply change it to start playing corrupt the database games.
Nothing that is ever given to the user, or recieved from the user should be trusted... EVER. that is the first rule and needs to be pounded into everyone in every book about any programming language for the first 5 chapters.
start there and you will heve very little security issues.
Parent
Re:No. (Score:4, Insightful)
what blows my mind is those that use the DB column name in a webform to be passed.
Along the same vein: I cannot count the number of scripts I've seen which use <select> tags and simply assume in the processing script that the only possible values are those which were given in <option> tags. Ditto for text inputs with a maxlength.
It all stems from a complete ignorance of the specs, or a bunch of reading-between-the-lines which is utterly stupid. Nowhere in the HTML spec does it say that the page referenced in a form action will always be requested with valid input.
The other thing which irritates me is how so many people assume using mysql_ functions is the best way to talk with a database. The PEAR project has had a fully-functional, object-oriented database package for years which handles escaping all by itself. It also makes INSERT/UPDATE queries much easier to write with its auto-queries.
In my opinion, this is the tutorials' fault. But it's kind of the same with any language, I suppose: everybody learns C with the standard library and with fixed-length char[] arrays, without learning all the pitfalls (i.e., buffer overflows) and other libraries (i.e., glib) which work around them.
Proper layering and abstraction should be a primary focus of any intro-to-programming class or tutorial.
Parent
Walked Right Into That (Score:3, Insightful)
No, not really. If you're arguing that Windows isn't insecure (which is slightly off-topic) I would have to disagree. The security flaws in Windows are due to over-complication of a proprietary system, leading to gaping holes that keep springing up on a systemic level; these holes are compounded by closed source, financial rationale (lacking in m
Ease of introduction (Score:5, Insightful)
"more weak"? (Score:5, Funny)
Should I submit this one? (Score:5, Funny)
<?php
echo "Hello World!";
?>
Re:Should I submit this one? (Score:5, Funny)
<a href="$PHP_SELF?command=date">Click here to see the date</a>
<?php
if ($command) echo system($command);
?>
Thanks,
Phillip.
Parent
magic_quotes (Score:5, Funny)
Re:magic_quotes (Score:3, Interesting)
at least with PEAR::DB now, i can finally do:
$db->query(select * from foo where a = ?", $a)
and not worry
I can't take a security sight seriously that... (Score:5, Funny)
Re:I can't take a security sight seriously that... (Score:4, Interesting)
and to boot are they running php as a CGI instead of a module?
*shrug*
e.
Parent
Re:I can't take a security sight seriously that... (Score:5, Funny)
Parent
PHP is as secure as you make it (Score:4, Insightful)
PHP documentation clearly states the pitfalls of using variables in a global scope. It is for this reason that PHP changed its GLOBAL array structure to read $_POST and $_GET methods, as well as default setting register_globals to off.
I find it a poor use of a developers time to attempt to see whose site they can deface. It is imoral and shows a lack of respect for those whom put countless hours into their site development.
I would challenge "UBERHACKER" to spend more time developing their website which is showing to be in poor syntatical use of HTML, slow loading and poor in URL design. Why run a php scritp in a
http://uberhacker.com/cgi-bin/index.php?page=fl
Pick up any book on programming and learn proper developmental tactics ( Throw / Catch ) before promoting the attack of others because your 'Uber' site thinks it can't be Hax0r3d.
End Rant.
Re:PHP is as secure as you make it (Score:3, Insightful)
Last time I checked, PERSONAL morals and ethics weren't defined by the actions of others or whether you "respected" someone or not. You're either moral or not. Nobody can "earn" your morality.
C'mon, Drop the FUD (Score:5, Insightful)
MySQL is not SQL (Score:3, Insightful)
SQL is a language, defined by ISO. MySQL is not SQL-compliant. Not even Oracle is. IBM DB2, PostgreSQL are SQL compliant, and a lot better than MySQL too. PostgreSQL is even faster and simpler.
Guides to Secure Programming? (Score:5, Informative)
Re:Guides to Secure Programming? (Score:5, Informative)
I have a few articles on my Web site that might be informative: http://shiflett.org/articles [shiflett.org]
I'm also writing a monthly PHP security column in php|architect [phparch.com], and these articles will be available for free six months after publication.
Lastly, I am writing PHP Security for O'Reilly, which is due out in the fall.
Parent
404d! (Score:5, Funny)
Bad Design Überalles.
SQL injection 101 ... (Score:5, Funny)
People! Remember the quotes! Do:
delete from table where id = '$var'
Not:
delete from table where id = $var
Try for $var = "10 and id = 11 and id = 12 ...".
zRe:SQL injection 101 ... (Score:3, Informative)
SQL Injection in PHP (Score:5, Informative)
An example:
It's easy to inject some malicious SQL when using the following PHP code:
mysql_query("INSERT INTO FOO('Bar') VALUES('$some_post_param');");
But if you prepare the SQL statement with parameters and bind the variable $some_post_param to the statement, it will be secure.
see mysql manual for mysqli_stmt_bind_param() aka bind_param [php.net]
$stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)"); $stmt->bind_param('sssd', $code, $language, $official, $percent);
I know this concept from Perl DBI, but in PHP I haven't seen anyone (phpBB,
As for general webserver security: use PHP and perl as cgi, use suEXEC, run the webserver as nobody/www, put the users into chroot jails, but by all means, don't use PHP safe_mode On.
Re:SQL Injection in PHP (Score:3, Informative)
The reason is that the function you reference is only available in ext/mysqli [php.net], and this requires MySQL 4.1 or greater. There was previously no way to bind parameters like this using PHP and MySQL.
Also, phpBB is not a good example to use with regard to secure programming practices. It is one of the applications that give people this silly notion th
Crap site (Score:3, Interesting)
That being said, I used to write a lot of PHP (I rarely do it anymore at work, but I still try to keep up with the language) and when I first started out I would have loved a comprehensive and easy-to-understand guide to common security holes. The world needs a simple "how to write security-conscious code" for beginners! The sooner you get to see stuff like SQL injection or XSS in action, the better.
Secure Programming HOWTO (Score:5, Informative)
Input verification (Score:3, Interesting)
So far the most "unsafe" aspect with PHP / SQL setups is poor input validation;
If you allow direct writing to your SQL and don't do sufficient checks on the input, well.. you'll get in probs with that.
Proof of concept;
Hello.. enter your email for free porn: sucker@hotmail.com '; DROP TABLE 'emails';
Or you have those pages who mess up or display info which can be abused (and / or shouldn't be on that particular page) after there's a "<blockquote>" injected and redisplayed without checking..
Same with <input type=text>
Then.. there's JS, and htmlentities, and, and..
All caffeine intense, and headache inducing subjects you should keep in mind if you plan on bringing something on wire.
"Nah.. you don't have to do that.. Who's going to know how to do that?"
"Trust me.. You want me to put in that extra code.."
"If you really say so.."
You also have stupid defaults, and uninspired [google.com] coding which gets abused, ofcourse...
I actually like the PHP / SQL combination and believe it to be safe enough for what I do with it.
This was modded up? (Score:3, Informative)
PHP/MySQL is not really that unsecure. If you don't do stupid things, you won't (generally) get hacked.
Nope (Score:5, Insightful)
This is not an issue dealing with PHP and MySQL, this is an issue with weak programmers writing bad code [phpnuke.org], and I'm sorry to say, you find it in every language. As a regular in #php [hashphp.org] on freenode [freenode.net], we are constantly correcting bad coding practices.
In fact, it's not uncommon to find people using GET and POST variables straight out of the box without any kind of validation whatsoever. Many people do not learn the de-facto first rule of web programming: the user can not, and should never be trusted.
To make matters worse, applications like PHP-Nuke spring up which are notorious for sloppy coding practices, and people tend to see them as reflect on the PHP community as a whole. That's like blaming the C language because someone, one day, wrote some bad code in it that got someone else hacked. This happens all the time, but we don't make claims like "C security is weak". Instead, we worry about the truth of it, that the programmer in question did a bad job, or just flat out missed something.
One of the key points that seems to trip most novices up (and granted, this is one of the stupider moves presented by the PHP Core Development team) was a thing called magic_quotes_gpc [php.net], which attempts to auto-escape incoming GET, POST and COOKIE variables in an attempt to sanitize user input. This is usually a double-edge sword because newbies are typicly not aware if it is, or isn't on. In later versions, this is on by default, and does prevent many SQL injections from occuring. However, for the more experienced user, having your input auto-munged can be something of a pain. Unfortunatly, to write truely portable code one must test this value [php.net] and normalize data accordingly.
The issues don't stop there though. I've seen many a more serious faux pas committed by the newbie. Another more serious flaw that I see happen on a regular basis is the use of user data within include statements without proper path checking. This is probably one of the more disasterous errors I see occuring because it typicly exposes sensitive data. There has been more than one occasion where i've shown a user their own passwd file in a browser to make my point.
Anyhow, to the newbies: we, the more experienced people of PHP are on our own quest to educate people, many times in a one-on-one basis on Freenode. If you're not sure about a particular issue, grab an IRC client [xchat.org] and ASK US (irc://irc.freenode.net). We're there to help!
Not sure if this is news (Score:5, Interesting)
Some of my favorite things I see _ALL_ the time:
Something bad happens while executing the code?
Let's <? die("here's my database connection info in case you wanted it"); ?>
Then there was the client who's previous developer was some moron who stored the database connection info into a
The web "design" group who's MySQL database was wide open without authorizing with a password.
The arsehole developers who built themselves little backdoor webpages during development to exec shell commands and upload/exec files
I've seen about 3 websites store credit card numbers unencrypted into a MySQL database.
I could go on and on and on, being a development gun for hire since 98, I've seen some things that defy all logic and explanation. In fact, I still wonder why they call it Computer Science. Now, Computational Arts I could buy into.
A new approach is needed (Score:4, Informative)
So I think a new approach is needed. One where you don't mix instructions and data so easily, or flag them more readily.
With SQL, this has been around for a while: bind variables. Your SQL queries tend to be static with ? thrown in (or :foo for named bind variables). In Perl, it looks like:
Not everyone is using bind variables, and I don't know why. One reason may be that positional bind variables can be confusing: they require you to correlate two lists in your head to position the correct variables in the correct spots. Not all language/database combos support named bind variables. (JDBC doesn't!) But they can be emulated - that's one reason I made xmldb [slamb.org].
For HTML, it's more rare to find something that does this. Apache Cocoon does, but it's grotesquely complex. I'm working on a simpler system [slamb.org], though it's not ready for production. Here's the idea: my files (XFP) are to a SAX ContentHandler [sun.com] as JSP is to a byte stream.
I like SAX because it's a way of making XML that does things right. Instead of doing something like:
you write something like:it's nice in that you don't do any of the escaping yourself - you just tell it how you're using each string, so it can do the escaping right. But that's six ugly lines instead of one, and it's worse with real SAX because you need extra arguments for namespaces and things. So I looked at JSP. It sticks Java code inside the text to produce. I stick Java code inside the XML to produce. I write something like this:...and it turns it into the code above when it makes aMy code is all Java. But the concepts should apply to PHP, Perl, Python, anything.
Anyone else working on a system to solve this problem? I'd be interested to share ideas.
"fuzzy developing" (Score:5, Insightful)
I attribute much of this problem to something I call "fuzzy developing". It's the latest trend. The crux of this problem involves Web designers, who know very little about programming who are deploying more and more complicated applications in a cut-and-paste manner. These fuzzy developers have no concept of proper programming skills. Many of them can't program at all, but they can snarf someone else's "free" code online, change a few config parameters, whine to an admin for access, and compromise entire servers.
This new breed of developer relies on existing code, following the fallacy that if it's on the net, it must work. They use sites like experts-exchange to get other people to code for them when they get in a snag, and don't contemplate the priorities involved when you put something on a public system.
From C to PHP & Admin Responsibilities (Score:4, Informative)
The first thing that completely freaked me out was the register_globals setting in PHP. I invited a PHP programming friend to come hang out and give me a little intro-tutorial into how he developed so that I could understand where these guys were coming from when developing apps. He proceeded to show me this "neat feature" called register_globals that makes it super easy to access passed parameters from the outside world. Of course it also makes it super easy for anyone on the planet to overload internal variables that could be used just about anywhere in the scripts. I've never seen such a dangerous "feature" [in a non-Microsoft product].
And this all ties into the number one rule of programming. When you're coming from C/C++, 80% of your job involves data/input validation, so it's second nature to cover your ass. I found myself very confused at first over the dozens of different functions available to escape, unescape, tokenize and otherwise mangle input from/to various forms. No wonder developers are confused.
But above all, there are basic tenets that the server admin should enforce that have the most impact on security. First off, NOBODY should be enabling register_globals - it's just a crutch for crappy programmers IMO. Second, safe_mode is a must. If you have an app that needs safe_mode to be disabled, then you are better off isolating that app to its own private server. Third, every application should have its own private database work area. I am amazed at developers who run multiple applications in a single database space. Fourth, the configuration of the web server needs to be such that PHP code is properly protected, with
Safe_mode is a good tool. It also creates annoyances for the customers, especially those who are writing apps that create files in their work area... this requires the admin's intervention to set up the proper permissions (and gives them a chance to give the client code a once-over for glaring errors).
One thing I haven't quite figured out, and maybe I just need the proper Apache mod, but when a PHP app creates a file, it's owned by the web process and not the script user process, so in safe_mode, to get things working you either have to change permissions or give liberal directory permissions in order for things to work with user-uploaded code.
Ultimately, the server admin should bit the bullet and refuse to give users access to certain dangerous "features" such as register_globals or non-safe_mode. It's just too easy to open a Pandora's box.
Re:Here come the jokes... (Score:3, Funny)