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?"

200 comments

  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 KillerCow · · Score: 1
      It's much better to start with a tool that prevents such mishaps rather than being unsafe by default.


      But... performance... power... flexibility... waaaaaaaaaah.
    2. 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 */
    3. 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.

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

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

      --
      Ewige Blumenkraft.
    5. Re:Tool safety by ChengWah · · Score: 0, Troll

      Just like it's vehicle manufacturers who kill and maim on the roads. If you can't or shouldn't drive then don't. Same applies to programming. Many programmers are optimists - poor misguided fools. If you write software, try to break it before you release it, or don't bother writing it in the first place.

    6. Re:Tool safety by mcrbids · · Score: 1

      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 shutting off the gas while in the air inadvertently.

      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?

      Another one: the stall. Why is it that the stall horn isn't rigged to the yoke, so that when you're about to stall (and potentially die, esp. during takeoff/landing) the yoke has pressure applied to it so that you have to actually try to stall the plane?

      And, why not do something similar to put some pressure on the yoke the other way when you are getting close to maximum speed? (Vne)

      Just stupid shiat that really, really, REALLY annoys me as a software engineer. How much of my time do I spend trying to anticipate the insane stupids done by my users?!?!? If I'm aware of a problem caused just twice by a stupid from a user DESPITE OBVIOUS WARNINGS, I change the button or something so I don't get the calls anymore.

      Now, if somebody's life was on the line, don't you think they'd hide the damned "kill gas" switch, or at least make it require a concerted effort to turn it off? (think: automatic transmissions in most modern cars, which require you to push a button or something to get it out of drive into reverse or park)

      It'd be nice if small plane designers thought about safety just a tad more.

      --
      I have no problem with your religion until you decide it's reason to deprive others of the truth.
    7. Re:Tool safety by pyite · · Score: 1, Insightful

      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 probably won't cut any wood either. In fact, while we're at it, we should make chefs use plastic cutlery, because gosh darn it, they might hurt themselves with those big, sharp, metal blades.

      Tools are tools. While tools can certainly be poorly designed, they should never be crippled just because people might "hurt themselves." This applies for real tools and it applies for software.

      --

      "Nature doesn't care how smart you are. You can still be wrong." - Richard Feynman

    8. Re:Tool safety by Anonymous Coward · · Score: 1, Funny
      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?
      I'd guess that an engine fire would be a pretty good time to use that particular switch.

      Having read a bit about kit planes, I've gained some serious respect for some of those "f--king retard" aircraft designers. I think I'll take their designs over your, my friend.
    9. 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
    10. Re:Tool safety by Anonymous Coward · · Score: 0

      From the page linked to for 'display errors':

      display_errors boolean

      This determines whether errors should be printed to the screen as part of the output or if they should be hidden from the user.

      Note: This is a feature to support your development and should never be used on production systems

      If you're too lazy to actually go through the conf file that's kind of your own problem, no?

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

    12. Re:Tool safety by rTough · · Score: 1

      This is probably the best comment I've seen =) thank you.

      There are some differances however.
      1. Pilot are educated. They need a license. A programmer does not.
      2. Programming is harder. Let's say a programmers controlpanel is many times more complex.

      But a really lovely argument otherwise. I will use it in the future =)

    13. Re:Tool safety by tacocat · · Score: 1

      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 but you really have to know your stuff. The key is entry barriers.

      Low entry barrier means lots of inexperienced programmers and get-rich-quick programmers start flocking to PHP to make all their blogs and such with dreams of becoming the next uber-prince or uber-princess in their community. So you learn to program quickly with visual results. But there's never any effort to try and actually learn what is going on or what can be done to make things secure because security is of no concern in a results oriented development model.

      Contrast this with something I'm familiar with, Perl. It's got a large entry barrier. Anyone who does more than basic CGI in perl is a real programmer first who started making web pages. Security is much easier to enforce even a rudimentary levels. And since you have to learn how to really program first, doing something in a secure or sane manner is much easier to conceptually impliment as you are building your websites.

      Because the entry barrier is higher in perl the only people who write in perl are programmers and not the script-kiddie types who only want to learn enough to get a page to render. The quality of the programmers is a direct relationship to how difficult it is to learn the language. Lower the barrier and you get idiot programmers. Make the language insanely popular and you get idiot programmers. There are a number of examples of this that I've experienced in my life.

      PHP is too easy to get started on and everyone just assumes everything will work perfectly. It is not a bad language in itself but it allows bad people to write programs.

      Java has a great certification program and if you get certified you can get a job. Hence there are a lot of java programmers that don't really understand what Java is doing when they write programs. My company is routinely hit with major system outages becuase the Java someone wrote either has memory leaks, race conditions, fails edge conditions. Any application log will reveal 10,000 or more RUNTIME and NULL POINTER Exceptions in a day.

      Perl programs that I've seen tend to be written only by a few people in the company and they know a heck of a lot more than just perl. They have a solid foundation in networking, security, databases, hardware that gives them the knowledge to make really good programs. The interesting thing is that I've been to a variety of conferences and have found the Perl conferences to have a general population of users who are more generally knowledgeable about perl and computers in general than any other group. If you present insecure code at a perl conference you will get tagged in about 5 seconds (seen it). If you present insecure code in Rails conferences and someone tags it (minutes by the way) it's debated if it really matters. Do that at a perl conference and they start forming a circle around you.

      PHP could do the same thing, but they need to develop the mentality from experience and time. Being the easiest programming language to use for web pages isn't always a good thing. And I personally think that you will never remove this problem of easy access languages bringing in problems of insecurity and bad coders. The only thing PHP can do is make it harder to program or come up with an even easier language.

    14. Re:Tool safety by VGPowerlord · · Score: 1

      Before anyone accuses me of straw-manning this, I made mention of display_errors and php.ini-dist as well as php.ini-dist and shared hosting in my last post.

      People who use shared hosting systems have one of three problems:
      1. The errors are shown for everyone to see. (display_error on)
      2. The errors are hidden in the syslog or error_log where they can't see them. (display_error off, log_error on)
      3. The errors are thrown away completely. (display_error off, log_error off)

      The other catch is that packaging systems tend to preinstall php.ini-dist as php.ini rather than using php.ini-recommended. This means that, if you just install it from apt without checking the ini, you get the one with behavior that isn't recommended by default. Which is, in itself, a problem.

      --
      GLaDOS for President 2016! "Well here we are again. It's always such a pleasure." -- GLaDOS, 2011
    15. Re:Tool safety by metallic · · Score: 1

      You can always use ini_set to override some of the settings in php.ini if you are in a hosting environment.

      --
      Karma: Positive. Mostly effected by cowbell.
    16. 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.

    17. Re:Tool safety by ultranova · · Score: 1

      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: "DANGER! Engine kill switch!" with a grinning skull drawn around it for emphasis.

      --

      Forget magic. Any technology distinguishable from divine power is insufficiently advanced.

    18. Re:Tool safety by the_B0fh · · Score: 1

      You forgot one part - when PHP was first created, it stated direction was for non-programmers to program. While I'm all for lowering the barrier of entry to most things, if you do not have a good understanding of design and security issues, whatever you write will probably be crap.

      Also, for all your points about perl, perl was pretty much in php's place previously, look at matt's scripts and not matt's scripts. I think documentation, and having a strong community that cares about security is really key.

    19. Re:Tool safety by nacturation · · Score: 1

      Wow. If that's your actual, honest opinion, you scare me. It looks like "personal responsibility" is all but nostalgia for people. Having a failsafe airlock on the space shuttle doesn't cripple the functionality of the space shuttle. I suppose they could have made it unsafe and left it up to the astronauts' sense of personal responsibility to live with the consequences... but if safety doesn't impact overall functionality, why wouldn't you make your tools safe?
      --
      Want to improve your Karma? Instead of "Post Anonymously", try the "Post Humously" option.
    20. Re:Tool safety by pestilence669 · · Score: 1

      What ever happened to people learning to use their tools properly? I, for one, don't want training wheels on everything I use... languages included.

      It's offensive to me that people actually advocate infantile languages just so the inexperienced won't mess themselves. How about education as a nice compromise?

    21. Re:Tool safety by nacturation · · Score: 1

      What ever happened to people learning to use their tools properly? I, for one, don't want training wheels on everything I use... languages included.
       
      It's offensive to me that people actually advocate infantile languages just so the inexperienced won't mess themselves. How about education as a nice compromise? That's the way it should be. The tools should be high quality and written with security in mind. An insecure, infantile language with training wheels isn't a high quality language as it hinders a professional programmer and does no favors for the amateurs. If security is important, you wouldn't go out and buy the cheapest padlock you can find; you'd get one that is made by professionals who design for security. Why would languages be any different?
      --
      Want to improve your Karma? Instead of "Post Anonymously", try the "Post Humously" option.
    22. Re:Tool safety by pyite · · Score: 1

      I think you did not consider the context of what I was posting. The parent of my comment said "saying that it's the programmers' fault for bad code is like saying being injured is the fault of a lumberjack..." It's always the programmer's responsibility to know what he's dealing with as best he can. I don't doubt any of your comments above regarding PHP's security. But the fact that you know about these things is testimony that other PHP developers also would know about them. Trust me, I'm not defending PHP, I'm *sure* there are plenty of bad design decisions in it, and I've heard lots of gripes about it. Being in the engineering and applied math disciplines, 70% of the code I write is in MATLAB and the other 30% is Java for side projects, both of which have their own "gotchas" which I try to be aware of as best I can.

      --

      "Nature doesn't care how smart you are. You can still be wrong." - Richard Feynman

  3. Upload.php by eldavojohn · · Score: 0

    Disclaimer, I am not a PHP developer!

    You know, I was thinking about this the other day. When I tried an online PHP tutorial a while ago, it turned out that it was trying to get me to use an upload.php file to put files on your webserver to try out. Tsk tsk, lazy developers!

    Now, the tutorial showed me this but I'm sure nobody uses it in real life, right? Well, explain this then!

    Now you may be able to convince me that some are fairly safe. That they check file type and all that jazz. Problem is that I know not everyone is being safe.

    I know this doesn't nearly cover this issue at all ... but for some reason in my mind I associate this upload script with PHP. Is it taught to everyone? I'm not sure, having received no formal training. I guess this is just anecdotal evidence of some lazy developers in PHP. But can you really criticize a language for its users being stupid? Probably since I've seen arguments all over about which language is "safer" than others.

    --
    My work here is dung.
    1. 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?

    2. Re:Upload.php by The+MAZZTer · · Score: 1

      You are making the troubling assumption that ONLY developers are going to need to upload files to their sites.

      How else are authorized end users going to be able to upload files for your script to process? To risk overusing a cliche, this is Web 2.0 here! The majority of users don't care about what FTP is, nor do they want to learn something new just to post a file to a website!

      An upload script is perfectly fine as well as the security behind it stops people from posting or touching files they shouldn't.

    3. Re:Upload.php by fullphaser · · Score: 1
      As a PHP developer (to some degree, not much) I am a bit confuse by the following
      trying to get me to use an upload.php file to put files on your webserver
      upload.php is just the name of the file, it may imply something but the security level on that file is going to very from developer to developer. It may have thousands of lines of code checking the file to make sure it is such and such a size, or such and such a file type. Don't assume just because they all named it upload.php that they are similar in any way. Would you prefer I name my upload checking file 514645646a4s.php? It is easy to remember, and in PHP you are going to be calling a lot of crap from other files, so keeping it easy to remember is a bit more than logical.
      --
      Did someone say cake?
  4. 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 Jack9 · · Score: 1
      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 make non-exploitable webscripts, I'm giving you the benefit of the doubt). Yes, it's possible to make full blown PHP applications. You can also intentionally insult your company's president at a corporate-sponsored party. A programmer acting irresponsibly is not the fault of a language.
      --

      Often wrong but never in doubt.
      I am Jack9.
      Everyone knows me.
    5. 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.

    6. Re:The problem is .... by Cecil · · Score: 1

      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.

    7. Re:The problem is .... by ibbo · · Score: 1

      Here here.

      Any old tom can put a few lines together and claim to be a programmer (you find them using Visual Studio a lot). These types dont even learn about the underlying concepts of programming for they dont have to as its all been abstracted away from them. Whereas C programmers or in this case php programmers do becuse you are encouraged to use your grey matter to see the problems that could arise and fix them prior to them becoming broken.

      In the long run I think its best that you should be the sole responsible for your code. If you fail to check it for security or errors its your fault and not that of the language.

      --
      Linux user #349545 (GNU/Linux)iD8DBQBAzWjX+MZAIjBWXGURAmflAKCntuBbuKC WenpmXoA7LNydllVQOwCfdjyzXscd
    8. Re:The problem is .... by Sancho · · Score: 1

      I thought he was saying that one should choose a language based upon how much they want to language to coddle. If a language doesn't have the security features you want and you aren't willing to implement them youself, don't use the language.

      Unfortunately, this fails when people aren't thinking about security in the first place (most PHP users fall into this category). It's hard to make an informed choice when you don't realize that you need to.

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

    1. Re:This is easy to test empirically by Myen · · Score: 1

      You need to add 20 to do it in Malbolge and find that language to be perfectly safe because nobody could claim to have something that would possibly ever be deployed, right? :p

  6. I have to agree.. by QuantumG · · Score: 1

    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 be built into the library call.

    --
    How we know is more important than what we know.
    1. Re:I have to agree.. by MysticOne · · Score: 1

      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.

    2. Re:I have to agree.. by Anonymous Coward · · Score: 1, Insightful

      you're the kind of idiot that magic quotes was created for.

    3. 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.
    4. Re:I have to agree.. by MysticOne · · Score: 1

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

    5. Re:I have to agree.. by Anonymous Coward · · Score: 0

      There is such a thing as http://www.php.net/pdo you know? Maybe you should look into a current version of PHP :-)

    6. Re:I have to agree.. by binford2k · · Score: 1

      Why should accessing form fields do SQL escaping? What if you aren't using SQL? Shell escaping is different. Or what if you're using a database that escapes strings differently than MySQL? (yes, believe it or not, there are other database servers).

      If there is auto SQL escaping taking place, it should be right where it's needed, in the db layer.

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

    8. Re:I have to agree.. by FooAtWFU · · Score: 1
      There is such a thing as http://www.php.net/pdo you know? Maybe you should look into a current version of PHP :-)
      Hasn't been around long enough. It takes longer than a year (+ 1 month 17 days since PHP 5.1.0) to change your stripes. PHP 4 is still the standard that you need to write your code to if you want to be sure Average Joe can run it at his mom-and-pop web host without funky settings. PHP 4 is still the language of dozens of tutorials on the 'Net. PHP 4 is still running dozens of production sites that would break if you switched to PHP 5 all of a sudden.

      And it will take more than this to get PHP a reputation of security. Maybe once they've deprecated (or even removed) the old cruft like mysql_connect and put great big bold notices on the documentation pages of the old functions about "DON'T USE THIS" and things like addslashes() and such that say, "use PDO instead", and once this news works its way down the grapevine... then we can talk.

      --
      The World Wide Web is dying. Soon, we shall have only the Internet.
    9. Re:I have to agree.. by Anonymous Coward · · Score: 0

      > Perl ships with a fair amount of stuff. It ships with a package named DBI.

      Actually, Perl doesn't come with DBI. It's just the first thing most people hit CPAN to install.

    10. Re:I have to agree.. by VGPowerlord · · Score: 1

      You have to install DBI separately, but CPAN will automatically install DBI when you install any DBD module.

      --
      GLaDOS for President 2016! "Well here we are again. It's always such a pleasure." -- GLaDOS, 2011
    11. Re:I have to agree.. by lewp · · Score: 1

      I know that. I also know about ADODb and PEAR::DB. I also don't write exploitable DB code.

      The people who give PHP its bad rap don't know about those things, or why they should use them, and they outnumber me 10:1. Unfortunately, when they go to http://us2.php.net/mysql_query to look up what is quite possibly the only PHP function they actually know, there's nothing except some gibberish in a comment halfway down the page with a poorly-written DIY solution and no link to the resources the clued folks know about.

      Is it the programmers' fault for being an idiot? Sure. I'm no friend of the morons. Burn them at the stake. Is it the PHP developers' fault for not directing said morons to the right way of doing things? Yes, because they originally caused the problem by making the only installed-by-default mentioned-in-the-docs interface to the most popular database one step above the C library interface without drilling the possible security issues into their skulls (notice there's no mentioned about security on that page at all), while also billing the language itself as the grandma-easy web language.

      I write PHP for a living (and Perl, Python, Java, or Ruby when I can sneak it into a project without making waves). I've been around it for several years. I know what I'm doing. Most of the people who are writing PHP, and even most of the people who are writing free PHP software that is being released to a wider audience don't meet those criteria. The PHP developers themselves share a large responsibility for creating this situation, and they need to be conscious of it every step of the way.

      --
      Game... blouses.
    12. Re:I have to agree.. by Alioth · · Score: 1

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

    13. Re:I have to agree.. by fimbulvetr · · Score: 1

      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 configured, which is probably a newer version than the one you installed on your last server.

  7. 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 Anonymous Coward · · Score: 0

      I believe the primary purpose of a language suited for web development is to deliver content to a browser. Thats just me though.

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

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

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

    5. Re:what's the purpose of a language, anyway? by Shados · · Score: 1

      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 easy that you can set it so your post variables are directly converted to PHP variables. Woohoo, I can have a textbox called MyField, and bang, retrieve its data from $MyField (or something, its been a while). How fun, flexible, and convenient. ...

      Its also one of the worse security nightmares ever. The slightest mistakes in your code design, and BANG, all kinds of issues. Its just NOT WORTH IT. Yes, ActiveXs have interesting and powerful uses. But -its not worth it- when weighted against the problems. Same thing here with PHP. A lot of things in PHP are rediculous design choices, and allowing these things at ALL serves no purpose, aside from allowing new programmers from thinking they're "L33t" while shooting themselves in the foot repeatedly, without ever knowing it.

      PHP isn't the only environment with these issues: why the bloody hell does VB.NET even allow you to code without option strict. WHY?! So people can waste memory left and right, make casting errors all over, and have hundreds of lines of code with problems that cannot be checked by the compiler? All in the name of being more friendly? -NOT WORTH IT-.

      See where I'm coming from?

    6. 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
    7. Re:what's the purpose of a language, anyway? by VGPowerlord · · Score: 1

      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.

      --
      GLaDOS for President 2016! "Well here we are again. It's always such a pleasure." -- GLaDOS, 2011
    8. Re:what's the purpose of a language, anyway? by jrockway · · Score: 1

      > 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 database interface, even though it's freakin' designed to interface with databases! Code like: mysql_query("SELECT * FROM foo WHERE bar='". sqlClean($bar). "'") is just plain hard to read and is just plain prone to error. Give me something like query("SELECT * FROM foo WHERE bar=?", $bar) any day. The compiler should do the heavy lifting for me -- as a programmer I should worry about solving problems. Navigating through spaghetti like "'".clean($var)."'" is not something I ever want to do.

      Obviously, this is just the tip of the iceberg... I could write 1000s of pages about PHPs failings.

      --
      My other car is first.
    9. Re:what's the purpose of a language, anyway? by jrockway · · Score: 1

      I trust PHP security experts about as far as I can throw them. This guy is the author of a PHP security book and I found many many severe security problems 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 PHP.

      --
      My other car is first.
    10. Re:what's the purpose of a language, anyway? by Russ+Nelson · · Score: 1

      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 sharp edges would be exposed.

      --
      Don't piss off The Angry Economist
    11. Re:what's the purpose of a language, anyway? by gbjbaanb · · Score: 1

      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.
    12. Re:what's the purpose of a language, anyway? by piranha(jpl) · · Score: 1

      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 ways to inject arbitrary HTML (and therefore, arbitrary Javascript) into the output of some page in your application.

      DOM is the structured approach to creating an HTML document. You don't splice strings, you manipulate tree structure fragments. If you want to include the output of variable foo, you might say: elem.appendChild (foo). DOM models the data in a structured format, and just about makes it impossible to introduce XSS bugs, because textual content is always properly encoded when the document is serialized and sent to the browser.

      It's like the difference between building SQL queries by hand or using prepared statements. The idea is to use a special notation for these specialized tasks (building a query, building a document). Then you stop worrying about trivial syntactic security issues and start actually operating on a more abstract and efficient level.

      What floors me is that PHP's DOM implementation absolutely blows chunks. For a "web programming language," they've really dropped the ball. DOM can make you more efficient: it abstracts HTML document generation so that you don't have to worry about quoting things (something of a relief, actually). You don't have to worry about stupid malformed-document bugs (say an obscure function closes an element prematurely). And it's suddenly easier to write software that returns bits of HTML code and ties it in with other HTML code.

      PHP's DOM is unreliable, or at least greatly surprising. Half the functions aren't documented. And PHP's DOM doesn't even follow the W3 DOM standard: every real DOM uses the same names for functions and attributes. PHP does it "their" way, because they don't understand that the standardization of DOM is part of what makes it so fantastic.

      Part of the problem may be PHP's reference semantics. It wasn't until considerably after I tried PHP's DOM that I really learned how references work in PHP. (The official documentation is far from clear on the subject.) Whenever you do assignment or call a function, all values are deep-copied. So, if you have variable a referencing an object, write "b = a", and change the object by dereferencing "a", you won't actually change the object referenced by "b". You actually have to use a special syntax in assignment to copy the reference to some object and not to instantiate a brand-new one. This flies in the face of convention in contemporary imperative/object-oriented languages, and must make writing a DOM implementation impractical.

      For my own project, I gave up on mutating a PHP DOM tree, and was forced to clone the whole tree just to modify it. Unlike most PHP documentation, there's little to no examples. Because of PHP's special reference semantics, examples would have been essential.

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

    14. Re:what's the purpose of a language, anyway? by 00lmz · · Score: 1

      Adding to that is the fact that PHP has never had a sane database interface, even though it's freakin' designed to interface with databases! Code like: mysql_query("SELECT * FROM foo WHERE bar='". sqlClean($bar). "'") is just plain hard to read and is just plain prone to error. Give me something like query("SELECT * FROM foo WHERE bar=?", $bar) any day. The compiler should do the heavy lifting for me -- as a programmer I should worry about solving problems. Navigating through spaghetti like "'".clean($var)."'" is not something I ever want to do.

      Thanks for saying that. It is one of the things that I hate the most about PHP (manually quoting data for the database). This is from http://dev.mysql.com/tech-resources/articles/4.1/p repared-statements.html. stating how you have to use a different (and only included with PHP5) interface to use prepared statements and bind parameters.

      Another API that has prepared statement support is PHP. PHP 5 has a new MySQL interface called "mysqli". You can read more about the mysqli extension in the mysqli section of the PHP Manual. The API provided by the mysqli extension is also nearly a one-for-one match with the C API, so the documentation for the C API may also be useful in learning about the PHP API.

      Those of you that are Perl or Java users have had prepared statements for quite a long time. However, those were client-side prepared statements. The client-side prepared statements provide the same security benefit, but none of the performance increases. Don't worry though, MySQL Connector/J has support for server-side prepared statements in the new 3.1 release. Perl's DBD::mysql driver will have support in the next release of the 2.9 tree. The best part is that your code is already written to use them, so all you have to do to take advantage of the new feature is to upgrade the driver behind the scenes.

      It's not like they (PHP devs) had nothing to learn from, I believe ODBC had query parameters before PHP3 was released. Maybe it's because the PHP team insists on making the database libraries as close as possible to the C libraries they are based on, but bind parameters (even emulated, client-side ones) are easier to use and less error-prone than escaping the values one-by-one.

  8. A bit of both, I'd say. by Anonymous Coward · · Score: 1, Insightful

    We need work on both sides. Programmers need to know how their apps could be exploited (cross server scripting, remote includes, SQL injection, etc.) The platform, on the other hand, should make it harder for these vulnerabilities to occur.

    Possible options for SQL injection attacks, for example, include Perl's "tainting" mechanism. Where does this string come from? The outside world? Right, it's considered tainted. Any manipulation that puts the string (or even just a part of it) into another causes that string to be tainted as well. No tainted string can be sent as an SQL command to a database, although it can be sent as a parameter. If you absolutely have to include it in an SQL command, there could be a function that de-taints the string: so that quotes and similar are escaped, to remove the ambiguity, for example.

    For example, instead of constructing a string 'SELECT * from FOO where BAR="(string from the outside world)"', you'd construct a string 'SELECT * from FOO where BAR=:parameter1'. You'd then construct a set, saying parameter1 = '(string from the outside world)', much like Python's dictionaries. Then you'd call the database: execute this SQL command, and these are the parameters to go with it.

    Last time I looked, you could do the latter part (but not the former part) with Oracle databases under PHP, but nowhere else. Why not? This is a very basic way to avoid 99% of the SQL injection cases out there ...

    1. Re:A bit of both, I'd say. by gradedcheese · · Score: 1

      For MySQl, PHP 5 and its MySQLi extension provide prepared statements and the like to improve things in the way you're suggesting. Earlier versions really didn't, and on top of that there is the magic quotes 'feature' that really mixes things up (and, I hear, is due for removal soon).

      My main gripes have been the complete lack of namespace support, dumping everything into one global space and making it relatively easy to screw up. PHP also plays fast and loose with variables, which at times is convenient but often leads to ambiguities that can have unforeseen consequences. Things like using uninitialized variables are marked as a very low warning priority (not shown by default). Pre-PHP5, the OO features were very lacking, often making it pretty worthless to try to write code that way. Not necessarily security issues, but they definitely contribute.

    2. Re:A bit of both, I'd say. by Mr.+Slippery · · Score: 1
      Last time I looked, you could do the latter part (but not the former part) with Oracle databases under PHP, but nowhere else.

      Sounds like PEAR's DB module or MDB2 modules.

      --
      Tom Swiss | the infamous tms | my blog
      You cannot wash away blood with blood
    3. Re:A bit of both, I'd say. by jrockway · · Score: 1

      Nobody uses those, though, because they're buggy, broken, and braindead.

      --
      My other car is first.
  9. 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.

    1. Re:SQL escaping considered evil... by Jesselnz · · Score: 1

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

      The problem is that most hosts are still using MySQL 3, which doesn't support prepared statements. There's really no excuse for that, considering that MySQL 5 is very stable now.

    2. Re:SQL escaping considered evil... by blincoln · · Score: 1

      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 simultaneously unless you reduce the character set down to something like alphanumeric + period and comma.

      --
      "...always new atoms but always doing the same dance, remembering what the dance was yesterday." -Richard Feynman
  10. 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.
  11. 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!
  12. agreed! by numbsafari · · Score: 1

    I have to say, part of the quality of the "tutorials" and documentation provided by the language proponents should probably be taken into consideration.

    For example, a while back I was reading the Microsoft training materials on .NET Web Services. The example instructed the developer that they should generate their primary keys by selecting the MAX of an int column, adding one and then inserting the new record.

    I can understand not wanting to confuse someone with the complexities of concurrent programming when you're just trying to introduce them to the UI for the compiler. But seriously, there was a two paragraph description of how to do this. One could certainly fit in a description of using identity columns or some other reasonable approach rather than selling this other mess as a good idea.

    And so, when MS complains that their devs get no credit... well... one only has to point to the quality of the manual they were supposed to learn from.

    Sounds like PHP suffers from the same problem.

  13. Re:mysql_escape_string, mysql_real_escape_string, by larry+bagina · · Score: 1
    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.

    Every php project I've seen uses raw mysql_* functions or a reinvent the wheel (only this time, it's lopsided).

    --
    Do you even lift?

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

  14. You are all lazy programmers! by Karaman · · Score: 0, Troll

    You are too lazy to create secure code, so you blame PHP, LOL :)

    I have been using PHP for 5 years now and I always checked
    how my code worked, whether it was safe enough, etc. etc. ....
    I dont rely on others to do my job!

    Well, I dont say there are no stupidities or bugs or whatever in PHP,
    but when you write insecure code, you should not blame the language
    you are writing in!

    Blame yourselves that you have not read enough, that you have not
    tested enough, or that you are not lucky enough!
    Then sit on your butt and rewrite those unsafe lines of code!

    p.s. If you feel you don't have the ability to write good PHP code, blame yourselves again!

    --
    sex is better than war!
    1. 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.

    2. Re:You are all lazy programmers! by VGPowerlord · · Score: 1

      P.S. If you don't have a call to get_magic_quotes_gpc() in your program somewhere, you don't have the ability to write good PHP code.

      --
      GLaDOS for President 2016! "Well here we are again. It's always such a pleasure." -- GLaDOS, 2011
    3. Re:You are all lazy programmers! by Karaman · · Score: 1

      You have never been so right, mate!

      --
      sex is better than war!
    4. Re:You are all lazy programmers! by Anonymous Coward · · Score: 0

      I don't have get_magic_quotes_gpc() in my programs. All the PHP I write is internal to my company, the web server is always deployed with magic quotes off, and every single database access is always via PEAR's DB module with parametric binding.

    5. Re:You are all lazy programmers! by revlayle · · Score: 1

      Amen, magic_quotes is the worst damn thing i have ever seen in PHP. I expect exactly what the put/get sent in my $_POST/$_GET/$_REQUEST arrays. I always use parametric binding when I can (which can be done with Oracle easily, as a lot of my PHP contracts use PHP/Oracle) and htmlencode() for all of my varchar-like output. If I need to "escape" my input, I will call a routine manually, or write my own.

    6. Re:You are all lazy programmers! by Anonymous Coward · · Score: 0

      True story. For all of PHP's supposedly bad defaults, you can always automatically work around them. If they take out register_globals, you can easily just extract($_GET); extract($_POST); Are we going to get rid of extract because it allows people to write bad code?

  15. it really is the dev's fault by ILuvRamen · · Score: 0, Flamebait

    If you leave it wide open for SQL injections when you could just filter out semicolons is absolutely the developer's fault. The code is gone by the time the page gets to the user for God's sake, it's not a horribly insecure language if you know how to use it. Languages aren't there to babysit someone who knows nothing about proper security, they're there to do the maximum amount of things. Adding securit restrictions would just piss people off and get in the way of people who want to do things other ways

    --
    Google's Super Secret Search Algorithm: SELECT @search_results FROM internet WHERE @search_results = 'good'
    1. Re:it really is the dev's fault by Rycross · · Score: 1

      If you think just removing semicolons prevents sql injection, then I have bad bad news for you. Your code is insecure.

      See thats the point. The reason we use higher level languages in the first place is partly so that we have a safety net. Its not just a matter of developer competence. Nobody is perfect. Everyone makes mistakes. Ideally the language should be able to catch them sooner rather than later. Why would I want to use PHP if one mistake could hose my security?

      Noones saying the developer is blameless, but saying that because the developer is ultimately responsible, the language has no blame, is a cop-out.

    2. Re:it really is the dev's fault by ILuvRamen · · Score: 0, Troll

      oh sorry, I meant to type out my entire security policy for PHP but it was a bit longer than that. Shut up, it was an example

      --
      Google's Super Secret Search Algorithm: SELECT @search_results FROM internet WHERE @search_results = 'good'
    3. Re:it really is the dev's fault by Anonymous Coward · · Score: 0

      If you remove semicolons at all, you're a retard. Use PHP's equivalent of PreparedStatement, stupid.

    4. Re:it really is the dev's fault by tepples · · Score: 1

      Use PHP's equivalent of PreparedStatement

      Do most shared hosting companies use PHP versions that include PDO?

    5. Re:it really is the dev's fault by LizardKing · · Score: 1

      If your PHP security policy is full of stuff like "remove semi-colons", then it highlights your ineptitude - unless PHP doesn't offer a better way of escaping user input other than getting the user to do it on a case by case basis, in which case that highlights the ineptitude of the PHP developers. In a framework designed with security as a primary concern, features like prepared statements and database specific escaping built into the driver are essential. This is how Perl's DBI works, and also how Java's JDBC works. If PHP does offer similar features, then they need to be introduced at the earliest opportunity and used consistently in all PHP tutorials.

      My last employer had a corporate vanity website, that acted as a glossy brochure to adverstise their subscription only websites. The brochure site was developed in PHP by an expensive, third part agency, who included a number of forms for submitting things like sales requests. When myself and the very competent graphic designer in my team expressed concerns about using PHP (the subscription only websites that we developed were JSP and Java) we were told that the agency claimed to know what they were doing, so no audit was necessary. Several months later, the company mail server was brought to it's knees, as it turned out you could use the PHP web forms to relay spam.

    6. Re:it really is the dev's fault by Rycross · · Score: 1

      My point is that instead of recommending the proper method (using parameterized queries) or the runner up (using build-in escaping functions), you recommended a method of sanitizing your SQL that still leaves you wide open for injection attacks. The fact that you did not mention either of these two methods leads me to believe that you're going around removing semicolons thinking that you've properly guarded against injection, when in fact your code is utterly insecure. Thanks for proving my point.

      If you were properly escaping them, you would have said so. And thats my point: developers aren't perfect. Its the responsibility of the framework and language writers make it easy for developers to do stupidly insecure things if they don't know what they're doing.

      There's a time and place for languages that don't hand-hold developers, but web development is not one of these places. There's absolutely, positively no reason whatsoever why web developers should need to sacrifice security, and thus theres absolutely no reason the language should make it so easy to write insecure code. Like PHP.

    7. Re:it really is the dev's fault by ILuvRamen · · Score: 1

      actually you just simply test for semi-colons and other SQL injection, multi-command signs so it looks insecure. Then when you find one, analyse it further to test if what's after the semi colon is a insert, update, delete, or select or you know, whatever logic to make sure it's someone doing something bad. Then when you determine that, log their IP and ban them from the server and take legal action later. If you use any "more secure" setup without php, it's only a matter of time before the hacker find a security hole in that and all you're doing is delaying the inevitable. But if you use T.R.A.P.S (totally, ridiculously, absolutely protected system) then they're caught and it's over for them instead of them just saying "oh, that didn't work, let's try something else" and eventually getting in since there's an unlimited time window.

      --
      Google's Super Secret Search Algorithm: SELECT @search_results FROM internet WHERE @search_results = 'good'
    8. Re:it really is the dev's fault by ILuvRamen · · Score: 1

      here's a security policy you obviously never learned in school: Don't trust it if you didn't write it! go troll somewhere else

      --
      Google's Super Secret Search Algorithm: SELECT @search_results FROM internet WHERE @search_results = 'good'
    9. Re:it really is the dev's fault by Anonymous Coward · · Score: 0
      here's a security policy you obviously never learned in school: Don't trust it if you didn't write it! go troll somewhere else
      So we can assume you wrote your own operating system, web server, scripting language and DBMS?
    10. Re:it really is the dev's fault by LizardKing · · Score: 1

      You really don't get this do you? You don't parse the strings trying to determine what needs escaping, you use the escaping built into the database specific driver that your vendor, who knows what to escape, has provided. Examine the JDBC API, where you construct a PreparedStatement such as:

      PreparedStatement ps = new PreparedStatement("INSERT INTO foo (fooId, name, age) VALUES (DEFAULT, ?, ?)");

      Then you use the JDBC API to safely insert data at the positional ? parameters. Supposing name to be a CHAR(), and age to be an INTEGER, you would write:

      ps.setString(1, userSuppliedString);
      ps.setInt(2, parsedInt);

      The age has already been validated to be an integer by your JSP tags, while any dodgy characters in the name will be escaped by the JDBC drivers implementation of setString, and wrapped in quotes.

      Trying to do this yourself is prone to error - you don't know your database as well as the vendor does, and any changes in escaping requirements between versions of the database are hidden from you by the corresponding JDBC driver.

    11. Re:it really is the dev's fault by Rycross · · Score: 1

      That method is insecure. Sorry, but you've proven my point.

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

    1. Re:Yes by bill_mcgonigle · · Score: 1

      but that doesn't mean we can't damn programming languages

      Reminds me of Spock in Star Trek IV. :)

      --
      My God, it's Full of Source!
      OUTSIDE_IP=$(dig +short my.ip @outsideip.net)
    2. Re:Yes by inKubus · · Score: 1

      I just hate seeing


      $page=$_REQUEST['page'];

      include($page);


      Use addslashes, use the mysqli DB calls (_prepare(), etc.), use STORED PROCEDURES which are finally available on MySQL. Take the DB stuff out of PHP and you're left with a pretty stable secure scripting language. Granted, there are some issues with typing, bounds checking, etc. but PHP is not an "enterprise" scripting language. It's not designed to write bank software. It works great for everything else.

      --
      Cool! Amazing Toys.
  17. Interesting... by sheldon · · Score: 1

    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.

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

      --
    4. Re:Who's fault? Zend's by jrockway · · Score: 1

      > 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 IS NO TYPING IN THE LANGUAGE. etc.)

      Anyway, most people that actually know how to program find Perl much more readable. If you're having trouble, maybe you should adjust the focus of your monitor.

      --
      My other car is first.
    5. Re:Who's fault? Zend's by cyberkreiger · · Score: 1

      You can't really say PHP is better than Perl.

      See http://tnx.nl/php for a great comparison.

      --
      Stumbling in the dark
      I hear slavering of jaws
      Eaten by a grue.
    6. Re:Who's fault? Zend's by LizardKing · · Score: 1

      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 reporting is a feature, not a bug.

      So it is, but defaulting to all warnings and errors would be saner.

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

      Well, there's a lot of naive and dim developers out there. fopen_urls() should be binned.

      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.

      Why is PHP, a high level web development framework, trying to "stay consistent" with C, C++ or Perl? As for consistency within standard languages and libraries C, C++ and Java are very consistent (bcopy is a bogus example as it's not part of any standard).

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

      That's strange, as the JSTL for Java Server Pages makes do with one escape routine. Of course, JSP and Java frameworks such as Spring encourage good practices that PHP makes difficult (pre version 5 at least).

      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 write a web app in C, so the point is moot. As for Perl and PHP obfuscation, most of the PHP code I've seen fails to separate business logic from presentation, has masses of duplication and often amounts to line noise. Generally, the rewrites into something better (Java and JSP) that I've undertaken, start from the spec rather than the code because of the obfuscation of the PHP.

    7. Re:Who's fault? Zend's by GWBasic · · Score: 1
      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.

      The above reason is why I gave up on PHP. I see it as insecure and difficult to maintain.

      As a result, I decided to make my own web development platform. It's easier then you think!

    8. Re:Who's fault? Zend's by Tablizer · · Score: 1

      I'd like PHP to be recognized as the excellent language it is but these security problems aren't helping.

      It's open source, so get a group together make a new branch: SPHP: "Secure PHP".

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

  20. Point of fact... by Secret+Rabbit · · Score: 0

    ... no language is idiot proof nor can a language be idiot proof.

    Secure programming can be mostly done by defining an extremely narrow band of valid input and strictly requiring said input... for everything. Which mostly doesn't happen from what I've seen.

    Why does SQL injection work? Because of improper validation. Another cause of insecure code is because of a high level of complexity (usually needless complexity). Why does this happen? Because mentally challenged project managers (and up) make ridiculous schedules for the developers and as such, the developers are forced to rush. This leads to bad design, cutting corners, etc. There's clearly going to be security implications in there.

    You might notice that the above doesn't make reference to any particular language. That's because such things are *independent of the language!!!*

    From what I've seen, PHP pumps out "less secure" code not because of the language itself (i.e. the interpreter, etc), but because it is easy to learn. So, you have a bunch of graphic designers, etc that want to program the site themselves, so they learn PHP. Now how secure do you think that there code will be?

    Languages don't currently hold it for you while you piss, nor should they.

    Basically, "make it idiot-proof, and someone will make a better idiot."

    This is real life, not nursery school. Take responsibility for your actions/knowledge or lack thereof, stop blaming the language, shut up and do you job properly!

    1. Re:Point of fact... by Goaway · · Score: 1

      Why does SQL injection work? Because of improper validation.

      No, SQL injection works because PHP forces you to do validation. Hardly any other language than C forces you to do that. Perl, Python and the others have sane database interfaces that BY DEFAULT let you get away with no validation or escaping. Leaving it up to every single developer to properly handle this on their own is madness.

    2. Re:Point of fact... by Secret+Rabbit · · Score: 1

      What you're complaining about amounts to bitching at the gun manufacturer because guns don't have a "don't shoot own foot" "feature." Basically, IF YOU KNOW that PHP does NOT do validation, THEN DO IT YOURSELF! If you don't want to do that, then DON'T USE PHP!

      This also reminds me of something along parallel lines that one of my former Physics Prof. (may he rest in peace) said, "Ignore the symmetry at your own peril." Or in this case, "Ignore the way the language works at your own peril." Either way, you're just as stupid.

      Basically, and I quote my original post here:

      """
      This is real life, not nursery school. Take responsibility for your actions/knowledge or lack thereof, stop blaming the language, shut up and do you job properly!
      """

    3. Re:Point of fact... by Goaway · · Score: 1

      I don't use PHP, for exactly that reason.

      The thing is, the vast majority of PHP users don't even understand that there is a problem. PHP is a language used mainly by beginners, and actively aimed at beginners, but it is not designed to be used by beginners. It's a landmine-filled sandbox.

      Thus, the internet is full of SQL injection vulnerabilities.

      Blaming every PHP programmer for not being a security expert is idiotic. Most programmers aren't, and they wouldn't need to be, if the language was designed properly.

    4. Re:Point of fact... by Secret+Rabbit · · Score: 1

      From Goaway \\\
      The thing is, the vast majority of PHP users don't even understand that there is a problem. PHP is a language used mainly by beginners, and actively aimed at beginners, but it is not designed to be used by beginners. It's a landmine-filled sandbox.
      \\\

      So, where do you get that PHP is a "landmine-filled sandbox"? Because people don't use it properly (see function list below)? If so, that rather asinine.

      From Goaway \\\
      Thus, the internet is full of SQL injection vulnerabilities.
      \\\

      SQL injection errors are created by people that have no clue how to do there jobs. It is NOT language dependent (see list of functions below).

      From Goaway \\\
      Blaming every PHP programmer for not being a security expert is idiotic. Most programmers aren't, and they wouldn't need to be, if the language was designed properly.
      \\\

      If you define a security expert as one who pretty much uniquely knows to escape params to a SQL query, then I'd hate to think what your code looks like. In fact, my first piece of paper was from a college where I got a 2 year diploma. And even there they EXPLICITLY taught to do sanity checking at the client AND server level. And the instructor HATED teaching that stuff AND his actual expertise was networking. This is NOT about being a security expert, it is about /common sense/.

      This also is an issue that has NOTHING to do with language design. If we were talking about having a standard db interface then THAT would be language design (btw PHP doesn't have one and that is a problem, but that's a completely other issue). What we ARE talking about, is how that design is IMPLEMENTED. These things are completely different.

      From Goaway \\\
      I don't use PHP, for exactly that reason.
      \\\

      Well, it's obvious that you don't use PHP because you have no clue what functions are in its library.

      From http://ca3.php.net/manual/en/function.dbx-escape-s tring.php

      """
      Escape a string so it can safely be used in an sql-statement
      """

      and from http://ca3.php.net/manual/en/function.pg-escape-st ring.php

      """
      Escape a string for insertion into a text field
      """

      and from http://ca3.php.net/manual/sv/function.mysql-real-e scape-string.php

      """
      Escapes special characters in a string for use in a SQL statement
      """

      etc

      So, there are loads of functions that do the required escaping without the "programmer" having to be a "security expert" i.e. it's just having a clue as to what functions are available /and using them/.

      Also, point of fact, web programming today REQUIRES knowledge of security features/programes/etc. If you don't know, then you have no business doing it.

      Point of fact, security is about creating layers of defenses to ensue that the app is pretty much tamper proof.

      This starts with sanity checking at the browser, then a web application firewall (e.g. http://www.modsecurity.org/), specific sanity checks in the application code itself (e.g. restricting usernames to alphanumeric and checking for it), and if one is using a language that has functions like the above, use them (if they implemented internally, great), if not, do it yourself.

      Of course sanity checking at the client level and using a web application firewall are optional but the others are required, period. If you don't do this you're asking for trouble. Furthermore, if you depend on others to do this checking for you, you are as well asking for trouble.

      There will always be vulnerabilities in any language, web server, db server, etc. What makes any vulnerabilities not exploitable (or extremely difficult to exp

  21. Both are to blame. by SkWaSH · · Score: 0

    I have been working as a full-time PHP developer for nearly 3 years now, and was a casual developer in the pre-PHP4 days. I will be the first to admit that I haven't always taken all of the necessary security precautions, but now I feel that I do pretty well in that area.

    Just today I came across a huge flaw in the design of PHP as a language. I wrote some PHP4 code this past summer to encrypt credit card numbers and other sensitive data for secure storage. Since then we migrated the system to PHP5 and I was able to make use of the MUCH better implemented public/private/protected attributes of data members in classes to protect the key I was using for the encryption/decryption. I have been using ioncube to encode the PHP source to hide my key from prying eyes, but I discovered that the key is made visible by doing a simple print_r or var_dump on $GLOBALS.

    I realize that the private/protected attributes aren't intended to keep data like this secure, but the point of this long post is to say that there isn't any way provided of securely keeping sensitive data secure.

    So my opinion to the question asked is this: uneducated PHP developers cause most of the security problems in PHP applications, but the language itself could definitely use some extra security consideration.

    1. Re:Both are to blame. by Anonymous Coward · · Score: 0

      Your program obviously has to be able to read the key, otherwise there's no way to use it. Similarly, obfuscating your program doesn't help at all, because it has to get turned back into a form PHP can understand so it can be run, at which point the key you're concerned about will be in memory somewhere and can be pulled out.

    2. Re:Both are to blame. by socalian45678 · · Score: 1

      The private/protected thing is not a flaw in PHP! It is possibly a flaw in the english language that the word has different meanings in different contexts. Private and protected are about data hiding in sense of encapsulation, which helps maintain proper separation of concerns between datatypes. It has nothing to do with security. In C++, you can get around access modifiers using pointers or references. In Java and C# I believe that the knowledgeable coder can get around them by reflection. Most dynamic OO languages don't even bother with them. If you are executing untrusted code (such as eval'ing a user-supplied string containing, for example, print_r), all bets are off for security. Ioncube isn't even intended as a hacker-safe tool. It's meant to keep your customers coming back to you for changes, or to make sure that no one does cowboy coding on deployed servers.

    3. Re:Both are to blame. by NotZed · · Score: 1

      You took 3 YEARS to find a flaw in PHP? ... err, ok.

      --
      _ // `Thinking is an exercise to which all too few brains
      \\/ are accustomed' - First Lensman
  22. 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.

    1. Re:PHP is no worse than C. by geminidomino · · Score: 1

      That's .sig material right there.

  23. Developer's Fault by KermodeBear · · Score: 1

    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 would not be using it.

    --
    Love sees no species.
    1. Re:Developer's Fault by jrockway · · Score: 1

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

      --
      My other car is first.
    2. Re:Developer's Fault by Anonymous Coward · · Score: 0

      I can't comment on Googles use of PHP, but I used to work at Yahoo!

      Frankly, given the mess that it replaces, PHP in any shape or form is an improvement over what went before. The old system was a mountain of hackish C and C++ that interfaced directly with Apache via it's module API. There were some absolute gems in that code - fixed size buffers with no bounds check on what went into them, trusting user strings and using them as format arguments to printf() and friends, etc. The web servers would go down all the time, and the only reason users didn't notice much was because the farm consisted of a huge number of "disposable" machines working on a round robin basis. If Apache on one went down, it was taken out of the round robin loop until Apache was restarted. Backend data processing would crash regularly due to bad coding, and persistent data storage wasn't implemented for many things because it was considered too slow. Instead, data was kept in shared memory and lost after a crash.

  24. So old... by ErGalvao · · Score: 1

    This whole thing about PHP being a non-secure language is so old that is getting really boring. There's no such thing as a bad programming language, there are bad developers.

    You can write bad code in any language, it's your fault, your decision and yes, you should be held responsible for it.

    PHP is an extremely easy language to begin with, so many developers begin their careers using it, therefore making bad applications. There are good Java coders and bad Java coders. There are good Ruby coders and bad Ruby coders. Why it's so surprising that there are bad PHP coders too?!

    Where are the articles about GOOD PHP apps/programmers?! What I say is: There's a vice of calling PHP a less secure language. It's prejudice and misinformed. It's not good for the language, not good for the programmers and even worst for those who make this kind of statement.

    Oh, and for those PHP features that are the source of many of the problems bad developers cause, PHP 6 will ship without the possibility of using register_globals, which is a very good thing.

    --
    Er Galvão Abbott - IT Consultant and Developer
    1. Re:So old... by LizardKing · · Score: 0, Troll

      Quit with this "no such thing as a bad programming language, there are bad developers" bullshit. If a language encourages bad practices with an inconsistent, badly designed library and dubious features, then it is the fault of the language. Add in the poor tutorials (including most of those in printed books and on Zend's own website), and you've got a bad language made worse by ignorance. You ask where the articles are about good PHP apps and programmers. They don't exist, as most large scale web apps are written in Java - see this UKUUG paper for some reasons why. PHP lowers the barrier for getting a simple web app up and running, but it simply should not be used for anything large scale. The language is poorly designed, and poorly implemented (check out the number of vulnerabilities on bug tracking sites that are attributable to PHP itself rather than just the apps written with it).

  25. both are at fault .. but let's fix PHP! by Anonymous Coward · · Score: 0

    Okay. First of all I have been programming in PHP since PHP 3.x. I am currently working on medium to large public sites written in PHP. The first time I programmed in a high-level language was 15 years ago. In the IT world, this either means I'm an expert, or I'm a clueless idiot, depending on whether the person I'm talking to is an expert or an idiot. :-)

    Anyway, I have no problem at all placing a lot of blame on PHP. Here are the major issues I have to deal with EVERY DAY:

    1) NO HTML ESCAPING BY DEFAULT IN TEMPLATES! This is just asinine and inexcusable. When I insert text into a PHP template, I expect *exactly that text* to be displayed in the browser. If I have angle brackets, show the angle brackets in the browser, and so on. On those *few* occasions when I need to insert HTML into a template, I'm willing to use a different, longer, more-difficult-to-type character to string to turn off the escaping. But no, PHP decides that it will do the unsafe, uncommon thing by default, and if I want to escape, I have to use htmlentities() or some LONG function name like that. You could almost eliminate an entire class of errors just by changing this.

    Think about it: you make a mistake with the current PHP behavior, you forget to escape.. what do you see? NOTHING DIFFERENT. (or maybe, you will see your app mentioned on Bugtraq someday ;-). If PHP escaped by default, and you made a mistake, and forgot to NOT escape, what would you see? ANGLE BRACKETS ALL OVER THE PLACE.

    2) THERE ISN'T EVEN ONE LANGUAGE CALLED PHP: why? That ridiculous php.ini garbage. All my apps have to ship with a script to test about, hmm, 10-20 settings to make sure they are the same as I assumed when coding the app. Yes, people can change php.ini, but they shouldn't have to! Remove php.ini please, make it so this stuff has to be set at RUN TIME if people need to change it.

    Languages should only be configurable from WITHIN THE LANGUAGE, in my opinion.

    3) Need more convenience functions to clean form input: one thing I always to do with newbies is give them my library of functions that strip whitespace, normalize space, strip non-digits, strip invalid chars from emails, and other obvious stuff. I think PHP should have some of these BUILT-IN (so that it's taught to newbies and everybody knows its there and can be used in code examples without extra clutter, etc).

    Yes, you can do this with regexps and stuff, but that's not the point, it needs to have some of it out of the box, and it needs to be shown in all PHP code examples.

    For example, I'd like to be able to tell people to do things like this:

    $email = strip_whitespace($_POST['email']);

    (and of course it would be nice if the PHP folks cracked open a book on programming languages once in a while [exception handling without "always"/"ensure" blocks? huh????], but that's a whole 'nother ball of cheese.)

  26. PHP??? by drpimp · · Score: 1

    "Perfect Haven for Phishing"
    So wrong and so right at the same time!

    --
    -- Brought to you by Carl's JR
  27. 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

  28. 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.
    1. Re:Speaking as a PHP Framework Developer by poot_rootbeer · · Score: 1

      I think the industry has established by now what are good programming habits and methodologies and what aren't.

      And five years from now, the industry's opinions about what good programming habits and methodologies are will have changed substantially.

      Let's not assume that since Java is an extremely popular language right now, that all languages forevermore should try to be like Java.

    2. Re:Speaking as a PHP Framework Developer by Foofoobar · · Score: 1

      Who said I was talking about Java? The principles and practices and methodologies that PHP could be using are ones adopted by Python, Java, C++, Ruby, Perl and many others.

      --
      This is my sig. There are many like it but this one is mine.
  29. Partially PHP's "fault" by Jeian · · Score: 1

    ... though the fault, IMO, is simply being a language that's easy to use.

    I can write secure PHP because I started web-scripting in Perl, and had to do a lot of stuff by hand (and learn how to do it by looking at other people's code), and in that way learned security principles that superseded whatever I was actually writing.

    No offense to PHP coders, but it's too easy for any idiot to learn the basics, call themself a "web developer", and never learn a thing about good coding practices.

    1. Re:Partially PHP's "fault" by tiocsti · · Score: 1

      *cough* pot. kettle. black. ever hear of cpan?

    2. Re:Partially PHP's "fault" by Jeian · · Score: 1

      Not at the time. :p

  30. Like ruining screwheads with the wrong bit? by SlappyBastard · · Score: 1

    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?

    --
    I scream. You scream. I assume that means we're both acquainted with the problem. We proceed.
    1. Re:Like ruining screwheads with the wrong bit? by nuzak · · Score: 1

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

      --
      Done with slashdot, done with nerds, getting a life.
    2. Re:Like ruining screwheads with the wrong bit? by pclminion · · Score: 1

      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?

      What if B&D claimed that the bit was one-size-fits-all and would work on any screw? Now who's fault is it?

    3. Re:Like ruining screwheads with the wrong bit? by SlappyBastard · · Score: 1

      OK... any decent critical thinking process eventually requires that an individual claiming a degree of skill ought to have enough background to sort out the bullshit claims that every single thing ever marketed to us makes. That goes double for FOSS, because most FOSS stuff is being sold on personal involvement, not money, and therefore has a less brutal and more hopeful thinking process behind it. This discussion will be an ongoing discussion until the last programmer dies. This is just a redux of what is supposed to be wrong with (INSERT PROGRAMMING LANGUAGE). Therefore, it is the programmer's responsibility to sort out whether the programming language in question is suitable.

      --
      I scream. You scream. I assume that means we're both acquainted with the problem. We proceed.
  31. You have to know a tool's limitations by SlappyBastard · · Score: 1

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

    --
    I scream. You scream. I assume that means we're both acquainted with the problem. We proceed.
  32. 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
  33. 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
  34. 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
  35. web developers using php by chrisranjana.com · · Score: 0

    I would say the first class or lesson an aspiring programmer should attend will be BEST PROGRAMMING practises. He/she must delve deep into how to avoid security pitfalls while programming. I do believe that whether it is PHP or ASP or C# or Ruby on Rails.. If the developer updates both his knowledge and his software regularly and subscribe to websites like securityfocus etc Most of the applications which he creates will be secure.

    --
    Chris ,
    Php Programmers.
  36. 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?

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

  38. Shared hosting? by tepples · · Score: 1

    PHP 5.2 ships with PDO (PHP Data Objects) extension

    Which PHP 5.2 shared web hosting companies do you recommend?

    You should be clear about which version of PHP your referring to as PHP 4.4 is no longer considered the main release

    Tell that to the majority of shared hosting companies.

    1. Re:Shared hosting? by Anonymous Coward · · Score: 0

      Maybe shared hosting companies should get off their ass once in a while?

    2. Re:Shared hosting? by tepples · · Score: 1

      Maybe shared hosting companies should get off their ass once in a while? But which shared hosting company that has got off its ass does anyone recommend?
  39. PHP- making wrong things easy & right things h by TheLink · · Score: 1

    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

    --
  40. Crowd Psychology by KidSock · · Score: 1

    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 to good ol' Java bashing?). Programmers are bored. Take your pick. Yeah, occasionally there's a real problem but like that doesn't happen to Perl?

    Anyway, the PHP devs sound like they want to make things better somehow. They have accepted that even if the security issues are user perception or crowd psychology (thanks to slashdot) that is a problem in itself and therefore something must be done regardless.

    Oh, and that security guy Esser that left a few weeks ago is a nut-job. I've seen him posting on the PHP internals list. I'm not saying that he doesn't know what he's talking about but I find it very hard to trust anyone who is so undiplomatic. Also, apparently he's stared a "hardened php" site which to some could be construed as motive to make noise. I don't know, I'm not very well connected but that's just my instinct.

    1. Re:Crowd Psychology by arevos · · Score: 1

      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 libraries themselves. A better way of doing it would be to do the same thing as every other web language in common use and pass user input in as arguments, e.g.:

      sql.execute("SELECT * FROM users WHERE name LIKE ?", username)

      This way, the database object would automatically quote the input in a secure and database-dependant fashion. Of course, one could easily use a library or write a function that does the same thing, but why doesn't PHP have something like that by default?

      Language bashing is fun

      And sometimes legitimate.

  41. Re:I have to agree.. well... not really. by sydney094 · · Score: 1

    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 differentiate when my " ' " should really be escaped), but rather to "encourage" the developer to use typed (named) parameters in the SQL.

    It isn't the language, it's the dev. More accurately though, since PHP is largely pitched to beginners, it's really the documentation and book authors.

    --
    "If we knew what we were doing, it wouldn't be called research." - Einstein
  42. Re:mysql_escape_string, mysql_real_escape_string, by Zaiff+Urgulbunger · · Score: 1

    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.

  43. input could be handled in a manner similar to para by Tei · · Score: 1

    You can do that now in a unpractical way. You can add a textNode, and set the content to the user output. A textNode will force everything to text, even &entities.
    The problem here is ..where this text come from? you can do a ajax conexion, but is unpractical.

    Anyway escaping in PHP/MYSQL is done with mysql_real_escape_string, and I dont think is bad.

    --

    -Woof woof woof!

  44. Re:mysql_escape_string, mysql_real_escape_string, by Zaiff+Urgulbunger · · Score: 1

    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 up and awful lot of very badly coded/out of date examples.

  45. Both by RAMMS+EIN · · Score: 1

    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 explained in some detail in my essay Better Languages for Better Software, many common vulnerability classes can be eliminated by providing the right language features and APIs. The typical vulnerabilities in PHP scripts (injection vulnerabilities) fall in that category. So PHP is definitely at fault, too.

    --
    Please correct me if I got my facts wrong.
  46. PEAR's MDB2 by remmelt · · Score: 1
    MDB2 has prepared statements. Problem solved.

    I haven't looked into PDO yet, but MDB2 will work for your PHP4 code as well. I must add that MDB2 is not the golden egg either, its support for sequences is kind of lame when the db you're coding for natively supports them.

    #> pear install mdb2
    1. Re:PEAR's MDB2 by Zonk+(troll) · · Score: 1

      If you're using a Real database (Postgres, Firebird, Oracle, DB2, etc) why not just use a stored procedure? I've never used sequences, but I offload nearly everything I can into the DBMS itself. In my code there's just a bunch of CALLs (for SELECTs that depend on input, INSERTS, DELETE, UPDATE, etc) and SELECTs (all using a VIEW).

      --
      "The Federal Reserve is a fraudulent system."--Lew Rockwell
      End The FED. -
    2. Re:PEAR's MDB2 by Matts · · Score: 1

      Because stored procedures do nothing to prevent SQL injection attacks.

      --

      Matt. Want XML + Apache + Stylesheets? Get AxKit.
  47. Speak for yourself by mangu · · Score: 1
    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 development I want an easy way to use the SQL code I have available. Too much "security" can become counterproductive. Converting legacy SQL code to parameters in function calls may introduce bugs that could be even more dangerous than SQL injection problems. It's the job of a competent programmer to choose wisely the tools and resources that he will use in each case, instead of branding highly productive languages, such as C or PHP, as "insecure" overall.

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

  49. Re:mysql_escape_string, mysql_real_escape_string, by xa0s · · Score: 1

    I'm by no means a PHP expert (I prefer Perl, but hey to each their own), but I've been helping my g/f learn PHP and have been trying to instill good coding practices, such as parameter binding in SQL. I found this to be a pain in the ass in PHP, so maybe I'm missing something.

    Currently, I am only using MDB2, but to bind both integer and string parameters to an SQL query (ie. a user table with user_id and first_name), you have to actually pass an array describing the types of each argument, and then pass an array to the execute(). Making that first array of 'integer' and/or 'string' is the part I'm referring to being a pain in the ass, since I'm used to that being done automatically for me in Perl (or Java for that matter). Can PHP do that for me in any way? Maybe using another library?

    In Perl, it's actually easier and clearer (IMHO) to use parameter binding in your queries, but in PHP with that extra array, this becomes extremely cumbersome for large tables. It's not that surprising to me a lot of developers end up embedding the parameters right in the string rather than doing it The Right Way because of this... which of course leaves them wide open for injection attacks....

    though like I said, maybe I'm missing something here...

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

  51. PHP == fucked by NotZed · · Score: 1, Flamebait

    The language is largely at fault. Sure the PHP developer space is filled with 'ASP-level' programmers - but at the end of the day, there's only so much you can blame on the monkey's cutting code. PHP is an awful language, doesn't scale, doesn't promote anything remotely 'good', but still does the job. It isn't alone.

    It isn't an entirely bad thing either. At the end of the day people need software that does something. Security is for the most part not a priority - and why should it be really? Only because of arseholes is it even be an issue.

    But anyway, to cut it short - avoid PHP. The security issues are not even the start of how fucked a language it is. I'd much much rather code in C (C, not C++) than PHP any day (and yes, I've written production software in both). It doesn't have any more security issues - yet the ones it has are more obvious - it is orders of magnitude more scalable and performant, and it doesn't have any of the limitations.

    --
    _ // `Thinking is an exercise to which all too few brains
    \\/ are accustomed' - First Lensman
    1. 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.

  52. Easy: Hackers are to blame. by Qbertino · · Score: 1

    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, no matter what technology I use. PHP is a great piece of work and the best SSI solution available. It has it's pipeline covered with a set of OSS tools other solutions can only dream of and it has the largest amount of super-mature OSS webprojects available. All of which are, measured by their installbase, safer than anything else out there. Which proves that security in PHP is nothing special. You just have to compensate for PHPs upside (extreme easy of use) by doulbe checking it's downsides (enough leash to hang youself with). You have to apply basic brain functions when building critical PHP apps. Just like with any other technology. It's just that PHP ease of use lures novices into building larger apps that ignore security at first. Don't anyone tell me that his first C, Java, Whatever app was built with security and buffer overflow prevention in mind.

    Blaming something on the language is just plain silly. If you don't like it, don't use it, period. It's not that there's a lack of them.

    --
    We suffer more in our imagination than in reality. - Seneca
  53. fork? by Anonymous Coward · · Score: 0

    someone smarter than me fork php already and drop the nasty backwards thinking bits (zend?).

  54. Re:mysql_escape_string, mysql_real_escape_string, by Paulrothrock · · Score: 1
    I'm a PHP developer, too and I'm with you on the namespaces complaint. Not only does it make upgrading harder, but it also doesn't provide logical grouping for the functions. Every MySQL function should be in a MySQL library. mysql_connect() should be MySQL::connect(). But still, I'm sure the fault lies more with the developers than with the language. I've seen some horrible, horrible code in my day. Stuff like this is not uncommon in my current job:

    <?php
    $user = mysql_query("SELECT * FROM users WHERE username = '$_POST[username]' AND $_POST[password]");
    ?>
    Not to mention that I spent yesterday implementing encryption for credit card numbers we were storing in the database. They had been stored in plain text for at least two years. Is it any wonder I've started interviewing somewhere else?
    --
    I'm in the hole of the broadband donut.
  55. Correctness is not being taught to neophytes by HighOrbit · · Score: 1
    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 to Programmer). I think the book and the tutorials were good a teaching the basic language features and syntax, but they taught me how to use PHP dangerously because they did not teach good practices. My application worked but never got out of the prototype/demo stage back then. Recently, I went back to it on my own time to try to clean it up, move it to PHP5, and make it deployable. I now cringe with horror at the extremely bad practices I was using back then. Granted, it was just a prototype, but I thought I was doing it "right" because I was following the examples in the book and the tutorials. I was doing stuff like accepting form data and passing it to the DB with out validation, outputing user submitted variables without checking for XSS, registering globals, etc, etc, etc.

    So here is my point, all the tutorials, examples, and books that the neophytes are using to learn are _WRONG_. They are teaching _BAD_PRACTICES_. Because php is necessarily in a network environment (excluding the rarely used cli) and exposed to potential maliciousness, secure practices should be taught markedly at the beginning, not as an aside. So as part of teaching how to pass form parameters they should include validation code, even if they have to comment that section as " /* trust us on this part for now, we'll show you how this part works latter, just remember you always have to validate the input before you use it */".

    I think PHP is a great language for its purpose, which is simple web-apps. Lots of the criticism about its brain-dead defaults is correct, but they can be overcome with good pratices by the application developer. PHP can be great, but it is typically taught wrong at the beginning and that just snowballs.

    The editors and authors all the PHP books and tutorials out there need to make sure the new editions encasulate good practice at the beginning of the learning process.
  56. Trick question! by pestie · · Score: 1

    That's a trick question. The correct answer is "bound parameters using PDO."

  57. You missed the point. by Generic+Player · · Score: 1

    I do have the ability to write secure PHP code. And it takes much longer and much more effort than when I write secure perl, or python, or pike code. Because the language is poorly designed and has tons of misfeatures that promote security holes. Just because you *can* write secure PHP with enough time and effort, doesn't mean PHP is secure. The language should not go out of its way to make writing secure code more difficult.

  58. You forgot a big one. by Generic+Player · · Score: 1

    Zend posts PHP tutorials and examples on their site that show how to write code with huge gaping security holes, and say "its ok because people shouldn't just copy our examples" when you point it out. When the developers of the language are giving newbies examples that are full of security holes, and don't even think that's bad, you know there's no hope.

  59. Huh? Tons of people bash C. by Generic+Player · · Score: 1

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

    First of all, its still VERY fasionable to bash C for being dangerous. There's a big difference though, C is not designed especially for web development. It was designed (decades ago!) as portable assembly. Assembly is dangerous, so portable assembly is too. PHP is a high level language designed for a task that requires alot of attention to security. It fails miserably to be suitable for this task. C succeeds very well at being portable assembly.

    Second, as much as I dislike alot of perl's shortcuts, they don't tend to lead to security problems. Its definately easier to write secure perl than to write secure PHP. And perl and C both behave how you want when you are writing code in them. PHP behaves differently depending on how someone has messed with the php.ini. Have fun testing with all the variations of possible php.ini settings.

  60. Re:PHP- making wrong things easy & right thing by Foofoobar · · Score: 1

    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.

    --
    This is my sig. There are many like it but this one is mine.
  61. 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.

  62. whole PHP mindset by Anonymous Coward · · Score: 0

    It isn't just the programming language. It is what I refer to as the PHP mindset.

    Not to pick on anyone in particular, but take a look at some popular open source projects (springing to mind are Joomla, mediawiki, mantis which each have some of the below problems).

    They generally use only MySQL and only in ISAM format. There lies a whole set of issues around data integrity that shows that the developers are not thinking about quality and scalability.

    They generally require installs in which the whole directory tree is owned by the web server user. The web server user owning any files at all creates a whole set of security problems.

    They generally want you to supply and use the database root user instead of a user pre-created for the particular database application.

    They generally put configuration items such as db passwords right there in the filesystem which is readable by the web server. Maybe using htaccess to help protect, but still right there.

  63. They could do alot more than they do. by Generic+Player · · Score: 1

    Why has register_globals been left in? It should never have made it to php4, nevermind php5. What are the chances it actually gets removed for php6 like they said it would in php5?

    Why does zend host tutorials that show how to do things in an insecure way, thus teaching people to write security nightmares?

    Why don't the database modules use prepared statements or sprintf() syntax?

    It shouldn't require attending conferences and buying magazines to write secure code. I write secure C code without having to do those things! I certainly never had to do anything like that for perl, or python, or pike, or ocaml, or...

  64. Ask a craftsman about tools some day... by Dion · · Score: 1

    Ah, yes, but a good craftsman doesn't blame the tool for a poor result, but that's probably because the good craftsman chooses good tools and refuses to work with poor tools.

    Not knowing how to use a tool and choosing a poor tool are both faults of the craftsman.

    I think that explains why so much php code is utter crap, the skilled developers stay far away from it, although some times some unlucky soul is forced to use php by his PHB and that some times leads to a working application.

    --
    -- To dream a dream is grand, but to live it is divine. -- Leto ][
    1. Re:Ask a craftsman about tools some day... by Cobralisk · · Score: 1

      Php is more of a tool box than a tool itself. In the box there are many tools, some are good and some are not as good. They all serve a purpose, but the junk tools get in the way of the good ones.

      It would be better if someone cleaned the toolbox out. I'm in favor of dropping the function bloat in favor of libraries. Keep the equivalent of java.lang.* in the core language.

      The part of php that tends to attract inexperienced programmers is the easy to find online reference. To help with the quality issue of wild php code the manual would benefit from a section on code style and qualtiy for inexperienced programmers. The barrier to entry is too low, we can't just ignore php and hope it goes away.

      --
      Waiting for ad.doubleclick.net...
    2. Re:Ask a craftsman about tools some day... by Dion · · Score: 1

      I'm sorry, but no, PHP, the language, is broken.

      Arrays that are also hashes?

      Stuff like borrowing Perl syntax, but doing it slightly differnt so everybody gets it wrong really got on my nerves until I stopped trying to use it.

      --
      -- To dream a dream is grand, but to live it is divine. -- Leto ][
    3. Re:Ask a craftsman about tools some day... by The+Clockwork+Troll · · Score: 1

      The lack of lexical scoping and proper namespaces is really what kills the language.

      --

      There are no karma whores, only moderation johns
  65. Re:mysql_escape_string, mysql_real_escape_string, by Anonymous Coward · · Score: 0

    ... or 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... It doesnt, and it shouldnt. Your query should contain the wildcarding directive in it directly by appending to the string. Simply put:

    SELECT * FROM titles WHERE notes LIKE ? + '%'

    Please don't gripe about prepared statements if you don't know what you're doing with them. Prepared statements are meant to ensure that when data is placed into the the string, it is formatted in such a way that it is always escaped and contains no directives or processing instructions themselves. You place the wildcard into the format string itself, thus you get controlled wildcarding based on data.

    Regards,
    -Steve Gray
  66. Re:mysql_escape_string, mysql_real_escape_string, by nacturation · · Score: 1

    Is there a situation where you would be unable to use a stored procedure to accomplish the same tasks?

    --
    Want to improve your Karma? Instead of "Post Anonymously", try the "Post Humously" option.
  67. wrong question! by chdig · · Score: 1

    PHP application security. Do we blame php for the fact that it's a web language? On an enterprise application level, PHP doesn't have the highest penetration, but since the mass majority of web apps, from 20 liners to tens of thousands of complex open source ones, are done by independent developers or SMEs who require a stable, free, portable web language with low barrier to entry. Given the choice of LAMP on so many ISPs, PHP is the language of choice for the web. Since the web is MUCH less secure than any other type of development, it makes perfect sense that PHP is the least secure language out there, whether caused by the developers or the language itself, I'd say it's the least secure simply because it's the most ubiquitous web language out there. Your average one-off developer or small company doesn't have proper QA procedures. Enterprise level software is generally created in an environment that is more security-aware. Not the software, not the developers (necessarily), but the programming environment. As a PHP programmer for 6 years, I've learned my share of security lessons, and am aware of PHP's issues, but it's a language made from the beginning for the WEB (unlike java and much of .NET), and has inspired some of the most exciting web apps that exist. PHPBB was insecure, but so popular because virtually anyone could use it. Its popularity and insecurity both came from PHP. PHP still needs to work on the balance of accessibility v.s ease of programming and backwards compatibility, and with version 6, they seem to be doing just that. --- PHP is the most popular web language. It operates in the least secure environment, and tends to be developed in non-QA'd environments more than other languages. Least secure language? Yeah, sure... that's it's nature! For web-coding in a QA'd environment by experienced programmers, the code is quick, efficient, portable, perfectly secure, and likely took less time to code than (almost) any other language.

  68. Is that bad? by sheldon · · Score: 1

    My background is a combination of hobbyist and ComSci. I started in junior high with BASIC, and did C development for a time, got into infrastructure and now work exclusively with C#.

    PHP is definately a hobbyist language. We need those, because there always needs to be a place for people to learn.

    But I think what we in the industry need to do is a better job of explaining why things are bad, and why and *WHEN* you'd be better off moving to something different.

    I think the mistake that I've seen PHP make is actually to try to focus on making PHP more of a grownup language, and less of a useful language. As such the more recent versions of the framework are not near as popular as version 4 was. What they risk by trying to be more like say Java or C#, is they risk having the hobbyists move on to something different. They will never compete with Java or C#, so why try? Keep your niche happy.

    So I see your point, but maybe what you are really saying is that you personally have outgrown PHP and it's time to move on to something different.

  69. Re:mysql_escape_string, mysql_real_escape_string, by Matts · · Score: 1

    And your comment really bothers me. There should be ONE function that safely escapes data for your database. Look at perl's DBI. You can ALWAYS rely on $dbh->quote() to do the right thing (though you should really use prepared statements and bind parameters).

    Why does a supposedly simpler language make security so much harder?

    --

    Matt. Want XML + Apache + Stylesheets? Get AxKit.
  70. Re:mysql_escape_string, mysql_real_escape_string, by MagicM · · Score: 1
    FIRST : stop forcing prepared binded statements for all
    From the looks of it, you're equating "prepared binded statements" with "one single hardcoded statement with parameters". That doesn't have to be the case. You should still use binds to pass the user-input to the SQL statement, but that doesn't prevent you from using:

    $sql = "SELECT * FROM myData WHERE CONTAINS (column,";
    if ( something ) {
        $sql .= "?)";
    } else {
        $sql .= "'FORMSOF (INFLECTIONAL, ' + ? + ')')";
    }
    You can write your statement as varied as you want. Just ensure that user-input can't affect what you intend the statement to do (and binds are the safest, most future-proof way to do this).

    SECOND : parameter binding through naming
    If MySQL and/or PHP doesn't support this, then that's too bad. There is no reason why they can't support it. For example using Oracle and Perl's DBI package you can do:

    $sth = $dbh->prepare(qq{
        INSERT INTO foo (id, bar)
        VALUES (foo_id_seq.nextval, :bar)
    });
    $sth->bind_param(":bar", 42);
    $sth->execute;
    But if you "cant wait" for when this is available, you are apparently willing to use it. Then the only argument against using the (slightly more cumbersome, but no less secure) version that uses numbered placeholders is... laziness. I think.

    THIRD : i want to see the final SQL
    For debugging, that's a valid argument. However, if you set it all up correctly, you'll end up with EXACTLY the final SQL, minus the user-entered values. For debugging correctness of your SQL, this should be more than enough. If you are doing performance testing, having the "base" SQL handy and executing it manually by search-and-replacing the "?"s couldn't be easier.

    Other than technical reasons (such as "the version of the database doesn't support it"), there is no good reason not to use bind variables when combining user-input with a SQL statement.
  71. Re:mysql_escape_string, mysql_real_escape_string, by nahdude812 · · Score: 1
  72. One example. $_GET() by neo · · Score: 1

    This variable should be SCRUBBED FOR CODE before I get it. That's the secure thing to do. If you want an unscrubbed version with php code in it, then I should as for it with an insecure variable like $_GET(code,insecure);

    Don't let the newbie make the newbie mistakes. Let the advanced user have what he needs the .01% of the time it's warranted. (How often do you really want code in your $_GET()?

    1. Re:One example. $_GET() by Utoxin · · Score: 1

      I don't know where to start with this... Heh.

      $_GET is not a function, first of all. It's an array, containing the contents of the GET request. And it is quite clearly labeled as being the GET request. ANYONE who knows ANYTHING about security knows that you treat it with extreme caution. Want it always escaped? magic_quotes_gpc is your ticket. With that turned on, any value that comes in from GET, POST, or Cookies will be escaped with addslashes().

      Want a different escaping method? Turn off magic_quotes_gpc, and in your codebase, filter them yourself before your code does anything with them.

      Me? I leave them alone, and escape them on use, as necessary in the given situation. mysql_real_escape_string() is a godsend when used properly. (I almost always wrap it in the much shorter and easier to type my_escape() function myself.)

      To get back to the question from the article: Is it the languages fault? Well... maybe a little. Things could certainly improve. But by and large, it's people doing Dumb Things. People have been doing dumb things for decades with computers. They will continue to do them for decades.

      --
      Matthew Walker
      http://www.tweeterdiet.com/ - My Diet Tracking Tool
    2. Re:One example. $_GET() by kayditty · · Score: 1

      you forgot to tell him that no one is worried about PHP code being passed to $_GET, as well. that code will not likely be executed, unless someone eval()s it (or maybe if a GET value is a URL which the script somehow manages to remotely include).

  73. Re:mysql_escape_string, mysql_real_escape_string, by Anonymous Coward · · Score: 0
    How to make safe MySQL queries:

    function sql_safe($value)
    {
      if (get_magic_quotes_gpc()) {
          $value = stripslashes($value);
      }
      if (!is_numeric($value)) {
          $value = "'" . mysql_real_escape_string($value) . "'";
      }
      return $value;
    }
     
    $sql= sprintf("SELECT * FROM sometable WHERE variable=%s", sql_safe($variable));
  74. Re:mysql_escape_string, mysql_real_escape_string, by Anonymous Coward · · Score: 0

    Use prepared statements. Period. Full Stop.

  75. Having long abandoned PHP by spankfish · · Score: 1

    It's reading about issues like this that make me love Hibernate, Struts and Tomcat. At least at work. ;-) It's all about the sensible security defaults and maintainability, neither of which are particularly common in PHP development. Seriously. All you PHP fanboys, I don't know if you're just scared of the learning curve or what, but the jump to J2EE is totally worth it for any serious application.

    --

    NO TOUCH MONKEY!
  76. Re:mysql_escape_string, mysql_real_escape_string, by tobi-azz · · Score: 1

    You can do everything you want with php5's native PDO (http://www.php.net/pdo). Any php prior to version 5 is trash.

    FIRST: Use PDO::query() if you don't want prepared statements.

    SECOND: PDO supports naming. Replace the ? with :name

    THIRD: You can probably do a dump on the statement object or something along those lines.

  77. What exact;y is PHP by Anonymous Coward · · Score: 0

    Which of the many open source libraries and tools compiled into PHP are "php"? That, in my opinion, is the security issue with PHP. The language isn't implicitly insecure. But the language links to a plethora of libraries that have different maintainers and different quality standards. If PHP is your sexual partner, you sleep with every library it sleeps with.