Forgot your password?
typodupeerror
PHP Programming Security

PHP Application Insecurity - PHP or Devs Fault? 200

Posted by Cliff
from the and-what-would-be-the-best-way-to-fix-the-problem dept.
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?"
This discussion has been archived. No new comments can be posted.

PHP Application Insecurity - PHP or Devs Fault?

Comments Filter:
  • by Anonymous Coward
    and addslashes. quick, which one is SQL secure?
    • by FooAtWFU (699187) on Thursday January 11, 2007 @11:50PM (#17568376) Homepage
      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 [php.net], 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...

      • Re: (Score:3, Insightful)

        by shoolz (752000)
        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.
        • Whilst I agree that the programmer needs to be responsible, the fact is that many people "programming" with PHP are _not_ programmers, or at the very least, are inexperienced programmers. So consequently, they write insecure applications.

          So the argument that the developers of PHP could do more does seem valid! And the point that the previous poster made about lots of poorly coded functions, also seems valid.
      • Agree totally.

        I've only recently got into using PHP myself. I am an experienced programmer, but it is surprisingly difficult to find a good solid way to properly escape MySQL statements. And before anyone asks, I'd write a function myself (like I've previously done with ASP/SQL server), but MySQL itself seems to allow.... lets say, at lot of "flexibility" in the encoding that can be used, and similarly, I couldn't easily find a complete description of this.

        And sadly, googling for answers tends to pull u
    • Trick question.

      None of the above, use bind variables instead.
      • 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

        • Re: (Score:3, Informative)

          by VGPowerlord (621254)
          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

          • Re: (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

    • That's a trick question. The correct answer is "bound parameters using PDO."
  • Tool safety (Score:3, Interesting)

    by nacturation (646836) <nacturation@gma[ ]com ['il.' in gap]> on Thursday January 11, 2007 @11:36PM (#17568218) Journal
    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.
     
    • Re: (Score:3, Funny)

      by nocomment (239368)
      His chainsaw probably wouldn't be so dull if he spent less time jerking.
    • Re:Tool safety (Score:5, Interesting)

      by Beryllium Sphere(tm) (193358) on Thursday January 11, 2007 @11:48PM (#17568350) Homepage Journal
      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.
      • by mcrbids (148650)
        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.

        As a student pilot (I should have my license by Feb/March) I've read quite a number of crash analysis reports, as well as a large number of articles reporting "near misses", all in General Aviation. (lightweight, personal planes)

        It's just amazing to me how many of these incidents are caused by things like the pilot shu
        • Re:Tool safety (Score:5, Insightful)

          by Cecil (37810) on Friday January 12, 2007 @03:58AM (#17570224) Homepage
          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.
        • by ultranova (717540)

          I mean, what f--king retard puts a "kill gas" switch in easy reach of a pilot in the air? Can you name *ANY* scenario where it is an advantage to kill the fuel flow while in the air?

          The engine catches fire ? Not that that justifies putting the switch where it's easy to hit it by accident, not putting any kind of safety device (a button you need to push to move it, or something like that) on it, and not coloring it yellow with black stripes and a text with large red letters right next to it saying: "DANG

    • Given your example of a chainsaw, you might want to google words such as anti-kickback chain, chain brake, hand guards and/or just the general chainsaw safety keywords.

      You might learn something.
    • Re: (Score:2, Insightful)

      by pyite (140350)
      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.

      Wow. If that's your actual, honest opinion, you scare me. It looks like "personal responsibility" is all but nostalgia for people. You know, I can make a chainsaw that I can guarantee almost 100% won't cut you, but it proba
      • Re:Tool safety (Score:5, Insightful)

        by VGPowerlord (621254) on Friday January 12, 2007 @01:32AM (#17569296) Homepage

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

        1. addslashes() [php.net] 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 [php.net] 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 [php.net] controls the programming environment. Turning on things like Safe mode [php.net] and open_basedir can cause previously working code to suddenly fail. Of course, php.ini-dist has display errors [php.net] 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 [php.net], which is enabled in both ini files by default. See also Magic Quotes as described earlier. Reading up on the deprecated Register Globals [php.net] 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.
    • by tacocat (527354)

      I would almost agree with you because this would be a perfect time for me to wave my Perl is Better flag. But there is a point to this story but there's also a nasty history to PHP as a language.

      There are many choices to which language you want to make a website/webpage in and there is a pretty reasonable opportunity in any of them to horribly insecure things. Given the best language, an idiot can make it insecure. As a corallary even the worse language can be made secure. Even BASH can be done securly

  • by lambent (234167) on Thursday January 11, 2007 @11:40PM (#17568264)
    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.
    • by Schraegstrichpunkt (931443) on Thursday January 11, 2007 @11:52PM (#17568402) Homepage
      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.
      • Re: (Score:3, Insightful)

        by lambent (234167)
        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.
        • by Coryoth (254751) on Friday January 12, 2007 @01:24AM (#17569228) Homepage Journal
          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.
        • Re: (Score:3, 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 &amp;lt;em&amp;gt;any&amp;lt;/em&amp;gt; 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 t

        • by Cecil (37810)
          It's YOUR problem, not anyone else's ... If you don't like that, choose another language.

          So basically you're admitting that it is PHP's fault, and that other languages don't have nearly as severe a problem with insecurity-by-default. I'll agree.

          In a perfect language, a security hole should always be an error of commission, never an error of omission. No language is perfect, but in that respect, most are a damn sight closer than PHP.
      • by Jack9 (11421)

        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.

        I wrote my first DB abstraction in PHP/FI in 1997. I've never ever used PHP for anything other than web development as it's not explicitly designed for anything else. The previous quote is from someone doing what any professional PHP programmer knows not to do. Trying to program non-web applications in PHP (forgive me if you mean you arent experienced enough to m

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

      A few years back (circa 2002), I whipped up a rapid application prototype with PHP while working off from some on-line tutorials and using Beginning Php 4 (Programmer [amazon.com]

  • by Schraegstrichpunkt (931443) on Thursday January 11, 2007 @11:41PM (#17568280) Homepage
    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.
  • PHP provides a means to access the fields of a form submit as strings.. not as integers.. not as dates.. not a html input boxes.. as strings. The default and common usage of accessing the fields of a form submit should require that you provide a type. Similarly, the default and common usage of accessing the fields of a form submit should do SQL escaping for you. If you find out you have a problem with that escaping, you should be able to turn it off... but the escaping should happen by default and should
    • by numbsafari (139135) <swilson.bsd4us@org> on Thursday January 11, 2007 @11:49PM (#17568370)
      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.
      • by blincoln (592401)
        Because no user input should ever be executed.
        (snip)
        People should use parametric SQL statements. No excuses.

        Agreed, however:

        In this manner, no escaping is ever necessary.

        You're still going to have problems in languages like Javascript that have methods like "eval()". I don't know if PHP has one (I'm just starting to look at it this week, I'm not a fan of web development in general), but if it does, all the SQL escaping in the world won't necessarily matter. You can't escape for multiple different languages
    • by MysticOne (142751)
      But PHP doesn't really have types, nor do HTML forms (aside from the differences between buttons, check boxes, etc.) And always escaping for SQL? That's the job of the SQL libraries, not the language itself. At some point a developer has to take responsibility for what they write, and they should handle data appropriately.
      • Re: (Score:3, Insightful)

        by FooAtWFU (699187)

        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 thos

        • by MysticOne (142751)
          I don't disagree that PHP is very ugly at times (with function names that are anything but consistent). I agree with pretty much everything you said, and that it IS easy to do bad things in PHP. But I do still think it's the developer's responsibility to know their language and use it appropriately. Also, does Perl actually come with DBI? I was thinking you had to install it separately from the base distribution (i.e., via CPAN or something).
          • You have to install DBI separately, but CPAN will automatically install DBI when you install any DBD module.
            • Alternatively, you can use a good OS with a package management system that's worth two squirts of piss. That way, you're kept up to date on security vulnerabilities, dependencies are handled, you don't have to futz around with CPAN config, and you're move to the next version of the OS in 3 years is not a moving target.

              You can also install your app on another server of the same os and be almost guarenteed of the same functionality, as opposed to installing the latest cpan module on a server you just configur
        • Re:I have to agree.. (Score:5, Informative)

          by quadra23 (786171) on Friday January 12, 2007 @12:41AM (#17568852) Journal
          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.net] (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 [php.net] and parameter bindings [php.net] of which you speak, and along similar lines, you can also do transactions [php.net]. 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.
          • by Alioth (221270)
            The trouble is that PHP is a particularly egregious example of sloppy design. I prefer to name it in the vein of PGP - if PGP means 'Pretty Good Privacy', then PHP means 'Pretty Hopeless Privacy'...
    • I have to disagree with you. Form values are sent over the line as strings, and as such, they should be treated as string by the base language/framework. I mean, who's to say that when you enter "3125551212" on a form, that you are talking about an integer number or a phone number string?

      As far as SQL injection, every RDMBS access method that I know of allows the developer to execute arbitrary queries. The trick isn't to have automatic SQL escaping (again, the language/framework isn't smart enough to dif
  • by numbsafari (139135) <swilson.bsd4us@org> on Thursday January 11, 2007 @11:42PM (#17568300)
    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.
    • by MysticOne (142751) on Thursday January 11, 2007 @11:55PM (#17568422) Homepage
      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.
      • Re: (Score:2, Interesting)

        by numbsafari (139135)
        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
        • by gbjbaanb (229885)

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

          Yep, this includes the developers of the PHP language itself. :)

          My personal opinion is that PHP should come out-of-the-installer with *all* its security features turned on. Safe_mode, register_globals, syscall restrictions, open_basedir set to the home directory even. Then, all the new PHP devs to the language will more likely work with these features. Of course, they can still be turned off if necessary, but I hope less people will do that.

      • by Shados (741919)
        Think of it this way: You know of IE's ActiveX, yes? You know how much of a security nightmare they are? Yet, they exist to make developing for IE easier and more flexible, and easy, without having to worrie about all these security settings, sandboxes, certificates, blah blah blah. Look what happens from that. Easy, flexible and fun should be balanced with robbust and well designed, thus later environments fixed that, but we still today live with the ActiveX mess.

        Same thing here with PHP. Yeah, its fun and
        • To be fair, PHP disabled the whole "post variables become PHP variables" by default back in PHP 4.2.0.

          Also, error_reporting(E_ALL); will make PHP throw warnings (but not die) when it runs in to undefined variables.
      • by jrockway (229604)
        > Is it really that PHP makes it that hard to be secure

        Yes, it really is. Perl has had "taint mode" forever. This forces the programmer to validate all input before passing it to things like database queries or open(), system(), etc. Instead of a coding error causing you to lose all your data and take out your web server, the program will just exit. Having the compiler double-check your work is always easier than wondering if you got everything.

        Adding to that is the fact that PHP has never had a sane
      • Dangerous code should look dangerous. In PHP, if you say "include $variable", and an attacker can set the value of $variable, then attacker 0wns your machine. Name another language in which include executes remote code.

        The problem with PHP is that insecure code doesn't look like insecure code ... unless you're a PHP expert. And yet PHP is pitched to people as an easy way to write websites -- which it is.

        If the "include" primitive was renamed to "includehostilecode", it would still be useful, but its shar
    • Re: (Score:3, Insightful)

      by lphuberdeau (774176)
      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
      • by jrockway (229604)
        I trust PHP security experts about as far as I can throw them. This guy [chxo.com] is the author of a PHP security book and I found many many severe security problems [seclists.org] in his published code. To parse XML, for example, he cleverly injected some PHP into the string containing the XML fetched from an untrusted server, and then eval()d the whole mess. Needless to say, that's not a very secure way to parse XML!

        If this is how published security experts write PHP, I pray to god that I never have to look at any entry-level
    • An entire class of common web-programming bugs, Cross Site Scripting, could be eliminated if people would use DOM.

      Currently, common practice for dynamic web applications is to build your output HTML document piece by piece, string-wise, splicing variables left and right to get the desired result. Unless you're extremely diligent in properly encoding plaintext to HTML (meaning changing <, >, &, and sometimes " and ' into HTML character entity references), you will slip up and people will find wa

    • Re: (Score:3, Insightful)

      by madstork2000 (143169) *
      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,
  • Yes (Score:4, Insightful)

    by Rycross (836649) on Friday January 12, 2007 @12:13AM (#17568578)
    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.
    • but that doesn't mean we can't damn programming languages

      Reminds me of Spock in Star Trek IV. :)
    • There's a reason that we've moved away from languages such as C, except when necessary.

      I do it differently, I move away from languages such as C *only* when necessary. Safety measures are indispensable, but there is such a thing as overdoing it. Motorcycle drivers should use helmets, but not truck drivers. Car seats should have safety belts, but not bar stools. And so on.

      When I do a web page that will get input from the outside world I take care to use parameterized queries, but when I do a quick developme

  • by kestasjk (933987) * on Friday January 12, 2007 @12:21AM (#17568642) Homepage
    I've audited quite a lot of PHP, written an article [kuliukas.com] on PHP security from the hackers perspective, and done quite a lot [phpdiplomacy.net] 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 [slashdot.org] 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.
    • Re: (Score:2, Insightful)

      by Mr. Slippery (47854)

      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
      • by kestasjk (933987) * on Friday January 12, 2007 @02:41AM (#17569708) Homepage
        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.
      • by jrockway (229604)
        > Perl (by writing line noise code that you can't understand a week later)

        What? PHP has even worse syntax. Everything requires parentheses @print(foo(@$bar[$this->baz()->something(array(1,2 ))->else()])). At that point, you might as well be using LISP. Not to mention that 90% of PHP's syntax is completely useless and has no reason for existing. (Why bother with dollar-signs in front of $variables when EVERYTHING IS THE SAME TYPE? Why bother with an OO model that uses interfaces when THERE
      • You can't really say PHP is better than Perl.

        See http://tnx.nl/php [tnx.nl] for a great comparison.
      • by LizardKing (5245)

        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.

        They'll be dead issues when they are removed completely from PHP. Too many tutorials and existing PHP applications turn them on if they aren't by default. As for "good ideas", they never were.

        Configurable logging and reporti

    • by TheLink (130905) on Friday January 12, 2007 @03:29AM (#17570018) Journal
      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.

  • 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...).

  • by Ant P. (974313) on Friday January 12, 2007 @12:30AM (#17568732) Homepage
    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.
    • That's .sig material right there.
    • 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
  • I have been working with PHP for over six years at this point. I have worked with bad developers and good developers. The good developers write good, secure code. The bad developers write bad, insecure code.

    This doesn't seem to change when the language changes, either.

    There are simple fundamentals that good programmers follow that the bad ones do not; Correct error handling and reporting, data validation, etc., etc.

    If it was the language's fault, or the fault of the tools, companies like Yahoo and Google wo
    • by jrockway (229604)
      > companies like Yahoo and Google would not be using it

      Companies like Yahoo and Google use it for non-critical applications because they can easily hire as many minimum wage code monkeys as they need. When you're a big company, that hiring liquidity can often outweigh the fact that developing code is probably more expensive in PHP than sane languages. There's a reason why Google uses C++, Python, and Java for most things.
  • by Foofoobar (318279) on Friday January 12, 2007 @01:13AM (#17569120)
    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.
    • It's not even that they leave it up to the developer to code badly. They make it easier to code badly than to code correctly[1].

      Just using the infamous (mis)features that make PHP PHP, automatically make your code bad. e.g. magic_quotes, register_globals, addslashes etc.

      PHP - making the wrong things easy, and the right things hard.

      [1] http://ask.slashdot.org/comments.pl?sid=216482&cid =17570018 [slashdot.org]
      • by Foofoobar (318279)
        I agree. One of the developers gave me the excuse' it would be too hard for developers to understand' as the excuse for not using better programming methodologies. The developer would adapt and if it was too hard, how come other developers in other languages aren't having a problem picking it up. It's really discouraging since I'm developing an MVC framework for PHP and am beginning to hate the language because the developers in it can't grow up because the maintainers of the language don't want them to.
  • The whole blame PHP or blame the programmer argument ultimately falls onto the programmer. If you use too small of a bit and end up stripping out a screwhead, should you blame Black & Decker for it? Of course not. Likewise, if you use PHP the wrong way, should you blame PHP for it?
    • by nuzak (959558)
      > If you use too small of a bit and end up stripping out a screwhead, should you blame Black & Decker for it?

      If that's the only bit that comes in the set, yes. PHP could have deprecated its old single-string DB APIs. It didn't. People still use them, and sometimes they even take your credit card data with them.
      • The greatest flaw to PHP is that it opens up more power than many of its users can handle. When you had to compile CGI binaries, it placed explicit limits on who could work on web apps. Now? The power that was once reserved for a handful of good programmers is opened up to all sorts of non-programmers and novice programmers.

        What is needed is better education. An up-front warning to the non-programmers about what exactly it is they are getting themselves, their clients and their clients' customers int

  • neither and both (Score:3, Insightful)

    by JoeCommodore (567479) <larry@portcommodore.com> on Friday January 12, 2007 @02:49AM (#17569758) Homepage
    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.
  • 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 hea
  • What all of the "PHP is insecure" claims refuse to recognise is that virtually all of the vulnerabilities reported would be no different had the application been written in some other language. PHP just has a huge installation base so of course there will be a corresponding increase in vulnerabilities. And lot's of newbies are not escaping things. Perhaps most damaging, high profile vulnerabilities in popular third party packages are giving PHP a bad name (e.g. phpBB). Language bashing is fun (what happened
    • by arevos (659374)

      What all of the "PHP is insecure" claims refuse to recognise is that virtually all of the vulnerabilities reported would be no different had the application been written in some other language.

      Most complaints seem to revolve around PHP's SQL handling and PHP.ini inconsistencies. Can you name another programming language where the language semantics can be altered via a global ini file? How many other languages advocate using insecure functions in the official manual? To quote the PHP manual on addslashes:

      Returns a string with backslashes before characters that need to be quoted in database queries etc.

      And:

      An example use of addslashes() is when you're entering data into a database.

      This would rather suggest to those unfamiliar with the language that addslashes should be used to database input, rather than using the quoting function provided by the database libra

  • Blame goes to both the programmers and the language. Ultimately, it's the programmer's fault if they write insecure code. Even in the very exceptional case where the language does not allow secure code to be written (which I think has been true of PHP a few times), the programmer can still be blamed for choosing to write code in the language. So the programmer is always at fault.

    Having said that, the language certainly has an influence on what (security) bugs can be made or are likely to be made. As I've ex
  • by AutopsyReport (856852) on Friday January 12, 2007 @09:11AM (#17571992)
    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.
  • Let's not loose our focus. If you want to talk about guilt and who's responsible it's first of all the hackers and crackers. No matter what site they attack and what language it's writtten in. Website hackers are criminals and are the guilty. If my PHP website get's hacked (happend just a few weeks ago) it's the hackers fault. Not mine, not PHPs. As far as I'm concerned he should go to jail or pay for my expenses plus a hefty fee.

    Apart from that it is, of course, my responsibility to keep my website safe, n

Line Printer paper is strongest at the perforations.

Working...