Slashdot Mirror


How Prevalent Are SQL Injection Vulnerabilities?

Krishna Dagli writes to tell us of an investigation, by Michael Sutton, attempting to get an estimate of how widespread SQL-injection vulnerabilities are among Web sites. Sutton made clever use of the Google API to turn up candidate vulnerable sites. You might quibble with his methodology (some posters on the blog site do), but he found that around 11% of sites are potentially vulnerable to SQL injection attacks. He believes the causes for this somewhat alarming situation include development texts that teach programmers insecure SQL syntax, and point-and-click tools that allow the untrained to put up database-backed sites.

37 of 245 comments (clear)

  1. The abuse of SQL injection by Reality+Master+201 · · Score: 5, Funny

    destroys thousands of lives a year. Sure, it starts small - a SELECT there, a few INSERTS on the weekend. Eventually, though, you're using stored procedures and trying to score triggers in the middle of the night.

    Just say no, kids.

    1. Re:The abuse of SQL injection by Reality+Master+201 · · Score: 2

      Hey, thanks. People are stupid and humorless; you get inured to it after a while.

    2. Re:The abuse of SQL injection by Reality+Master+201 · · Score: 4, Insightful

      Yeah, but most people are still stupid and humorless. So, in the end, I come out ahead.

  2. Unfortunately: Not Surpirsing by charleste · · Score: 4, Insightful

    This is a possibility that was obvious back when I was developing web applications as far back as 1996 using CGI. The approach in TFA was a similar approach we used "back when" to demonstrate the need for (a) not using GET, (b) turning off verbose error reporting, (c) controlling *how* queries were made (e.g. architecture of the app and DB I/O), and (d) storing sensitive data encrypted. The sad part is that it is *still* a problem. I guess it underscores the need for a decent architect as opposed to letting whiz-bang do-it-yourselfers start coding without design, and the need for security analysis, et. Al. Just my 2 cents.

    1. Re:Unfortunately: Not Surpirsing by CastrTroy · · Score: 4, Informative

      How does not using GET stop anything, you can POST anything you want to a webserver just like you can GET anything you want from a webserver. Only using POST will make things a little harder, but it doesn't stop anything.

      --

      Anthropic principle: We see the universe the way it is because if it were different we would not be here to see it.
    2. Re:Unfortunately: Not Surpirsing by dgatwood · · Score: 2, Insightful

      Using POST doesn't make it any harder. It just makes the address bar less ugly.

      IMHO, any web application should be written to accept both GET and POST. I'm very annoyed with USPS.com for this very reason. I have a small Dashboard widget that I use to track packages. Short of writing some custom redirect script on a server somewhere, I cannot construct a URL that I can use to create a clickable link to the tracking results.

      I sent an email to the USPS webmaster and asked if there was anything they could do to help, and they pretty much said "no". Same problem with DHL, but I don't care enough to bother with them because I so rarely get packages delivered by DHL.

      UPS and FedEx work fine and have worked fine for years because their programmers had a clue. Needless to say, while I can't control what service other people use to send packages to me, I make it a point when shipping packages to other people to always use a service that supports GET requests in their forms even if it costs more than USPS. So their insistence upon POST over GET is costing them business, at least from this customer.

      --

      Check out my sci-fi/humor trilogy at PatriotsBooks.

    3. Re:Unfortunately: Not Surpirsing by ehud42 · · Score: 3, Informative


      "SELECT `userID`,`user`, `password` FROM `table` WHERE `user` = 'trim($_POST['user'])'"


      Ack! Nice demonstration of the code that is vulnerable to attacks!

      My user id is '; drop database; --

      --
      I'm in my right mind and I have the answer to everything!
    4. Re:Unfortunately: Not Surpirsing by Ford+Prefect · · Score: 3, Insightful

      IMHO, any web application should be written to accept both GET and POST.

      No. Web applications should use GET and POST where appropriate - GET for idempotent requests (showing database records, search results, those kind of recurring, non-database-changing things) while POST should be used for things which actually change data, user state, and so on.

      Using GET in the wrong places can lead to all kinds of irritations and miniature security problems. Imagine sending an email to your web application administrator containing something like the following: <img src="http://example.com/webapp/user_admin?action=e dituser&username=me&accesslevel=administrator" width="0" height="0">...

      Many web applications do get the two horrendously mixed up (I've seen search results done via POST, which is subtly, incredibly annoying) but they're definitely not interchangeable.

      For simply displaying a non-password-protected package shipment page, GET would probably be the best solution. But blindly accepting both isn't a good alternative.

      --
      Tedious Bloggy Stuff - hooray?
    5. Re:Unfortunately: Not Surpirsing by Bogtha · · Score: 2, Insightful

      GET for idempotent requests (showing database records, search results, those kind of recurring, non-database-changing things) while POST should be used for things which actually change data, user state, and so on.

      You are confusing idempotence and safety. "Idempotent" merely means that repeated requests have the same effect as a single request. You should use GET because it is safe, not because it is idempotent. For contrast, DELETE is an idempotent method, but it's certainly not a safe method. For some reason everybody seems convinced that "idempotent" is a fancy word for "safe". See section 9.1 of the RFC, it explains in more detail.

      Using GET in the wrong places can lead to all kinds of irritations and miniature security problems.

      The example you give for Slashdot highlights the difference between safety and idempotence. It doesn't matter if you make the request once or a hundred times, the result is the same - you are logged out. The request is idempotent. The problem is that it's not safe, because it alters application state by logging you out.

      The example you give of sending an email is a bad one. Consider sending an email to the admin containing an iframe that generates a form and auto-posts it.

      The correct way to guard against vulnerabilities like this is to generate a per-user nonce. Include it as a hidden field in every legitimate form and check for it in every form handler.

      --
      Bogtha Bogtha Bogtha
    6. Re:Unfortunately: Not Surpirsing by Snover · · Score: 2, Informative

      I hope not, since mysql_escape_string() will also allow for SQL injection by not respecting the character set of the MySQL connection. The PHP Group, in all its brilliance, decided to add another function, which they named mysql_real_escape_string(), rather than simply fixing the first one. /me sighs

      --

      [insert witty comment here]
  3. Simple solution by CastrTroy · · Score: 5, Insightful

    The simple solution is to use parameterized queries. I don't know why more books don't know why more books don't push this methodology, as it makes you program faster, easier to read, and also makes you invulnerable to SQL injection attacks.

    --

    Anthropic principle: We see the universe the way it is because if it were different we would not be here to see it.
  4. Re:Return of the Flat File by ip_vjl · · Score: 3, Insightful

    Won't work. The same 'novices' who leave gaping SQL injection holes will now be writing pages that need to access the file system. Now instead of accessing the DB, script kiddies will be traversing the filesystem. Yes, this can be mitigated through file permissions, but there are a lot of servers out there (set up by these same novices) where processes run as root and would have full access to read and write files. So, a bad script could allow them to write to /etc/passwd and have all sorts of fun.

  5. No. That's a stupid idea. by Reality+Master+201 · · Score: 2, Insightful

    Stupid application construction isn't a good reason to make the design of the app even stupider.

    In the old days, everyone used flat files, because that's what there was. Then someone (several someones, most notably Codd and some others at IBM) realized that breaking the flat data into sets of discrete data that related to each other reduced redundancy and allowed for an overall better quality of data. And it wasn't app specific.

    The answer to SQL injection is to test apps more completely (including tests for this kind of attack), to provide extra checks at the database level (for integrity issues, perhaps in the form of constraints, etc. dependent on the scale and structure of the database), and to develop tools/libraries for data access that make this kind of thing hard to do accidently.

  6. Re:Return of the Flat File by RingDev · · Score: 3, Insightful

    Why convert to an entirely different structure when just implimenting proper code standards will suffice? Using parameterized stored procedure calls instead of dynamic SQL will not only protect you from the vast majority of SQL Injection attacks, but will also improve the performance of your web page.

    -Rick

    --
    "Most people in the U.S. wouldn't know they live in a tyrannical state if it walked up and grabbed their junk." - MyFirs
  7. Re:Sure, blame the "untrained" developers.... by tuffy · · Score: 3, Insightful

    In short, trusting the client (i.e. the web browser) to not send bad values - either through the INPUT tag's maxlength attribute, JavaScript scrubbing or whatever - is entirely the wrong way to go. The web script must check all user input for validity along with properly escaping everything from the database that's getting sent back via HTML.

    --

    Ita erat quando hic adveni.

  8. Re:Sure, blame the "untrained" developers.... by dk-software-engineer · · Score: 2, Informative

    I don't think you understand SQL Injection at all.

    If the obvious fix is to exclude special characters from password fields

    It's not. First of all, it wouldn't work. Second, it makes to sense at all at any level. Sorry if I seem rude. :)

    There are a lot of new programmers (or whatever we're calling people who make websites these days), who are not naturally paranoid and sensitive to the exploitation of their code. They shouldn't need to be.

    I agree, but it's a dreamworld. I shouldn't need to fiddle with keys or whatever every time I use my car or get home. But I do.

    Luckily you can create pretty safe code by making nice code. It's amazing how many side-effects "nice" has. But yes, you'd need to be a good programmer to make nice code.

  9. Some kind of software checklist by Realistic_Dragon · · Score: 4, Funny

    There should be some kind of government run website somewhere.

    You would answer questions and it would give you license keys to software that you were qualified to use. For example, I might tick:

    Engineer (check)
    Artist ( )
    Manager (check)
    Linux (Check)
    Mac ( )
    Windows ( )

    And it would issue keys for website point and click installation software, Vi, apache and Latex - but deny me keys to powerpoint thereby saving the lives of people who might otherwise have to gnaw off their own leg to survive my 8 hour presentation on optimising synergisyms in a web 3.0 environment by sub molecular interactions.

    --
    Beep beep.
  10. testing methods by Akatosh · · Score: 4, Insightful

    This 11% was determine by a weak testing mechanism. For every site that baltently spews sql errors to the user there are two that silently return a generic sanitized error, and another two that return no error at all. It would produce more results if you take it a step further and ask yes no questions, such as:

    ?id=99999' OR '10

    and see if the page returns the results of id=10 as expected. It's also common for people to use weak regexp (regexp should NEVER be used to protect against sql injection, see mysql_real_escape_string) and miss some characters:

    ?id=99999)

    or fail to sanitize non us language encoding. Also, get variables are often the most protected. It is much more common to find sql injection in <input type=hidden variables, or in cookie data. The number 11% is extremely low. I'd guess more like 80%.

  11. The "Oh-Sh*t" face... by moco · · Score: 2, Insightful

    From the article:

    * Many development texts actually teach programmers insecure SQL syntax. ...
    * Many sites are exposed to SQL injection attacks but don't know it.

    I agree completely! I've seen the texts, I've seen the hordes of VB+SQL programmers that learned from said texts moving to the web porting the same "vices" to the new platform.
    And I've seen the "oh-sh*t" face on a couple of developers after demonstrating to them that their software is vulnerable to SQL Injection. In both cases the vulnerabilities exposed the customers to the posibility of serious financial damage.

    So far, the stupidest work arounds i've seen have been:
    Developer: It's ok, I'll switch to post instead of get so the user can't forge the request.
    Developer: It's ok, I'll write a method that removes sinlge quotes for every string i get from the user.
    Developer: It's ok, I'll write some java script that will validate user input.

    Writing secure software is never easy.

    --
    moi
    1. Re:The "Oh-Sh*t" face... by valloned · · Score: 4, Insightful

      Microsoft VB.NET and ASP.NET texts are AWFUL in this regard. Nearly all examples use in-line SQL queries rather than paramaterized stored procedures. Why? Probably because they are trying to fit in with Microsoft's strategy that devoping applications should require absolutely no knowledge of code (or anything else for that matter). The big selling point for their VS 2005 suite is "no code required". That speaks volume.

    2. Re:The "Oh-Sh*t" face... by jrockway · · Score: 3, Informative

      > Writing secure software is never easy.

      It's easy if you use good tools. PHP is not a good tool. Rather than hacks like mysql_replace_the_string_with_things_that_wont_com primise_my_database(), you should be using tools that make it impossible to inject SQL.

      Some ideas:

      Perl's DBI, whose docs tell you to ALWAYS write SQL like:

      $sth = $dbh->preprare('SELECT foo,bar FROM baz WHERE something=? AND another = ?')
      $sth->execute(q{''Some\ things"'}, 10);

      Notice that the programmer can't forget to escape the SQL -- because there's no escaping.

      Even better is something like DBIx::Class, which lets you write

      $resultset = $table->search({something => q{''Some\ things"'}, another => 10});

      Again, no opportunity for the programmer to fuck up the SQL in any way. It's just like getting data out of the hash... DBIx::Class will generate the SQL (for any backend), run the query, stream in the results as needed, etc. It's easier and it's better!

      Ruby on Rail's ActiveRecord is similar, but it's impossible to do certain types of joins. DBIx::Class is better in this regard. (And Perl is faster than Rails, and Catalyst is more complete rhan Rails :)... but both Ruby and Perl are MUCH better choices than PHP.

      PHP makes it easy to write insecure code. Perl makes it hard! (With taint mode, a selection of ORMs, 10000+ well-tested modules, and nicities like Moose, Moose::Autobox, etc.)

      --
      My other car is first.
    3. Re:The "Oh-Sh*t" face... by Nos. · · Score: 3, Insightful

      Or use the appropriate PEAR classes with php, like MDB2, which documents how to do prepare/executes. Don't suggest that PHP is worse than PERL because PERL has DBI, PHP has addons as well.

    4. Re:The "Oh-Sh*t" face... by Ford+Prefect · · Score: 2, Interesting

      And I've seen the "oh-sh*t" face on a couple of developers after demonstrating to them that their software is vulnerable to SQL Injection. In both cases the vulnerabilities exposed the customers to the posibility of serious financial damage.

      Have you seen the 'oh, that's not a problem, we're using SSL so it's completely secure' face yet?

      As for stupidest work-arounds - a site I was doing a vague security audit for (sans source-code, alas) was (is) rife with SQL injection vulnerabilities. On attempting to explain this to the programmer, with very simple code examples, I was confronted by some increasingly complicated 'solutions' to the problem.

      It was an integer database ID. But strings would go in. I suggested converting it to an integer. But no, programmer decided to do a search-and-replace on SQL keywords in the string.

      So I used lower-case SQL keywords, and strongly recommended converting to an integer.

      Programmer added lower-case SQL keywords to his search-and replace routine.

      So I used mixed-case SQL keywords, and told him to stop being silly and just convert to an integer.

      Last seen, the code was replacing non-digits with &nbsp;. Okay, so it removed SQL injection attacks from that particular variable, but AAAAARGH.

      --
      Tedious Bloggy Stuff - hooray?
    5. Re:The "Oh-Sh*t" face... by XanC · · Score: 2, Informative

      Prepared statements aren't there to guarantee that every datum you insert is the "correct" type for what you're trying to do. What they do is guarantee that nothing in your variables will be interpreted as part of the SQL command.

      If I have "10; <naughty stuff>" in $numeric_var, it will attempt to insert (or select, or whatever) exactly that string, without interpreting it. The data may be useless, but it will not be executed.

  12. Massively widespread problem by shawnmchorse · · Score: 3, Insightful

    If anything, I'd question how FEW sites they claim are vulnerable to SQL injection. It's an insidious problem that just creeps up on you anytime you don't think about it sufficiently (as when writing something quickly, on a deadline... not that this ever happens!). I know that at my workplace we fell victim at one point to a SQL injection attack on one of our (many) custom PHP scripts. We eventually found out how it worked through the web logs and were able to fix it, but honestly even after we did our best to clean things up... I'm dead certain that there are still probably hundreds of places that we're still vulnerable. This is due to a number things including the sheer volume of PHP code in use, the fact that the code has been written at various points in time over a period of six years or so, and the fact that this code has been written by at least twenty different people. It's like trying to plug holes in a dam.

  13. Re:Sure, blame the "untrained" developers.... by jizziknight · · Score: 2, Insightful

    As some others have pointed out, there are tools to get around that sort of thing. You should be validating all input server side, whether it's validated client side or not. There are also very easy ways to deal with SQL injection already, such as parameterized stored procedures. Doing what you suggest would involve a hell of a lot of recoding, break a hell of a lot of existing sites, and proceed to punish good coders by making them work around the "safe-guard". Programmers who don't take steps to protect against SQL injection deserve to have their sites hacked. And guess what? If they have their sites hacked, they'll probably remember to do something about it in the future, or hire someone who already knows how.

    I may sound like an elitist by saying the following, but secure programming should not be "easy" for the "masses". It should be reserved for those who know what the hell they're doing, and they should be paid accordingly. I do not believe it's wise to give the average Joe the tools to make even slightly sophisticated programs. We've seen what happens when we do this; take a look at most websites from the dotcom bubble.

    --
    Everything I say is a lie. Except that... and that... and that, and that, and that, and that... and that.
  14. Re:Sure, blame the "untrained" developers.... by CaffeineAddict2001 · · Score: 2, Funny

    This is kind of like saying we can prevent buffer overflow exploits by having the windows API not allow people to enter shellcode into textboxes.

  15. Re:Sure, blame the "untrained" developers.... by merreborn · · Score: 2, Insightful

    All the HTML standards in the world won't stop an attacker with a copy of telnet.

    bash$ telnet example.com 80
    GET /vulnerable_app.php?id=%2310 HTTP/1.1

    Two things to note here: (1) there's no HTML involved in the actual transaction at all (2) like another poster said: you can't trust the client to send valid data.

    Stick to purposing solutions for things you know about.

  16. Turn Key solutions broken? by Bryansix · · Score: 2, Insightful

    Why are the point and click or turn key solutions so vulnerable to SQL injection in the first place? I had a friend with a PHPBB site that got shot to all hell when some cracker came along and defaced it. Why wasn't it secure out of the box? Second of all, why is it that every website has to worry so much about security. I know about databases but I don't know the first thing about preventing an SQL injection attack and why should I have to. There is nothing sensative on my sites. Let me throw out this analogy.

    Let's say I own a house and around Christmas time I put out an inflatable snow man. Then some vandals come along and pop it. Are you going to walk up to me while I'm sulking over my snow man and say "Don't you know you have to wrap your snow man in kevlar to prevent vandalism and then put up an electified fence with constantine wire on it."? I would give you the strangest look if you did. Then I'd probably say something pertaining to the fact that the police should catch these bastards and presecute them.

    So why is it with technology that no emphasis is put on catching vandals and bringing them to justice and a ton of emphasis is put on protecting your site from attack?

    1. Re:Turn Key solutions broken? by winomonkey · · Score: 2, Informative

      Perhaps it would be more appropriate to use an analogy of vandals mortaring your snowman. For, you see, the problem with the e-vandals is that they are not actually physically present when they attack your snowman. Yes, there is proof that they attacked you, but chances are that determining their physical location is hard. Sure, you could look at the trajectory of the incoming projectile, but even then you are having to do a lot of imprecise and possibly flawed work to find out just where these attacks are coming from.

      Another analogy, regarding security, is that of the attractive and financially well-endowed woman walking in a dark alley in a bad part of town. Sure, she SHOULD be safe, because she is a human and everyone should have some sort of basic respect for the dignity and humanity of all other people. Why is it, then, that she should have mace or a gun in her handbag? Why does she need to take a precaution to mitigate actual harm to her person? Why should she avoid a part of town known as being dangerous?

      Apply this to web development. Why should developers protect their code? Why should they take extra steps to secure their sites and servers? Quite simply, the internet is a bad part of town, and we need to make sure that we are not doing things that make us susceptible to attack.

      Concertina wire is more likely to help than counting on the prosecution of attackers and vandals.

  17. Re:Return of the Flat File by MagicM · · Score: 4, Informative

    That, and/or bind, bind, bind. Concatenating user input into your SQL statements is bad on both security and performance.

  18. Re:Criminalize? by bestinshow · · Score: 2, Informative

    Even if they did prosecute, it does you know good once they'd messed with your database or otherwise hacked you.

    It isn't hard to secure an online application against SQL injection. So there's no excuses for the developer to write 'SELECT blah FROM table WHERE field='$forminput';' directly in their code is there?

    Your example should be about you going to the police station complaining because you don't have a lock on your door, not because you need a paid security guard.

    Yes, I agree that hacking crimes should be punished more, but that doesn't absolve you of your responsibility to secure yourself and your property.

  19. Re:Sure, blame the "untrained" developers.... by Mister+Whirly · · Score: 2, Funny

    ATM = Automatic Teller Machines

    "ATM machines" = Automatic Teller Machines Machines - definitley leave it to the pros, otherwise you may screw up on your "PIN number"

    (Apologies for being a pseudo-grammar Nazi)

    --
    "But this one goes to 11!"
  20. Re:Let's find out... by arclyte · · Score: 2, Informative

    Well, I have verbose error messages turned on on my local dev server to make debugging easier, but we log all errors on the live site, returning an "oops! something went wrong" generic error to users. Verbose errors can give you a lot of information, depending on what the error is.

    First of all, it's going to tell a hacker what kind of system you're using. They'll probably find out anyway if it isn't apparent, but who wants to give them any help along the way? And then it all depends on what the error is. If i'm making reads to the filesystem or requiring files and I screw up the path, verbose error reporting will spit that path out. Now the hacker knows what your file system looks like, and possibly what kind of system you're using. Also, while the hacker is busy trying out various methods to inject SQL, verbose errors may spit out the entire failed query, giving them full knowledge of how to edit it to make it work...

    All around, it's just a very bad thing.

  21. Why errors are good for crackers by omgwtfroflbbqwasd · · Score: 2, Insightful
    The SQL error message unto itself is not an indicator of vulnerability. It *is* an indicator that you were able to get input from the web form to manipulate/modify the SQL query (and break it). This is the first step in determining whether a given web app is even exploitable. If all you keep getting back is "invalid username" or a normal app response, it's unlikely that the app is vulnerable.

    The trick to exploiting SQL injection is being able to figure out the right sequence of input characters needed to gracefully terminate the intended SQL command, while also being able to craft a subsequent SQL query that does what you intend. Alternatively, you may want to modify the intended command. For example, "SELECT orderstatus FROM table where orderid = $FORM{'orderid'}" expects the orderid form field to be some value that's in the table somewhere. If instead you enter "1 OR 1=1" as your input, you'd get every row back since 1=1 for all rows. Using this example, you could also try to append a new query, by entering something like "1; drop database;". Many times an attacker will need to find various escape characters, quotes, etc. to get their input crafted properly to exploit the app.

    SQL errors in web apps are what web crackers like to see for the same reason that exploit authors like to see segfaults where EIP=0x41414141.. it means that they were able to get their input down to the execution point in a program that got past the boilerplate protections that the app had in place (if any).

  22. You don't need to bother with SQL Injection by thewils · · Score: 4, Interesting

    If you search for "mdb" you can download the entire database without too much trouble.

    I recently came across a commercial site where you could substitute, for instance, "(select first_name from users where id=1)" into the page url and a nice error screen came up telling you that it couldn't convert "George" into an Integer.

    It's not the SQL Injection per se that is the biggest problem, but the nice error messages you get back giving you, more or less, a SQL command line interface. Errors should be detected and redirected to a sanitized page, or if you can't be bothered, an unceremonious crash.

    I notified the owners of that site by the way.

    --
    Once I was a four stone apology. Now I am two separate gorillas.
  23. RFC 2616 doesn't say anything about proper use by omgwtfroflbbqwasd · · Score: 2, Informative
    Are you referring to a different RFC? 2616 establishes the function for the various HTTP requests, among other things. The only recommendation that it provides is regarding sensitive data as part of a GET URI, from section 15.1.3:

    Authors of services which use the HTTP protocol SHOULD NOT use GET based forms for the submission of sensitive data, because this will cause this data to be encoded in the Request-URI. Many existing servers, proxies, and user agents will log the request URI in some place where it might be visible to third parties. Servers can use POST-based form submission instead

    Repeat after me kids: "GET and POST are equally tamperable and equally (in)secure. The only thing they are not, is equally logged".