Slashdot Mirror


PHP Application Insecurity - PHP or Devs Fault?

somersault asks: "There have recently been a lot of people making jokes at the expense of PHP, but how many common security flaws in PHP are the fault of the language, and how many the fault of the developer? A recent Security Focus article (via the Register) has a brief discussion which suggests that PHP is no less secure than any other scripting language, and that it is the users of the language themselves who need to be educated. The other side of the story is that the developers of PHP should work on tightening up the language to make it more 'idiot proof' by default. Should the team developing PHP take a more active role in controlling the use of their language? What will it take to ensure that users of the language learn to use it securely, short of defacing every vulnerable website out there?"

45 of 200 comments (clear)

  1. mysql_escape_string, mysql_real_escape_string, etc by Anonymous Coward · · Score: 2, Insightful

    and addslashes. quick, which one is SQL secure?

  2. Tool safety by nacturation · · Score: 2, Interesting

    Saying that it's the programmers' fault for writing bad code is like saying being injured is the fault of a lumberjack for not knowing how to use a chainsaw which is dull and jerks a lot. It's much better to start with a tool that prevents such mishaps rather than being unsafe by default.

    --
    Want to improve your Karma? Instead of "Post Anonymously", try the "Post Humously" option.
    1. Re:Tool safety by nocomment · · Score: 2, Funny

      His chainsaw probably wouldn't be so dull if he spent less time jerking.

      --
      /* oops I accidentally made a comment, sorry */
      /* http://allyourbasearebelongto.us */
    2. Re:Tool safety by Beryllium+Sphere(tm) · · Score: 4, Interesting

      The aviation industry began making real safety improvements when they stopped regarding "pilot error" as the end of the story and began to fix ergonomics so that pilots weren't led into error.

    3. Re:Tool safety by qbwiz · · Score: 2, Funny

      Remember, it's PHP we're talking about here.

      --
      Ewige Blumenkraft.
    4. Re:Tool safety by VGPowerlord · · Score: 5, Insightful

      Have you ever used PHP? If not, take a look at the following features:

      1. addslashes() function - Most references say to use this to quote data before putting it into a database. Not only is it The Wrong Way To Do It (twwtdi) according to the SQL standard, but different vendors' databases need different values escaped.
      2. Magic Quotes ini settings. magic_quotes_gpc is the most important one. When enabled, it runs addslashes() on all GET, POST, and cookie input. It is on by default in php.ini-dist, off by default in php.ini-recommended. Which brings up my next point...
      3. The programming environment is not consistent. An INI file controls the programming environment. Turning on things like Safe mode and open_basedir can cause previously working code to suddenly fail. Of course, php.ini-dist has display errors turned on by default, so anyone visiting that page will see the location of your file, the line that has the error, and which error it is... Which brings up the next point:
      4. Security is secondary to convenience. See Using remote files, which is enabled in both ini files by default. See also Magic Quotes as described earlier. Reading up on the deprecated Register Globals is informative, as it was on by default up until PHP 4.2.0. I've also mentioned display_errors, which is on in php.ini-dist.

        Here's a disturbing fact: php.ini-dist is the more ocmmonly used of the two inis, at least for shared hosting. I'll let you consider the implications of that while I summarize things.
      To summarize: The PHP team has made a number of questionable decisions over the years that makes it much easier to write a security hole than it should be.
      --
      GLaDOS for President 2016! "Well here we are again. It's always such a pleasure." -- GLaDOS, 2011
    5. Re:Tool safety by Cecil · · Score: 4, Insightful

      There are two sides to that coin, you know. Aircraft designers tend to be extremely conservative, yes. But there's a reason for that.

      Why do general aviation planes usually have extremely simplistic, 4-stroke big block engines with carbureators? Because they generally work. They do fail, but their failure modes are very well known, very obvious, and usually easy to fix. Those are important qualities, and I'm willing to bet that you underrate them. If you replaced the aircraft's engine with a modern fuel injected digitally controlled model, what happens if an injector clogs, or the computer goes insane? No one knows, and they're not eager to find out. If your carb ices, you can fix that. In-air, no less. It may be a less reliable design overall, but the failure modes are usually pretty tame. And that's worth a lot to an aircraft designer.

      Taking one of your examples regarding the stall indicator/yoke... do you really want to take a piece of equipment which in correct operation is almost *never* going to get used, and hook it up to your primary controls? That's just *asking* for trouble. If the stall indicator ever gets jammed open (it is just a little metal flap after all, it's unlikely but possible), your "safety" measure may well crash the plane on its own.

      It's not as easy as it looks. These people are not idiots, they simply have a lot of variables to consider and weigh. And they have a pretty solid track record behind them, too.

    6. Re:Tool safety by Oersoep · · Score: 2, Insightful

      4. Every virtual user has his own (limited) ini, logs, etc.

      PHP is much more powerfull and versatile then everybody seems to think.
      The only problem is that it seems so easy to master.

  3. The problem is .... by lambent · · Score: 5, Insightful

    The problem is that so many neophyte progrrammesr jump into PHP to create something visible and useful. Which they succeed in doing, more often that not, I guess. But without a proper background in security and proper practice, there's a ton of vulnerabilities that get created, accidentally, over and over again by every new PHP programmer.

    The same can be said about any other language. Take for instance, C. Very easy to create working code that's vulnerable as hell. Is this the original author's fault? Of course not. I'm sorry that whoever chose to write a webapp in PHP is ignorant of basic security principals, but it's not up to the coders of PHP to protect us from ourselves.

    1. Re:The problem is .... by Schraegstrichpunkt · · Score: 3, Informative

      Blah blah blah. I've written code in both PHP and C, and writing secure code in PHP is harder, because you have to work around the insecure C code it's written in. No amount of rhetoric is going to convince me otherwise, because writing PHP code is my job, and I know better.

    2. Re:The problem is .... by lambent · · Score: 3, Insightful

      Good for you. Writing PHP code is part of my job, too. As is writing C, perl, java, python, and anything else you can throw at me.

      It all comes down to knowing what you're doing in the language you're coding in. If you're not good enough to sanitize, error check, bounds check, mem check, fault check, and whatever the hell else could go wrong, you have no business coding.

      It's YOUR problem, not anyone else's. Don't pass the buck. If you don't like that, choose another language.

    3. Re:The problem is .... by Coryoth · · Score: 4, Insightful
      If you're not good enough to sanitize, error check, bounds check, mem check, fault check, and whatever the hell else could go wrong, you have no business coding.

      I think the point is that we're all human and we all make occasional mistakes even with the best of intentions. There's plenty of code out there written by very experienced C programmers that still has buffer overflows and other glitches. That means that having a language that has the facility to make such errors easier to catch and correct early is a good thing. That means that having a language that pushes you toward secure practice by not having sloppy easy ways to do things is a good. Yes, we could all, in theory, write perfectly secure error free code in C or PHP or whatever, but in practice we don't - no one does. Languages that encourage best practice by default and provide the tools to catch errors earlier (with, say, design by contract) are a good thing if security is important. We're all human, and can use all the help we can get.
    4. Re:The problem is .... by Schraegstrichpunkt · · Score: 2, Insightful

      It all comes down to knowing what you're doing in the language you're coding in. If you're not good enough to sanitize, error check, bounds check, mem check, fault check, and whatever the hell else could go wrong, you have no business coding.

      "Sanitized" is a generous way of saying "not binary-safe", which also means "not internationalized" and "doesn't work in edge cases". Most of the time, if you have to \"sanitize\" input, instead of accepting and properly encoding <em>any</em> possible input, you\'re doing something wrong.

      As for error checking, bounds checking, "mem checking" (what is that? avoiding memory leaks?), "fault checking" (how is that different from error checking?), etc, those are tasks that a computer can do much more reliably than any person. If, realizing that, you still can't see how hopelessly stupid your argument is, then I suspect you're the one who has no business coding.

      You would totally fail at investigating plane crashes.

  4. This is easy to test empirically by Schraegstrichpunkt · · Score: 4, Interesting

    Take 100 programmers selected randomly, and instruct them all to write a given application, but have 20 of them write the code in PHP, 20 write the code in Python, 20 write the code in Java, and 20 write the code in C++, and 20 write the code in Perl. Then analyze the resulting code.

  5. what's the purpose of a language, anyway? by numbsafari · · Score: 3, Informative
    The question, as I see it, is what really is the purpose of a programming language?

    I mean, why can't we all just write our code in assembly language and get it over with?

    The fact of the matter is, that a programming language is a productivity tool. It is supposed to enable the programmer to more simply express complex actions rather than having to deal with all of the low-level particulars.

    PHP advertises itself thus:

    PHP is a widely-used general-purpose scripting language that is especially suited for Web development and can be embedded into HTML. So, PHP claims to be "especially suited for Web development". Given that one of the primary concerns of web development should be security, I would expect that the language, and the core libraries that are packaged with it, would promote and encourange safe programming practices.

    So, should the language be "idiot proof"? No, not necessarily, but it should certainly make secure programming hard not to do.

    A good example of this approach is that taken by the OpenBSD project when it redesigned some of the low-level C library string manipulation functions to make them "more secure" in that they eliminated the programmer's ability to make certain, common, mistakes.

    I don't look at this as a "stupid" versus "smart" issue. It's a "does my programming language help me do X or not?" issue.

    So, stop blaming the programmer and find ways to make their already busy lives easy.
    1. Re:what's the purpose of a language, anyway? by MysticOne · · Score: 3, Interesting

      Is it really that PHP makes it that hard to be secure, or that it makes it easy to do whatever you want, thereby allowing a lot of lazy people to take the easy route? I think the developer (writing code in PHP, not necessarily the developers of PHP) have to take responsibility for the things they write. If you're trusting user-entered data without escaping it and verifying its validity, shame on you! If you're doing other silly things that make it possible for people to h4x0r your systems, that's also largely the fault of the person writing the offending web application. I have nothing against making PHP more secure, but what does this entail? Not allowing you to do the things that make PHP flexible and fun to work with? I think the resulting language would be about as useful as safety scissors.

    2. Re:what's the purpose of a language, anyway? by numbsafari · · Score: 2, Insightful

      Sure, but what good is it if the content happens to be spyware or a root exploit?

      I mean, you could make the same degenerate argument about Windows and OS's, but something tells me it would sound just as lame.

    3. Re:what's the purpose of a language, anyway? by numbsafari · · Score: 2, Interesting

      Agreed: developers should absolutely take responsibility for the code the write.

      And people should take responsibility for the cars they drive and the pollution they create.

      Of course, it would seem to me like a lot of people believe that there's a certain social value in asking the producers of cars and heavy equipment to improve the quality of their products.

      As with anything, one should select the right tool for the job they are trying to do. If you need to write a complex site, pick a tool that allows you to do things that are more complex. Of course, doing so means you need to be aware of what that complexity means and take responsibility for the increased risks.

      However, PHP sells itself as the "easy to learn", "user friendly language" of the web.

      As someone noted earlier in the thread, user friendliness often times includes safety matters. Sometimes, safety scissors are warranted.

    4. Re:what's the purpose of a language, anyway? by lphuberdeau · · Score: 2, Insightful

      Of course the programmer is not to blame, but the PHP Group can't do everything. I've attended to multiple conferences, read PHP magazines and such. The community does encourage good practices. Security is discussed all the time, with techniques to structure code in order to avoid problems. The Zend PHP Certification contains a section on security. The problem is that the entry level programmers using PHP don't spend $800 to attend a conference. They don't pay $50/year to subscribe to a specialized magazine. They don't buy one of the two great books on PHP Security. Instead, they surf the web and grab the tutorials written by anyone and use the one that looks the most simple, which is obviously a bad choice. The PHP Group has no control over what is published on the web.

      --
      Qui ne va pas à la chasse n'a pas de gibier
      PHP Queb
    5. Re:what's the purpose of a language, anyway? by madstork2000 · · Score: 2, Insightful

      Something I don't see a lot of talk about is the deployment environment. "The Web" is pretty general, during the day I write applications for an internal corporate network. Those apps live in a closed environment, and are not exposed to the world. We are also under constant pressure to provide "quick-n-dirty" features and updates that happen with out a lot of planning. Our job often is to get people access to information or add a new field as quickly as possible.

      PHP gives us the flexibility to deliver, while being "lazy", since doing it the "right way" would be overkill, and over costly for the intended purpose / environemnt.

      On the other hand at night I still do a great deal of side work. You better believe that the code going on the Internet isin a lot better state than most of my regular work.

      Is it better code? No, it is different with a differnet purpose. PHP gives me the ability to choose.

  6. SQL escaping considered evil... by numbsafari · · Score: 5, Informative

    I kind of agree with where you are going, but I would add the following point:

    SQL Escaping is evil.

    Why?

    Because no user input should ever be executed. EVEN if it is escaped. The problem is that the escaping can be invalid and buggy and thus, insecure.

    People should use parametric SQL statements. No excuses. In this manner, no escaping is ever necessary.

    A separate issue is what to do about displaying user input. Here, things are more problematic, especially in the world of HTML. What would be nice is if we all got together and redesigned "the web" so that user input could be handled in a manner similar to parameters in SQL.

    Obviously, there's a difference between data in tables and data in a formatted page. But I'm sure something could be done.

  7. Re:mysql_escape_string, mysql_real_escape_string, by FooAtWFU · · Score: 3, Interesting
    Ooooookay. I've just been doing mysql_real_escape_string all day, so it had better work. :P

    mysql_escape_string and mysql_real_escape_string should both work (assuming you're using MySQL, anyway), but the former is deprecated as PHP 4.3.0 in favor of the latter; it also does not respect the current character set setting.

    If you looked at the documentation for addslashes, though, it will tell you nice things like An example use of addslashes() is when you're entering data into a database even though there are special characters that it does not escape that can be used for SQL injection.

    My beef with PHP is that it's full of junky functions like mysql_escape_foo() in the core distribution, main namespace, which don't even have a hint of data verification in 'em. I hear there's a neat database abstraction layer in PEAR, it even has prepared statements. But I'll wager there are plenty of PHP developers who haven't even heard of PEAR. Somehow, though, Perl seems to have managed to put together a decent standard distribution without this sort of mess...

    --
    The World Wide Web is dying. Soon, we shall have only the Internet.
  8. Re:mysql_escape_string, mysql_real_escape_string, by mabinogi · · Score: 3, Informative

    Trick question.

    None of the above, use bind variables instead.

    --
    Advanced users are users too!
  9. Re:Upload.php by temojen · · Score: 2, Informative

    Erm... "Upload.php" is a logical thing to call a script which accepts an upload... it doesn't necessarily mean they all do the same thing. Ever noticed that there are an awful lot of C functions called "char** parse(char* s)" even though many programs have errors in their parse function?

  10. Re:I have to agree.. by FooAtWFU · · Score: 2, Insightful

    PHP pretty much invites you to be insecure with MySQL. They ship with this tempting mysql_query() that takes as an argument... a single string. (well, and a connection ID). To get something in there, you need to do something like mysql_query("select * from foo where whatever = '$var'") -- and remember to have $var properly escaped. PHP does not give you a pretty library with prepared statements, parameter binding, and such. There's a nice DB and MDB2 package available on PEAR, but PHP doesn't ship with those. It ships with the compile option --with-mysql.

    Perl ships with a fair amount of stuff. It ships with a package named DBI. You can do things like $rv = $sth->execute(@bind_values);. The documentation on it starts off with a convenient set of good examples which go like

    $sth = $dbh->prepare("SELECT foo, bar FROM table WHERE baz=?");
    $sth->execute( $baz );

    You can write code in PHP that's perfectly secure, you can do just about anything in PHP you could do in Perl (props for being Turing-complete, I guess), and yes, it ultimately is the developers' responsibility to secure their applications, not PHP's. That doesn't change the fact that PHP is an ugly mash-up of a language with Bad Choices just lying around in a scrap heap on the ground begging to be used. It's just about as organized as a scrap heap, too... (insert generic rant about naming conventions, parameter ordering, and such).

    --
    The World Wide Web is dying. Soon, we shall have only the Internet.
  11. Re:You are all lazy programmers! by Shados · · Score: 2, Interesting

    The problem here, is that if you cannot depend on the framework for SOME stuff, why are you even using a framework? Thats like if in Java or .NET you had to constantly worrie about memory leaks (you actualy do, to some light extent, but thats beyond the point), then when someone complained about the framework not handling them, people would go "dont blame the framework, blame yourself!". The framework is supposed to handle these things.

    The absolute worse thing ever in PHP is how until recently, SQL injection could happen because there was incredibly poor prepared statement support. Good frameworks encourage the use of prepared statements to the extreme. It was possible to use in PHP4, but certain extras had to be added, and it was rare to hear about them in tutorials, etc (thus the blame was also greatly on the community). This, along with the far too common default setting of mapping post variables to variables directly were major things that I definately think CAN be blamed on PHP and its community.

    .NET 1 and 1.1 had a very well known flaw of this kind. The datagrid, when a column was configured as invisible, would still render the HTML for the data in that column, but simply not display it. This allowed the data to be seen in the source, but not on the actual page. This lead several developers to hide columns to have secret data in memory to work with on the server side, thinking the user had no access to it. Of course, a GOOD programmer would think of that and use a different method to hide the data securely. That doesn't change that it was an insecure and poor design choice in the .NET framework, and it was fixed in .NET 2.0. So yes, the framework was to blame. Same with PHP's issues. And they are severe. The community however, make them 10x worse than they should be.

  12. Yes by Rycross · · Score: 3, Insightful

    The answer is yes. Obviously, developers are ultimately responsible for writing secure code, but that doesn't mean we can't damn programming languages that fail to encourage good coding practices. I'm including libraries and official tutorials in this.

    Fact of the matter is, real security comes from having many layers. Having a programming language that directs you to safe practices and actively prevents you from creating unsafe code is the first line of defense. Yes, the programmer needs to educate him or herself on how to write secure code, but given that people are not perfect, the language should have a safety net.

    There's a reason that we've moved away from languages such as C, except when necessary.

    And from what I've seen, PHP has really encouraged bad programming practices. Preferring escaping SQL strings instead of proper parameterized queries, register globals, etc.

  13. Who's fault? Zend's by kestasjk · · Score: 4, Insightful

    I've audited quite a lot of PHP, written an article on PHP security from the hackers perspective, and done quite a lot of PHP development, and I've never come across an security problem that you could blame the developers for!

    It's always the developer assuming something about PHP or the PHP environment but getting it wrong; you can argue that the developer should know, but there are so many gotchas in PHP, you have to be an expert to be aware of them all. (I've listed some in a previous post on /. , and won't repeat myself here).
    This isn't right for any language, but a language which web applications run on?! The most hostile environment to develop for is not the place for a language that makes it so easy to trip up!

    The fault, for the vast majority of PHP security problems, is completely Zend's. Zend needs to give security priority over backwards compatibility, and get rid of all of their problems that developers repeatedly trip up on.

    --
    // MD_Update(&m,buf,j);
    1. Re:Who's fault? Zend's by Mr.+Slippery · · Score: 2, Insightful
      there are so many gotchas in PHP, you have to be an expert to be aware of them all. (I've listed some in a previous post on /. , and won't repeat myself here).

      Looking at your list, I see complaints about:

      • magic_quotes and register_globals, which are options that can be turned off: register_globals is off by default, and has been that way for a long time. Anyone who turns it back on deserves what they get. It's a dead issue. magic_quotes is headed for the same fate in PHP 6. They seemed like good ideas at the time the web as young; they turned out not to be.
      • "Only critical errors are reported...unless you specifically turn up the error_reporting level" Configurable logging and reporting is a feature, not a bug.
      • "fopen_urls: By default you can include scripts hosted on other websites!" I'll agree, that should probably be off by default. But a developer has to be naive or dim to either use an URL include, or include a variable in the include directive (and thus introduce the possibility of a URL inclusion) without being damn sure what they're doing.
      • "Inconsistencies: What one function does can never be applied to what another function does; you can never assume anything with the PHP library and always have to keep a browser window with the PHP manual handy. Using a function without carefully reading up what it does, even when it's very similar to another function you're familiar with, is asking for trouble in PHP." And in C (bcopy versus memcpy, anyone?), and C++, and Perl, and Javascript, and... In fact, most of these "inconsistencies" stem from trying to stay consistent with functions borrowed from C, Perl, et cetera. That's a good goal.
      • "Input checking is difficult...Do you want htmlentities() or htmlspecialchars()?" Depends on what you want to do, now, doesn't it? Developers have to know what conditions they need their data to adhere to, and PHP gives them a variety of tools to make it fit those conditions. Feature, not a bug.
      The most hostile environment to develop for is not the place for a language that makes it so easy to trip up!

      It's easier to trip up badly in C (by commiting some memory buffer error) or Perl (by writing line noise code that you can't understand a week later) than PHP. But it's no longer fashionable to bash those languages.

      Zend needs to give security priority over backwards compatibility, and get rid of all of their problems that developers repeatedly trip up on.

      Apparently what you see as "problems", others see as features.

      --
      Tom Swiss | the infamous tms | my blog
      You cannot wash away blood with blood
    2. Re:Who's fault? Zend's by kestasjk · · Score: 4, Insightful
      magic_quotes and register_globals, which are options that can be turned off: register_globals is off by default, and has been that way for a long time. Anyone who turns it back on deserves what they get. It's a dead issue. magic_quotes is headed for the same fate in PHP 6. They seemed like good ideas at the time the web as young; they turned out not to be.
      Yes, but if you develop on a server which has magic_quotes on, and you deploy on a server that has it off, your code won't behave as expected. You have to be aware of magic_quotes before writing anything in PHP, if you want to be safe.
      Same goes for register_globals; and it's hardly a non-issue as it's enabled just about everywhere in the name of backwards compatibility. In the article I wrote the site that got exploited had a vulnerability exposed by register_globals.

      "Only critical errors are reported...unless you specifically turn up the error_reporting level" Configurable logging and reporting is a feature, not a bug.
      You bet it's a bug when only critical errors are reported by default. Errors in code aren't shown, and users don't realize that there's a problem in their code until it's being exploited.

      "fopen_urls: By default you can include scripts hosted on other websites!" I'll agree, that should probably be off by default. But a developer has to be naive or dim to either use an URL include, or include a variable in the include directive (and thus introduce the possibility of a URL inclusion) without being damn sure what they're doing.
      I don't think you can blame the developer for this. If they develop with magic_quotes on, or register_globals off, or error reporting >E_WARNING, they may not realize the variable in the include string is writeable, and they probably wouldn't realize you can include remote documents anyway.

      "Input checking is difficult...Do you want htmlentities() or htmlspecialchars()?" Depends on what you want to do, now, doesn't it? Developers have to know what conditions they need their data to adhere to, and PHP gives them a variety of tools to make it fit those conditions. Feature, not a bug.
      What about add_slashes() not escaping everything that mysql_escape() does? Or mysql_escape() not escaping everything that mysql_real_escape() does? What about 5 == "5 OR 1=1"? What about the ability to input arrays (and errors which should be shown when dealing with unexpected arrays aren't printed because of the default error reporting level)? These are bad ideas which make sanitizing input difficult.
      It's easier to trip up badly in C (by commiting some memory buffer error) or Perl (by writing line noise code that you can't understand a week later) than PHP. But it's no longer fashionable to bash those languages.
      I wouldn't use C for the web either, and Perl can be very clear. I agree that PHP gets a worse rep than it deserves; I like PHP, and understand that if bash or C was the language of the web they'd be just as bad, but they're not and PHP is.
      PHP would be so much better if they fixed the security holes; one of the reasons it gets such a bad rep is because it lets newcomers make mistakes so easily, I'd like PHP to be recognized as the excellent language it is but these security problems aren't helping.

      Apparently what you see as "problems", others see as features.
      Some see pointers and no bounds checking as useful features, but that doesn't mean they're a good idea for security.
      --
      // MD_Update(&m,buf,j);
    3. Re:Who's fault? Zend's by TheLink · · Score: 4, Informative

      Definitely Zend's fault!

      From your post: "magic_quotes: This adds slashes to all input so that you don't have to sanitize it before it gets inserted into SQL."

      BUT that is so totally the WRONG thing to do and a MISFEATURE, and the fact that the PHP developers made it a big feature of PHP shows why they and PHP suck. Think I'm being harsh? Read on.

      This is what any sane programmer should do:

      Each input source for YOUR application should be _individually filtered and escaped so that _YOUR_ application can handle the inputs correctly.

      Each output destination for your application should be _individually_ filtered and escaped[1] so that the RECEIVING programs/entities can handle your app outputs correctly.

      Example:
      Say some data is http posted to a PHP web app, and the PHP app then sends the resulting data to a MySQL database, an Oracle database, syslog, and in some cases also emails some of that data to an email address, or redisplays the data in an HTML form on a web browser (required field left out).

      magic_quotes would add slashes to the data when it enteres the web app, and that CORRUPTS the data. The resulting munged data _might_ still work for MySQL, but as is be incorrect for Oracle and SMTP (<lf>.<lf> needs to become <lf>..<lf>), data to syslog should have ctrl chars removed or escaped _appropriately_ and to be safe kept < 1024 bytes in length, and data to an HTML form shouldn't have the added slashes, but instead be appropriately quoted for HTML.

      My proposal would have the web app filtering/escaping the data so the webapp can handle it, and then escape/filter stuff appropriately for MySQL, Oracle, SMTP, syslog and HTML. It seems like more work, but it is the correct way. It is less work in the long run especially if you make/use the appropriate libraries.

      Once you understand the above, you should see why magic_quotes is so TERRIBLE, and why I have a low opinion of PHP and Zend.

      And magic_quotes is not the only PHP misfeature that makes PHP PHP. You have named a few already.

      Basically PHP makes doing the wrong thing easy, but the right things hard[2].

      [1] by escaping/filtering I also include use of "SQL prepared/parameterized statements".

      [2] After all these years it's still not clear what DB abstraction layer/library to use for PHP - there's the PDO vs PEAR DB thing, and PHP users are still resorting to crap like addslashes and magic_quotes. If each PHP coder writes their own DB library, anyone else taking over has to learn it. PHP should have learnt from the other languages mistakes.

      For perl you use DBI, for Java you use JDBC.

      All this crappiness has to be blamed on the developers who made PHP.

      --
  14. there's plenty of blame to go around by larry+bagina · · Score: 2

    almost every php book or tutorial I've seen does incredibly dumb and insecure things... creating sql queries by concatenating strings without escaping input data, not using htmlentities, using global variables... that's an sql inection or xss problem waiting to happen.

    PHP makes it easy to do dumb things and harder to do the correct thing. There's a low barrier to entry, so many php "programmers" don't know what they're doing. (this also applies to javascript...).

    --
    Do you even lift?

    These aren't the 'roids you're looking for.

  15. PHP is no worse than C. by Ant+P. · · Score: 3, Funny

    C gives you enough rope to hang yourself with.
    PHP gives you lego bricks. Most PHP users, for some inexplicable reason, try to eat them and choke.

  16. Re:I have to agree.. by quadra23 · · Score: 5, Informative

    PHP does not give you a pretty library with prepared statements, parameter binding, and such. There's a nice DB and MDB2 package available on PEAR, but PHP doesn't ship with those. It ships with the compile option --with-mysql.

    Perl ships with a fair amount of stuff. It ships with a package named DBI. You can do things like $rv = $sth->execute(@bind_values);. The documentation on it starts off with a convenient set of good examples which go like

    $sth = $dbh->prepare("SELECT foo, bar FROM table WHERE baz=?"); $sth->execute( $baz );


    PHP 5.2 ships with PDO (PHP Data Objects) extension which can run with your example code provided you load the extension in your php.ini (yes, I know its a setting that is not done by default, but that argument doesn't hold water with PHP 5 anymore). PDO also supports the prepared statements and parameter bindings of which you speak, and along similar lines, you can also do transactions. You should be clear about which version of PHP your referring to as PHP 4.4 is no longer considered the main release and also has not been updated since August while PHP 5 was last updated in November.

    Though I can still agree that not all the choices made in the development were the best. AFAIK, every language has human developers and humans are not perfect, but we do do the best we can and have to continually aim to improve ourselves and the work we create.

  17. Re:mysql_escape_string, mysql_real_escape_string, by AdamPiotrZochowski · · Score: 4, Interesting
    FIRST : stop forcing prepared binded statements for all :

    I dont mind prepared statements for when they are usefull, but they dont always work properly. And actually there are many cases where using them you actually lose power. Lets start with a simple example of the LIKE clause :

    SELECT * FROM titles WHERE notes LIKE ?

    For the unfamiliar, like clause allows me to do partial searches over strings (char/varchar in the sql world). The LIKE clause search string syntax is something of a simplified regular expression. This means that characters that usually have one meaning gain another one. For example the percentage sign becomes a wildcard (think dos/bash filename matching with '*', or regexp with '.*'). For example, all string starting with 'word' we would just search for 'word%'. Great, but how does prepare/binded statement know if the given percentage is to be escaped or not. It doesnt. So you end up doing own user parsing. You are back to square one. You need to still parse user input, so whats the point of binded/prepared statement? Another example is using power provided through fulltext index. Generally, string searching is slow. In SQL world we do an index, a cache to speed up looking. Strings have indexes, but that only speeds up searching for string that start with something (like in above example LIKE 'word%') but what if we want to search for something purely inside the string ?? then we could do LIKE '%word%' but thats slow, on the other hand, we could speed this up by various smart caching and indexing of the contents of the string. This smart indexing we call 'full text'. For example to see if a column contains some word or phrase we could just do

    SELECT * FROM myData WHERE CONTAINS (column, ?)

    all ok, right? NOPE, because it also could be :

    SELECT * FROM myData WHERE CONTAINS (column, 'FORMSOF (INFLECTIONAL, ?)')

    To explain slightly, the second examples tries to find words that are not exact, but very close. So for word 'good' another word 'best' could be used as an alternative (with a lower relevancy ranking). Great power?? Yes, but the first time the sql expects the query in the form CONTAINS ( notes , ' "word" ') notice single and double quotes while later its CONTAINS(notes, 'FORMSOF (INFLECTIONAL, word)') notice, no quotes allowed...

    and dont even get me started with the

    SELECT * FROM myData WHERE column IN ( ? )

    The IN clause is a speed over a series of OR statements. I could write WHERE column = 1 OR column = 2 OR column =3 or I could just do it with WHERE column IN ( 1,2,3) . And now the question for the binding gurus. How do I do it with prepared statements ?? Do I create a loop and both generate the SQL and fill a flat array with the right amount of paramenters WHERE column IN ( ? , ? , ? , ? ) , or do I just send arrays within arrays.

    SECOND : parameter binding through naming :

    cant wait for when parameter binding can be done in a templated fashion, so that no longer order of the columns matters, currently the way you fill prepared statement with data matters by order of the data. It all should be done with associative arrays.

    $sth = $__db->prepare ( "select * from myData where cond1 = ? and cond2 = ? " ) ;
    $res =& $__db->execute ( $sth , array ( $userInput1 , $userInput2 ) ) ;

    it should be done more like

    $sth = $__db->prepare ( "select * from myData where cond1 = ?userInput1 and cond2 = ?userInput1 " ) ;
    $res =& $__db->execute ( $sth , array ( "userInput1" => $userInput1 , "userInput2" => $userInput2 ) ) ;

    There is no special need to input more -- if you want, use the first method just pass non associative array, and library should know to handle param binding in old way -- but for any larger querry, with dozens of parameters, this will be a big boon in readab

  18. Speaking as a PHP Framework Developer by Foofoobar · · Score: 5, Interesting

    I used to work with the Zend team and they seem determined o pander to the least common denominator of hobbiests and not allow the language to grow up. Things like nested classes and strongly types variab;es which should have been implemented in the latest version are strongly fought against. They things as well as other would help enforce good coding standards. But I have been told by the Zend developers themselves that they like to leave it up to the developer to code badly and to me that makes the language just as much to blame. I think the industry has established by now what are good programming habits and methodologies and what aren't.

    --
    This is my sig. There are many like it but this one is mine.
  19. Re:mysql_escape_string, mysql_real_escape_string, by VGPowerlord · · Score: 2, Informative
    To the first part:
    When you're using like statements, you will have to pre-process things, yes. Most notably, escaping % and _ plus any other rules you want to implement (* to %, ? to _, explode on spaces with multiple LIKE statements to search on keywords, etc...).

    SELECT * FROM myData WHERE CONTAINS (column, 'FORMSOF (INFLECTIONAL, ?)')

    Parameters are intended for user input. I certainly hoping you aren't allowing users to type functions in directly...

    As for IN, I build up the placeholders using something like...
    $placeholders = array_fill(0, count($search_params), '?');
    $placeholders = implode(', ', $placeholders);
    $query = "SELECT last_name, first_name FROM patients WHERE disorder IN ($placeholders) ORDER BY last_name";

    Then bind the parameters when running the query. (I use ADODB for PHP.)
    --
    GLaDOS for President 2016! "Well here we are again. It's always such a pleasure." -- GLaDOS, 2011
  20. Re:mysql_escape_string, mysql_real_escape_string, by AdamPiotrZochowski · · Score: 2, Insightful
    SELECT * FROM myData WHERE CONTAINS (column, 'FORMSOF (INFLECTIONAL, ?)')

    Parameters are intended for user input. I certainly hoping you aren't allowing users to type functions in directly...


    For one of the servers I worked on this was the syntax for full text search. you would do CONTAINS ( column , param ) . The argument param was a string that contained additional properties for the full text search engine. One could add things like weights associated with words and phrases (hence double quotes), or ask to search for word variation (search for 'good' also matches 'best', since they are related). Ofcourse, this was all happening in one string, that param, so you had to, yet again, format your own string.

    I am not advocating against using parametered sql calls, actually they are great, but I fear that on some level they are not much better than the magic_quotes=on, I fear as if they were an escape for lazy developers : use always, and your code will be unhackable. That was the premise of magic_quotes, it made developers feel safe, as if magically their code was unbreakable.

    Now, for stored procedure calls, especially with parameters that double as both input and ouput, the parameter binding is the only way to go.

    Cheers
  21. neither and both by JoeCommodore · · Score: 2, Insightful

    The arguments:

    PHP is secure as in it has the functionality to make secure sites.

    PHP is insecure in that some of this is not implemented from the get go.

    PHP is flexible as it does not force security on you - if for any reason you are running in an isolated environ or implementing something different attached to PHP.

    By not being as strict in variable typing, etc. there are some things that can be done more directly in PHP then in other languages. Though it could cause hidden errors in good code as well.

    There is stuff that can be fixed, Zend should get some of the hard housecleaning done (magic quotes, register globals, etc.) in a version # release (those who can't stick with 4 or 5 etc.) Though you then need to get the ISPs to upgrade and all the legacy scripts...

    ASP, Java, Perl and Ruby people would like to see more stuff in their languages than in PHP (and will FUD PHP to promote thier cause good or bad).

    I chose PHP because:
    - it is on most webhosts and distro installers
    - a lot of great code and/or projects are readily available in PHP.
    - the language does everything I require and then some
    - the syntax is VERY easy to read and understand - this includes my own code as well as learning from others.
    - it is platform agnostic (no lock-in)
    - it is not limited by licensing (if open source, which is ok for me) or vendor-control code restraints
    - it works with many platform agnostic DBs also
    - even the security issues are well documented and understandable and does teache you a lot more about web security than languages that just do it for you (or that you assume are secure).

    So for me I know the drawbacks and I see the benefits, and the benefits are worth the extra effort.

    In summary I see that it has worthy merits and also "warning labels", (such as this slashdot post illustrates) the devs will make up thier own mind on using it, get over it.

    --
    "Enjoy what you're doing! If it becomes drudgery, you're doing it wrong!" - Jim Butterfield
  22. Every Scripting Language Has Problems by Biffa · · Score: 2, Insightful

    The first web scripting language that I did any sort of serious development with was Cold Fusion 1.0, late last century. It was simply amazing how much quicker the development of database-driven websites became. (Prior to that, I was compiling custom DLLs to load into IIS - or whatever it was called way back then.)

    I very quickly made a whole series of small web applications to access our internal data - something that I later found out was called an "intranet".

    Then, one day, when I was testing a form, I heavy fingered the single quote ' and the enter key on an input box and got some surprising results! The SQL statement got completely destroyed by including the quote in the input box. I actually thought this was fun, and typed in additional SQL to see if I could change the query. It was easy! I made the query do all kinds of weird things. This got me toying with forms that actually did inserts and adding random stuff to the query string and I realized how trivially easy it was to completely subvert all the smallish applications I had written. Thank the Lords of Kobol it was an internal site!

    At any rate, I learned, in my safe sandbox, that securing a web application is not trivial nad is something you have to think about from the moment you sit down to code. I developed a bunch of functions to verify the existence of, escape, and validate every single piece of data that is ever passed from the UI to the database. You just have to do it, it's that simple.

    Since those early days, I've done sites in Cold Fusion, ASP, JSP, PHP, Perl, WebCatalog and a couple of other oddballs, and I've always started by translating those functions to the new language, using the built-ins of the language when I could. You know what? All web scripting languages that are easy and powerful wind up being insecure in the hands of an inexperienced developer.

    And let's be honest, if there was a secure and easy to use web scripting language, we'd all hate it because it tied our hands too much and made us do things a certain way. We, serious developers, love languages that let us do things the way we want to do them. Assembly developers feel confined by C, C++ developers feel confined by Java; HTML hand coders feel confined using Dreamweaver. So honestly, if they came out with SecurePHP, largely not backwards compatible for one thing, would anyone use it?

    I know I'd WANT to, in theory, but would I? Would you?

  23. Re:mysql_escape_string, mysql_real_escape_string, by shoolz · · Score: 2, Insightful

    Oh man your comment really bothers me. If you are relying on a PHP function to ensure user submitted data is trustworthy then you don't have PHP to blame if something goes Ka-blam due to a malicious user. I don't care what language you're coding in... if you trust user-submitted data without putting it through multiple rigorous tests, then you have nobody to blame but your naive self.

  24. Re:mysql_escape_string, mysql_real_escape_string, by Daytona955i · · Score: 2, Insightful

    mysql_escape_string and mysql_real_escape_string should both work [...] but the former is deprecated as PHP 4.3.0 in favor of the latter; it also does not respect the current character set setting.

    Does anyone else not see a problem with this? Oh first we had addslashes but a lot of people complained, then we added mysql_escape_string but we decided it didn't work (for whatever reason) so now we have mysql_real_escape_string so people should be happy now. Oh and we have a magic_quotes variable you can set to automatically do this for you, but it might not be enabled on every instance of php.

    And then we have:
    PEAR::DB is a nice database abstraction (somewhat like perl DBI). Although it's been superceded by PEAR::MDB2. PHP 5 has native PDO, which is also like DBI or DB, or MDB2, but each one has a slightly different syntax.

    <sarcasm>Wow, these PHP developers really make it easy to do something simple like query a database! </sarcasm>

    First I have a problem with lack of namespaces. Yes, you've heard it before but the above illustrates why it's a problem. If I instead had two libraries, mysql_escape and mysql_escape2 (bad names but bear with me), I could now have them use the same function names so I don't need to have mysql_escape_string and mysql_real_escape_string. To upgrade, I just change what library I include and I'm done. Having all these functions always accessible creates an inconsistent naming of functions.

    I currently program in PHP as my real job.... I rarely use it in my personal web based projects preferring python or Perl (Possibly looking into Ruby at some point) because I've come to really dislike the language. However I also don't think it's as bad as some people make it out to be.

  25. Security is about education by AutopsyReport · · Score: 2, Informative

    Security is primarily about education and not the language. I've been deploying public PHP applications for clients for years. In the early years problems were more abundant (registered globals, etc.), but in the later years (PHP5), the storm has calmed and common practices and patterns have been discussed, encouraged, and implemented so thoroughly that anyone making common mistakes these days simply hasn't educated themselves adequately.

    And this isn't just the fault of the developer. Unfortunately there's too many resources and options available, all of which have differing and conflicting methods for accomplishing something. Letting an uneducated developer decide which option to pick, I would agree, is not desirable.

    But let's be clear on something: I design, build, and deploy enterprise-grade PHP applications for multi-million dollar projects. If there's a security problem discovered, it is my or my team's fault that we didn't protect against it. It's my responsibility to be educated enough to diagnose and prevent security threats in an application. I cannot say to the client, "PHP is inherently insecure", and expect that reason to fly and absolve myself of all responsibility.

    I clearly do not understand why this excuse is the predominant argument here. "PHP is inherently insecure" is simply not true. PHP certainly doesn't encourage proper programming practices from the beginning, but by the same token, I can't recall a programming manual that doubled as an education tool in design and security practices that, combined, allowed me to write bulletproof code from the very beginning.

    --

    For he today that sheds his blood with me shall be my brother.

  26. Re:PHP == fucked by AutopsyReport · · Score: 3, Informative

    PHP is an awful language, doesn't scale

    How many times has this been said, and how many times do people need to point to examples like Wikipedia, YouTube (partially), Yahoo, Google, Facebook, and much more for proof of scalability?

    And if you mean PHP doesn't scale architecturally, then you've demonstrated that you've never worked in an environment that did effectively scale PHP, or you simply failed at it. I'm going to guess both.

    --

    For he today that sheds his blood with me shall be my brother.

  27. Pretty damning statement. by Generic+Player · · Score: 2, Insightful

    I'd argue PHP is actually worse than C, since C at least behaves consistantly and doesn't depend on the settings in some .ini file to get reasonable behaviour. But even if PHP is "no worse than C", that's still incredibly bad for a language designed specifically for web development. C is dangerous because its portable assembly. PHP has no excuse for being dangerous, it was designed specifically for a security sensitive task in an era where exploits had already become common place. The idea of exploiting software was quite foreign in the early 70's when C was born.