PHP and SQL Security
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."
Looks more like "Scripts people write using PHP and SQL without understanding security issues are being proven more weak every day." to me.
When the site falls over, cue the jokes about PHP and MySQL, from the battle-hardened Perl and Postgres veterans.
Get your own free personal location tracker
PHP and MySQL are not weak; faux programmers are weak. Purification of incoming data is essential, and often ignored by novice script-writers, and that's the problem. SQL injections are common among novice coders, and they can slip past even competent coders, but a strict design engine for passing SQL vars using $_REQUEST, and turning off register_globals, will result in better results.
Essentially, the problem is with those making insecure scripts, not the whole PHP and SQL system.
The dangers of knowledge trigger emotional distress in human beings.
I think a lot of the blame for this can be traced to the ease of getting started with PHP/MySQL. Result: more people learning how to program with php will of course result in less thought about security. Add the ability to have input arguments via the http request be automagically available to the running code shares a lot of the blame too. Put them togeather and thats a disaster.
How about "weaker" :P
This one is pretty secure...
// Try to break into this script!
<?php
echo "Hello World!";
?>
The problem with socialism is that they always run out of other people's money. - Margaret Thatcher
You could also enable magic_quotes in your php.ini. However, if you\'re too dumb to know the basics of sql, chances are your program won\'t work quite right.
uses MS Comic font for their articles. Sorry.
Your scripts are only as secured as you make them. What this "UBERHACK" website is simply doing is sending a flock of young script junkies out to locate sites which have not implemented a good code structure.
/cgi-bin/ do you feel more secure by doing so? The ScriptAlias which you most probably have set for this directory will in no way prevent malicious intent from remote connections if your php is not properly configured for base_directories, register_globals, and safe_mode.
a b
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.
My Thoughts, Kyndig
There is no trully unsecure language, only programmers that practice building unsecure sites. Bugs and security holes can always be patched, but if the site is crap to begin with, then that's just asking for trouble. You should always check user input, esp if you plan to use said input as part of a SQL query or entry. Duh.
Sometimes I doubt your commitment to Sparkle Motion.
If you're going to make that argument (which, BTW, I think is accurate), then you'd better be prepared to say that Windows isn't inherantly insecure as well. You can't blame the platform for the sloppy coding of others who write apps for it, under ANY circumstance.
"Ask not what your country can do for you." --John F. Kennedy
SQL is probably the most widespread example of this, closely followed by regular expressions in Perl. I am often amazed that more people aren't working towards programatic ways to express SQL queries and/or regular expressions (attempts exist for both, but rarely make much progress).
I am often amazed that more people aren't working towards programatic ways to express SQL queries and/or regular expressions
They're called stored procedures. They've existed for at least 20 years.
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 DBI and Php PEAR can emulate bind variables for you.
Of course, if you're stuck with ASP and Sequel Sewer, you're somewhat out of luck, and need to do the proper quote escaping yourself.
When will /. stop posting misinformation?
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.
Leandro Guimarães Faria Corcete DUTRA
DA, DBA, SysAdmin, Data Modeller
GNU Project, Debian GNU/Lin
This is exactly right. GET, POST, or COOKIE data? It's all equally dangerous. Anybody have firefox and the web developer extension? Try displaying form details and change some post inputs. Or just use javascript in the url to alter the form at will.
Other than the scripting challenge, what's on this site? I've read the guides to hacking, but it's all a bunch of kindergarden material. Seems if you follow the guides you'll certainly have insecure PHP scripts with all kinds of SQL injection. How about posting some real articles on secure PHP scripting...
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'.
I want to drag this out as long as possible. Bring me my protractor.
If you need general purpose functions etc., I'd imagine it could be beneficial to have them just use $_REQUEST.
You can then let your particular frontend deal with where the values came from (get/post), and sanitize the data there. Afterwards the values will be available via $_REQUEST.
Of course you could also pass the sanitized data to the functions as parameters, with no need for $_REQUEST. As always, YMMV.
zWhat would an EWOULDBLOCK block, if an EWOULDBLOCK could block would? -- me
The worst practice I ever saw was making the global variables local scope using the extract() function, in... every... single... file... especially the security login files - its almost like register_globals and v4.1 never happened.
Then again this is the same person who insisted in using the $array[key] array syntax which was never the correct way of doing to start with.
And this was the supergenius hired to replace me. Fun city. Glad I don't work there anymore.
</mode>
Damien
Notice: Undefined index: name in example.php on line 2
Notice: Undefined variable: submit in example.php on line 3
Maybe someone can write a PHP script to take care of the 404 error that occurs when you click on the "home" link on Uberhacker.com.
Bad Design Überalles.
Purification of incoming data is essential
Then why doesn't the language do it by default?
If you need the unfiltered data, you should be forced to jump though at least one hoop to get it.
Take RXML for example. By default, all user-supplied data is encoded, unless you explicitly say that you want the raw format. That way, novice script writers don't get bitten by it.
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 ...".
zWhat would an EWOULDBLOCK block, if an EWOULDBLOCK could block would? -- me
You have indicated that Slashdot is not 100% accurate. You will be Slashimilated.
AFAIK SQL injection can be prevented by binding the parameters to the SQL statement and not putting them within SQL.
...) using bind_param.
Why is this? Performance? Keeping the code short and simple?
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
$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.
It is an economic fact of life. People will always be learning in the job. We will never have a guaranteed level of expertise, let alone competence. Tools will have to start enforcing security. Humble coders have been dealing in overflows, SQL injection, and cross-site scripting forever. Tools that manage buffer/stack overflows are not just for junior programmers. Tools/frameworks that add taint checking and build-in automagic security (like ASP.Net's validaterequest). If we have to rely on all the programmers becoming competent experts we will never have security.
Yes, that guide to secure scripting was very useful - a "hello world" program. Whoopee. To be frank, that site looked... well, less than professional, and with a name like "uberhacker" I expected their tips to be a little more advanced than "look, you can change the values in a query string but don't tell anyone!!!!11"
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.
and turning off register_globals, will result in better results.
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 gummed things up for the near future. Every language has had some stupid progressions, and session handling is high on PHP's Stupid List.
Table-ized A.I.
Liberal use of addslashes() +
Surrounding data from clients with quotes in SQL =
SQL injections? Where?
All I want is a kind word, a warm bed and unlimited power.
Jeez... this is hosted on HappyHacker ..
Won't that lady *ever go away*...
How long has it been.. she calls the FBI constantly trying to say people who put up negative stuff about her are "hacking" her.
Dis had to sue to get his face off the cover of her book. I was in the middle of a move and didn't get the email about getting my face off of there.. And I am still pissed about it.
bah..
don't give this retch any more publicity.. she is a bottom feeder.
anime+manga together at last.. in real time.
- David A. Wheeler (see my Secure Programming HOWTO)
for the admins at uberhacker to plug their own site, put up a shitty page, tell /. /. is so shit nowadays it accepts..
> If you're going to make that argument (which, BTW, I think is accurate), then you'd better be prepared to say that Windows isn't inherantly insecure as well.
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 motivation for corrections) and corporate belligerence on a systemic level. Fewer eyes have seen Windows source code than PHP source code, and those that have are swimming from confusing and conflicting design models.
Windows is insecure because the people involved are xenophobic. Plus PHP isn't an operating system, so we're really talking about penguins, apples and windows.
The dangers of knowledge trigger emotional distress in human beings.
Stored procedures still require SQL code to be embedded in the client code - and therefore still requires the mixing of code and data.
Have you ever used a stored procedure? You call the name of it, and that's it. You give the web server permission to call the stored procs.
Think it was just a "look at my cool site, try to slashdot that one!" kindof 'article'.
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 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.
I think we can keep recursing like this until someone returns 1
Absolutely. It's not PHP's fault it has a lot of clueless and/or lazy users.So true. The same argument can be used in relation to crappy Visual Basic apps: Crappy / ignorant / lazy programmers build bad VB code. This formula can be applied to any language (C... let me at those pointers...).
"Who are in control, they are not in control of anything - they don't even control themselves!" - Glen Beck
... and if anyone codes like that, they deserve to be hacked.
Free Firefox news reader.
Security does not belong in the database because it removes context of action. The correct level of security is to place it in between the database and the interface through a well-defined, simple interface that keeps the context of the action secured from the interface. By treating each element in the table as an object, the object is loaded with the security of the entity at the time of instantiation; thus, even if the interface is highjacked and the object is commanded to alter information, the user does not have permission to alter it even if under other scenarios the user might have the right to do so. In other words, a database can never know why something is being altered, and an interface can never been trusted to fully comply with security.
Bel, the mostly sane.. "Of course I can't see anything! I'm standing on the shoulders of idiots." -- Me
This is not an issue dealing with PHP and MySQL, this is an issue with weak programmers writing bad code, and I'm sorry to say, you find it in every language. As a regular in #php on freenode, 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, 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 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 and ASK US (irc://irc.freenode.net). We're there to help!
BeauHD. Worst editor since kdawson.
The real solution is not to use a separate language and syntax for constructing queries.
What are you talking about? This doesn't make much sense.
Programmatic ways to express SQL?!?
Isn't OO development basically tying code and data?
Plus, business rules belong intimately tied to data -- that's so you can't circumvent them. Hence the whole idea of a relational database management system.
Thanks,
--
Matt
Sh!t PHP coding is as old as the hills.
.inc file under htdocs!
... not so much as an HTTP_AUTH to secure it with and would handily chmod 777 all uploaded files and put them under htdocs for ease in execution.
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.
Languages which encourage the mixing of code and data make it extremely easy to write insecure code
In what way? I can see how it makes it easy to write unmaintainable code.
Yes, the coder is to blame, but so is the language.
By far the most widespread problem with people using PHP and SQL is that they don't escape user-supplied data, or that they trust user-supplied data. That is programmer ignorance, and it shows up the most with PHP and SQL because they are basic building blocks that newbies tend to pick up informally.
So that's a "No" on the question "Have you ever used stored proceudres" then? 'Cause it sure sounds like you don't get it. The good news is your current ratings suggest you're not alone.
Anyone have suggestions for a bit more uh, quality sites on the topics? Seen plenty of coding sites, but none particular to security of this combo.
No, I didn't say separate files, I said STORED PROCEDURES. Yes, this is the way it should be done, and this is the way that all of my web projects are done. Stored procedures are faster, more secure, and allow for code re-use. There's nothing wrong with SQL, you just shouldn't put it in server-side scripted web sites.
e =UTF-8&oi=defmore&q=define:stored+procedur e
You don't know what stored procedures are. You probably use MySQL, right? Check out Google definitions of stored procedures: http://www.google.com/search?hl=en&lr=&ie=UTF-8&o
ASP.NET data binding to SQL has built-in protections to avoid SQL injections and other common SQL security problems. In general, the .NET security model is quite effective and useful for web programming.
Fair enough, he should have known the saw was unprotected and therefore dangerous and should not have been used. Likewise, if you're silly enough to use PHP, it's your own fault.
I've been playing around with the adodb library in my spare time. It seems fairly powerful, and flexible (so much so that I really have to question why everyone doesn't write using it, since it opens your script up to a much wider potential audience).
But now I wonder whether it's more secure that plain ol' vanilla php/mysql (keeping in mind that my globals are off, code's written with POSTs & GETs in mind, and so on).
If it is more secure, then I have to ask why it's not made the standard for accessing databases w/php? It seems comprehensive enough to replace php's built in database functionality, and as mentioned, by using it, suddenly your scripts are compatible with a lot more databases, as opposed to being written specifically for mySQL.
I was just about to ask about a book on how to write secure code, and for other good practices.
Might I suggest that you mirror your column on your site after 4 or 5 months?
Any other recommendations for security books?
> what blows my mind is those that use the DB column name in a webform to be passed
OMG how many times I've seen that!!! It makes me wonder what planet these people are on. It's like they have a big bullseye on their asses, really.
Keeping table names secret is a good way to make it harder for script kiddies to attack. PHPBB allows for table names to have a prefix for this purpose, and sadly most people using it don't even bother.
Since most attacks come from script kiddies, you limit the ability by obfuscating things. I'm not suggesting it's the only path to security, just that it helps deter anyone but the more adept.
> Nothing that is ever given to the user, or recieved from the user should be trusted... EVER
Yeah it's like giving them your bank card PIN and mailing them the card, so they can check for errors on the little black stripe; the oldest game in the book is that wallet-inspector gag.
The dangers of knowledge trigger emotional distress in human beings.
PHP hasn't executed more than one query per mysql_query() for quite some time. Your exploit example might have worked a few years ago, but not for some time.
PHP/MySQL is not really that unsecure. If you don't do stupid things, you won't (generally) get hacked.
In the law there is no overlap between theft and copyright infringement whatsoever.
I guess everything is a trade-off....
I too was wondering why the parent seemed to be confusing files and stored procedures....??
Light travels faster than sound. This is why some people appear bright until you hear them speak.........
Stored procedures still require SQL code to be embedded in the client code.
Say what? what variant of sql are you using that's this broken?
Or is your crack cut with Tide detergent?
The point of this article is based upon the misconception that writing secure applications should be done for you.
Next article will be.
"PHP has weak performance because it can be slashdotted."
Oh, I agree; it definitely locks you in. I don't know any 2 DB's that have the same stored proc language, although I have seen tools to convert between, say, PL/SQL and T-SQL. That being said, the DB is even less likely to be changed than a webserver is, so I think that "lock" in is less critical at the RDBMS level. And, the larger the company is, the less likely they are to even change database vendors.
I think that parent doesn't know what stored procs are. I see it all of the time. It seems that very few of the latest batch of new web app developers know what a database is and what they do. The vast majority that I've seen tend to use databases as a flat file for pulling info out of. Very rarely have I seen an app developed properly, with business logic and security and logging in the database engine, where it usually belongs.
Why worry about security when your site's been slashdotted? No one can get to it so no one can hack it!!!
So your solution to the problem that SQL encourages the mixing of code and data is to physically separate all the SQL out into separate files?
Oh, well, Jesus, you're just an idiot. You should have said so up front, because we can't see the explanatory note that's pinned to your shirt .
A PHP CMS can be written securely, check out www.geeklog.net, the best PHP CMS out there.
PHP is the only language I've used that forces you to index arrays differently in code and string context.
Code: String: What the hell is that? While I try to follow the guidelines as described above, I wouldn't place blame on anyone for getting confused. Especially considering the fact that the $array[key] syntax is only discouraged. Not using it will not adversely affect any script in any version of PHP as of this writing, and keeps the syntax consistent across code and string contexts.
Last post!
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.
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, though it's not ready for production. Here's the idea: my files (XFP) are to a SAX ContentHandler 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.
Interesting topic, but I don't think the problem lies with PHP or MySQL. You can create insecure apps in any development environment. Yes, some are more problem-prone than others, but I'd rank Perl much higher than PHP/MySQL in terms of being conducive to allowing vulnerabilities.
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.
is that allowing globals is called insecure in PHP and gives no real explaination why except that users can give variables values. Well...that's the idea. It's no different than allowing user input in any other form. The only danger is when you don't assign values to variables before using them. In which case, where were you expecting to get the value?
And PHP I think is pretty useless without being able to append variables and values to the URL. It's a necessary ability for users to be able to bookmark exact pages. It also avoids the highly annoying "refresh" problem where pages expire and data needs to be resent when you make the socalled mistake of using the back button.
And MySQL's semicolon "hack" I didn't like either. It seems way to simplistic for a product that should be more sophisticated. Somebody exploited that not too long ago but didn't cause any real damage. The net result is that I still don't use it for anything critical. The only thing MySQL is used for is the forums and "Fun With Cutouts." People had more fun with HTML injection than MySQL injection with the latter. So now all and ; characters are stripped from user input before processing.
It's a "create your own comic" page anyway so nobody uses correct punctuation. Much less a semicolon.
Ben
Work Safe Porn
I don't remember exact numbers off hand, but the last time I saw this discussed someone posted benchmarks demonstrating that the $array[key] syntax is actually significantly slower than $array['key'] because of some nuance in how php works internally.
PHP and SQL Security are being proven more weak every day.
:)
Where does this guy get his facts? Tell me, what exactly is insecure about SQL or PHP? If you know what you're doing and write your scripts to prevent any SQL injections and you set adequite permissions on the database, you're not going to have any problems (assuming there isn't some huge flaw in the database server, itself).
By the way, I don't trust anyone who puts up a research project in Comic font. What is this guy, a 12 year old boy, or a 60 year old grandma? Either way, it's ugly and a Windows-specific font and I don't trust one word this llama says.
One more rant - he doesn't talk about SQL in general, he talks about MySQL. There is a difference.
(OK, I'll stop being a troll now
> Security does not belong in the database because it removes context of action.
aha
Well, rather than debate whether or not the data should be persisted in the context of its rules and actions (which doesn't work in reporting, btw), lets get down to what simply works.
You need to plan on including security awareness within each layer and component of your architecture. Since we've moved beyond client-server we seldom now authenticate & authorize individual users in the database. That's fine, but locking down the data should still be done in any database, even if the granularity is now at the application level rather than the individual.
The difference between today and ten years ago is that we're now mostly implementing database security at the application level of granularity.
Here's a trivial example:
- 20 users are in ldap group finance
- all are also in ldap group report
- 10 are also in ldap group invoice
- 4 userids are used by the database:
- userid invoice has ownership privs on invoice schema
- userid gl has ownership privs on general ledger schema
- userid fa has ownership privs on fixed-asset schema
- userid report has read privs on above schemas
- The invoice application will authenticate users via ldap service
- The invoice application will use ldap service to authorize users using either report or invoice group depending on what the user attempts to do
- The application(s) will connect to the database using either appropriate database userid. This will be used by database to ensure that invoice application does not attempt to write to general-ledger schema, etc.
This isn't the end of your security concerns in the database. You've also got to lock down all your file systems, ensure that no users can create new database objects, etc, etc. That's also fairly straight-forward.
Anyhow, don't get all hung up about where security must go - or in the interests of some kind of misguided purity you'll end up leaving giant gaping holes in your defenses. Implementing security at the application level of granularity is both simple and effective. Take advantage of it.
Most likely because
$array['key']
'key' is most definitely a string.
$array[key]
First we have to check if 'key' has been defined as a constant
define(key, 'blah')
But, if it's not a constant, PHP converts it into a string.
If you loop through an array a whole bunch of times and do it throughout your script...yeah, I'd imagine it'd impact performance (although I'm not sure if it would do so significantly)
concrete5: a cms made for marketing, but strong enough for geeks.
Being a low-level programmer, and specifically working on advanced CGI, awhile back I bowed to pressure to offer some of my web clients scripting abilities on their servers. I went with PHP/MySQL and started the process of learning about the language and its caveats.
.htaccess restrictions in code lib directories and careful consideration over other virtualhosts that might have php disabled in a higher-level directory.
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.
Because this is where all sorts of injection attacks come from (script injection, as well as the sql injection that's the focus here). If you mix code and data, and the data itself contains code, then that code can be executed, as it is now part of your script/ program. This means that a malicious user can put code in the data he supplies to your program and that code will get pasted in with the code you wrote, and run with the same security priviledges.
I'd rather be lucky than good.
Comment removed based on user account deletion
>Say what? what variant of sql are you using that's this broken?
That would probably be MySQL: the "choice" DB for Script Kiddies worldwide. Why make the database do all the heavy lifting, when you can shuffle it off to your PHP code? It is not like you're going to need to look at or maintain said code in six months/year.
These are the same fools that count NOT NULL sometimes as NULL, and consider column constraints as only suggestions.
Yeah, right.
Why are PHP developers so freakin quote-happy.
Example:
print ("$array[key]");
You dont need the quotes.
In the uberhacker site:
mysql_select_db ("$dbname")
You dont need the quotes.
Further, its faster to use single quotes since php wont look for variables within and no one seem to do it. PHP is the greatest language but I have to work with a bunch of lazy bastards.
I'm sorry but your comment comes off as a bunch of useless blanket statements to me. Don't get me wrong, I agree that maxing new and bad programmers with versatile tools that are both easy and dangerous to use is a fatal cocktail, but what are you exactly suggesting we do?
So what's your solution? Making PHP/MySQL more difficult and more error prone like C/C++ so newbie programmers will run away?
I've seen too much shitty C/C++ code to know no language/tool is idiot proof. Some are just more idiot resistant.
Add the ability to have input arguments via the http request be automagically available to the running code shares a lot of the blame too.
Wait a minute, programming languages are supposed to be functionally ornothological, but your complaint seems to suggest we somehow prevent the programmer from piping one variable to a paricular slot to fix one security exploit.
How about just providing a coherant database library that properly encodes SQL data when building queries and the like?
Couldn't have said it better.
Some people are working on programmatic ways to express database queries. Have a look at HaskellDB for example.
Turning it off doesn't actually solve anything if you know how to code. And having it on makes it easier for everyone.
If you're passing around variable values that a user shouldn't be able to change, you store them locally and give the user a key. The script then uses that key to open the file (or reference the table entry) to retrieve the values.
Since the critical values are set inside the script and stored in a file that the user can't change, they can pass the values through globals all they want but those values will be overwritten by the time the variables are actually used.
The other nice side effect of this method is that the user can't use any page but the one you give them to use your site. Since if they try to use some other site, the file with the values won't be generated and the processing script will just ignore the request since it can't find the file.
This is what I use on Indie-Mail and the Anonymous E-Mailer. The user is just given a very long randomly generated key that references the file which stores the values for any variables that a user isn't allowed to change. When a user makes a request, the script checks that the file the key points to actually exists and then loads the values from the file.
The fear of globals is just undue paranoia unless you really have no clue how to securly pass things around. If you really want to be secure, you ignore client input. It has nothing to do with whether or not the variable is global or not.
For my real world example, the user sends the username and password exactly once and it is never returned to the client in any way shape or form. The server handles everything locally from there based on the SessionID and the IP address of the client.
Ben
Work Safe Porn
The SQLite extension does allow multiple queries per call, though, and this is being pushed/bundled with PHP5. It seems like there is a big push for this to be the "standard" database that you can always expect to be available (kind of how MySQL is now).
---John Holmes...
Yeah I don't thnk it's significant in terms of raw amounts of time, but comparatively it does make a large difference. I just threw together a quick little script to test it out, and here's an average sampling of the numbers I got:
$array[key1] = 'value 1': 7.0095062255859E-05 seconds
$array['key2'] = 'test_value': 1.8835067749023E-05 seconds
$Key1Value = $array[key3]: 2.598762512207E-05 seconds
$Key2Value = $array['key4']: 2.0027160644531E-05 seconds
The biggest difference is in assigning a value to an array. While it's still fast, using quotes is 3-4 times faster than not using them so that is a relatively significant difference considering the only excuse for not using quotes is lazyness.
*** This thread is marked as CLOSED ***
*** Please move on to another topic ***
It seems that very few of the latest batch of new web app developers know what a database is and what they do. The vast majority that I've seen tend to use databases as a flat file for pulling info out of.
I'll second that! I've been tasked with updating some old PHP apps to remove reliance on register_globals. In most cases, this has meant a total rewrite of the (really crappy) code. Most of the apps have a DB (and I mean this loosely) backend to them.
Web design/programming courses that teach DB use should have a whole course devoted to DB normalization. I usually sit in front of the code shuddering for about half an hour before I'm able to dig in and get to work. I'm not kidding...I've got some real hall of fame $#!+ to wade through.
For me, updating these apps has usually turned into re-writing them, from the DB structure up.
-Ben
I know this is flamebait, but I can't resist: How in the world can someone who refers to Perl as PERL make disparging comments about Perl or its users?
Java is the blue pill
Choose the red pill
Just use SafeSQL, a database wrapper class that handles SQL injection very easily, among other very useful features. This one is a must-have for any PHP/SQL application IMHO.
>>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
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...
I run Uberhacker.Com, the reason why there are so few articles on the site is because I have had about two months to put it together. I am trying now to get more up there, but I have school daily. I am not making excuses, but that is the main reason why.
to maintain consistancy, you can also use {} when interpolating complex variable types.
ex: echo "blah blah {$array['key']} blah blah";
it's bad to use $array[key]; outside of interpolation though, because PHP will first look for a constant called 'key' before it decides you're using a string. if you have a defined constant named 'key' it will use that first, which may not be desierable.
BeauHD. Worst editor since kdawson.
I disagree with your post in many ways. This is the same logic that causes so many work-place accidents to be blamed on "human error" when they're really in combination with bad design that fails to take into account the practical limitations of human abilities. It's also the same logic that HCI advocates have been arguing against for some time now. Certainly the user does have to be responsible, but the design of a tool and how it's expected to be used should be taken just as seriously.
For instance, if you design an aircraft that requires the pilot to reach over her left shoulder to adjust a control that will cause the plane to pitch to the right, it shouldn't be any great surprise that sooner or later someone's simply going to make an error. You can train pilots about how to fly the plane for as long as you like, but sooner or later someone's going to make a mistake, perhaps with drastic consequences. That's a fact, based on human limitations. It's also a fact that it wouldn't happen as often with interfaces that are designed more intuitively with the pilot in mind.
Two possible ways around this are to:
I'm not familiar with power tool accidents, but there are certainly a variety of situations where the tools can easily be considered at fault for their badly designed interfaces that consistently place unrealistic expectations on a user, yet the people are blamed for failing to operate the tools correctly.
> Can anyone tell me how to do a solid path checking so I can include a module specified by a POST variable?
. $fields['the_filename']);
:-)
Personally, I would create a table of values that lists the existing filenames.
Possible fields:
record_id (INT, PRIMARY KEY, AUTO INCREMENT)
the_filename (VARCHAR 128) (ie: thatfile.php)
Don't put the path in the_filename... hard code the path in your init file. ie: $FILENAME_PATH = '/images/birthday2004/';
Then:
print $PATH.$fields['the_filename'];
or
require($PATH
This way the file your clients request has to be in the table.
Make the POST var a numeric one, and that way you can quickly SELECT from the table, the record_id, and read the_filename.
I've got examples of how to do this in the Gemsites code.
The dangers of knowledge trigger emotional distress in human beings.
If you call .000025 seconds "significant"
Speed is not the reason to do it the right way, what it does behind the scenes is.
BeauHD. Worst editor since kdawson.
Stored procedures are evil. Databases are meant to store data, all manipulation can and should be done at application level.
Marxist evolution is just N generations away!
Thanks for that completely useless analysis that doesn't even do us the favor of showing us the actual benchmark code.
How many times did you need to iterate to make the script run that long? i'm guessing somewhere in the neighborhood of 100,000 - 250,000 iterations, which no sane web-based script would ever do.
I do fully agree that you should quote array keys, however *speed* is not the reason to do it right. What it actually does *is*. Too many people bring up the "X is faster than Y" argument using completely unrealistic benchmarks to show their reasoning. A classic example of this brought up by people who go to fanatical lengths to optimize is double vs single quotes, which is so slight in it's speed difference it probably shouldn't be considered an optimization unless you're interpolating on the order of 100,000 - 200,000 times. If your PHP web-based script needs to do something like this for some real-world application, you need to rethink your logic.
In fact, if you feel you really need to be splitting hairs over a fraction of a millisecond of execution time, you probably should be using a lower-level language (such as C) for the operation.
BeauHD. Worst editor since kdawson.
Its just informative PHP scripting, but
/'
still very very very very far off from
really coding in PHP.. I'm thinking about writing my own sessions system.. Security in most php programs stinks anyhow, not much in the way of finer access restrictions.. I knwo of better ways, but I'm not going to tell nyah nyah nyah..
PS- make sure you have the variable unification stuff turned off, you don't want people producing variables in your global scope, better to scope it to POST and GET associative arrays.. Scoping is fun and is necessary, people who code with globals are just asking for it.. Especially guys with
exec($mycommand);
What happens if $mycommand is not initialized?
What if I did
www.yoursite.com/yourscript.php?mycommand='rm -rf
then repeated with
www.yourname.com/yourscript.php?mycommand='del C:\*'
lots of fun stuff..
Just say no to license servers!!
Because this is where all sorts of injection attacks come from
No, injection attacks are where data is supplied with characters that are special in some way to break down the boundary between code and data. Such a boundary already exists, no matter what language. When people complain about "mixing of code and data" in relation to PHP, they are usually talking about putting logic into HTML pages. A PHP page that outputs nothing can still be vulnerable to injection attacks.
Thanks for that completely useless analysis that doesn't even do us the favor of showing us the actual benchmark code.
You've done a great job of putting down our anonymous friend. I myself was absolutely horrified that he was interested enough in the problem that he would go to the trouble to benchmark the problem of all things, and document the actual effects. Oh! The horror!
Last post!
By the way that link is Carolyn Meinel's. If you're into security you'll remember she's a fraud that has no knowledge of technology. ;)
This whole "contest" sounds like "please write code for our web site for us." The first challenge is an article submission system like /.. The requirements read like a spec for work. "It should have this and this and this and be able to do this. And make it so we can reconfigure it for our database." Geeze. Some contest. It might be fun to submit really bad examples and see if they end up using them on their own site. OK, that's mean, but hey...
Kind Regards, Phillip
I agree with the comment in the context of product design. But the original statement wasn't a question of product design but of responsibility.
Yes, product design leads to failures but it doesn't cause them. Someone cutting off an arm with the unprotected blade of a circular saw (I've no idea what a "buzz saw" is and I've done construction) has not cut off their arm because the saw was badly designed, they cut it off because they applied a blade to their arm. Yes, product design could have helped them but that does not absolve the user of the responsibility for having been the -cause-. There are two contexts at play here: HCI design and "responsibility" in the wider world. Bringing bizarre and irelevent metaphors about industrialization era labor exploitation into it notwithstanding. Oh, and yes. People -do- cut themselves with protected circular saw blades all of the time. That doesn't mean the designer of the blade protector caused those accidents, it means that both designers and users should exercise due care.
Keep in mind that many tools fail in catastrophic and *non-intuitive* ways, and people do not always have a choice of what tools they get to use (except perhaps in some theoretical Ayn Rand world). It is unreasonable to hold users responsible for failure modes that are not obvious - but that the engineers of the product are aware of. There are, of course, special cases in which protecting the users from harm is nearly impossible. However, there are many cases in which a simple design element can save lives & limbs. When a company is too cheap to spend $0.14 on a deadmans switch for a large machine that requires someone to climb inside to repair - and a few people die each year because of the combined savings of $3.72 - we've got a problem. Fortunately, the courts solved that problem. Back to the original subject: a software tool that very easily fails in a way that is hazardous, when this could easily be prevented - is flawed. It isn't the 'bad workman' it's the 'bad tool'.
> Why should I switch to Linux/PHP/mySQL
Hardly any security problems will crash VB at runtime. Same goes for PHP. Security and bugs are two different things, really. Security is a system design plan, while bugs are merely accidents that crop up from time to time. Some bugs are caused by incorrect system design, and others are merely accidental.
Why you should switch is entirely up to you. VB and PHP are not the same system at all. VB creates executable code, and PHP is only a scripting solution. For my needs, PHP is the best choice. What are your needs?
The dangers of knowledge trigger emotional distress in human beings.
> I need a way to port a huge (80k LOC) VB/IIS web app project over to PHP in a couple of days without it failing and me/my staff looking incompetent.
Maybe you could outsource it to someone? I'm not very busy right now...
The dangers of knowledge trigger emotional distress in human beings.