Slashdot Mirror


SQL Injection Attacks Increasing

An anonymous reader writes "Help Net Security has a story that covers the dramatic increase in the number of hacker attacks attempted against its banking, credit union and utility clients in the past three months using SQL Injection." Article follows up on press release with a little more information. Not a lot here shockingly surprising, but it's worth mentioning that SQL injection is a real pain for web developers. You have to be very careful about checking user input.

35 of 384 comments (clear)

  1. Another web developer pain... by Anonymous Coward · · Score: 5, Funny

    Sudden traffic surge from certain news sites can be a pain.

  2. How difficult is it. by El_Muerte_TDS · · Score: 4, Informative

    Simply forcing request variables to the correct type and escaping all strings is pretty much the only thing you need to do.
    Most languages provide the functionality to do that (in php: intval() for all integer request vars, and _escape_string() for string data.).
    It's just a small amouth of work, yet a lot of people are way to lazy.

    1. Re:How difficult is it. by eggoeater · · Score: 4, Informative
      Simply forcing request variables to the correct type and escaping all strings is pretty much the only thing you need to do.
      Or you could just use stored procedures.
      I've been doing that for years without any problems.
      I've also never had any issue with "business logic". I can keep my business logic
      seperate with stored procs. (I never understood that argument against them.)

    2. Re:How difficult is it. by aymanh · · Score: 4, Informative
      PHP doesn't force you to do that by hand, you can make use of the numerous database abstraction layers for PHP, like PDO or PEAR::DB.

      Here is an example, taken straight from PDO's page:
      $stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
      $stmt->bindParam(':name', $name);
      $stmt->bindParam(':value', $value);
       
      $name = 'one';
      $value = 1;
      $stmt->execute();
      The framework is there, PHP developers need to make use of it, but sadly things like the following are still common:
      mysql_query('SELECT value FROM REGISTRY WHERE name = "' . $name . '"');
      --
      python>>> q="'";s='q="%c";s=%c%s%c;print s%%(q,q,s,q)';print s%(q,q,s,q)
    3. Re:How difficult is it. by beavis88 · · Score: 4, Informative

      1) Use a sensible naming convention. eg P_User_Create, P_User_Delete, etc. Use the naming conventions to effectively categorize your stored procs. This takes a little planning and discipline, but what "best practices" don't? The "intellisense issue" is a red herring IMHO - if anything, you're worse off in this regard without sprocs.

      2) USE SOURCE CONTROL. Without trying to be nasty, you're insane (or a one man operation) if you use the database as your authoritative source for stored procs. If you have any environments beyond a production server, the ability to script installation/alteration of procs is essential.

    4. Re:How difficult is it. by CaptainZapp · · Score: 4, Informative
      Sure you could have files with all your stored procedures in them

      Bingo!

      but then you have to have 2 copies of everything.

      Stored procedures (like any DDL statements to set up your database schemas) should be handled like any other source code and treated as such. This includes version control

      There seems this "but I can pull it out of the database with my super GUI tool, so why should I keep it on file too?" attitude. Well, duh; it's mighty hard to pull anything of a database whoms disk just crashed.

      For recoverability reasons database objects (including stored procedures) should be scripted and version controlled. Period.

      --
      ich bin der musikant

      mit taschenrechner in der hand

      kraftwerk

    5. Re:How difficult is it. by Anonymous Coward · · Score: 4, Insightful

      "If your database interface doesn't suck completely, like PHP's default one"

      Wow! How intelligent, I expect this to be modded up before I ever post...after all this is slashdot.

      Quite honestly, as a programmer, I expect the applications to do as I ask them to, and not hold my dick at every opportunity. If I want something passed to a SQL statement in the way I've asked it to, I don't expect my data to be munged by the application to protect me.

      I'm sorry, but this rash of piss poor programmers that don't know how to program, nor care to do any security on their own part is a problem unto themselves and not a symptom of an interfact that completely sucks. Folks that make blind statements about folks who suck generally are the ones wiping their lips afterwards from the sweet juice of man-gina.

      I've been programming for nearly 20 years. I've used probably a dozen languages and every year I hear from the kiddies about how much more one app needs to do for you than the other. And usually its a bit more convenient and thus I generally adopt the language that helps get things done quicker. At the same instance, I never forget its me that has to be assured of the security and understand the lower level concepts so that if someone isn't taking this into consideration with this particular release of their language you'll be fucked (and its happened to me before in off version releases of 'secured' 'programming languages' -- luckily I was immune in most instances).

      So if anyone is missing a point, its the guy stating there is only one database iterface for Perl, the guy that believe perl is a decent language to write in (in my 20 years of programming and teaching an upper level computer science theory course at one point), perl has been the only language I've decided to entirely skip after realizing how bad it really was and the fact it was designed solely to appease geeks that wanted to repell the opposite sex. You'd find more readable code programming in Klingon, to put a statement that you might understand.

      Seriously, if I had mod points today, I would have simply modded every post of yours down today, but I decided to respond anonymously, and I hope mine gets modded down just as yours does. If you are going to write something ignorantly, write it anonymously where most of us can ignore it.

    6. Re:How difficult is it. by ubergenius · · Score: 3, Insightful

      PHP has always had this problem, and it always will, because the major reason why PHP is so prevalent on the web is because it is highly accessible to all users, even the most uneducated and unknowledgable individuals, allowing anyone to make a dynamic webpage. However, just as PHP allows anyone to write easy code, it also allows anyone to write proper, secure code for those who understand how to do it. Once again, the problem lies between the keyboard and the chair.

      --
      Student Manager - Take control of your education!
    7. Re:How difficult is it. by Tony+Hoyle · · Score: 4, Insightful

      Yes you do. No matter what language you use if you take user input and put it in an SQL string you're asking for trouble. It's not the language that's the issue it's the programmers.

    8. Re:How difficult is it. by Anonymous Coward · · Score: 4, Insightful

      "Why not write lightning-fast code in C instead? If you're trading speed for convenience by using a high-level language, why wouldn't you want to use something that is even more convenient?"

      Because the modern CPU has rendered the need for compiled languages pretty much to nothing.

      There are times I will revert to a C backend for functionality that needs massive processing without a lot of connection to the outside world. I've done this on a recent project where I needed to analyze text to parse into a synopsis. Early prototypes of the workflow used both PHP and Perl because I like the readability of PHP but one of my lead developers likes the textual nature of Perl...I actually agreed with him on this point and allowed him to design the prototype in this so that we could tweak the algorythm in realtime without having to do a 30 minute compile each time -- which is about how long it takes to do the final C routine. As a development and prototyping language, it worked out, but was slow. It was also very hard to understand mixed with idiosynchratic perl and higher level mathematical formulae to derive this. The C was much cleaner.

      If it wasn't for the textual nature of Perl, I would have never allowed it to be used. I ended up keeping a second set of code developed in parallel that by the end was actually easier to maintain and faster than Perl in PHP. Both were several factors slower than the compiled application regardless of how you looked at it.

      "why wouldn't you want to use something that is even more convenient?"

      Because convenience doesn't mean that you shrug off the responsibility of protecting your code, or using good practices simply because someone else might have put it into their application. If you are doing simple queries, you can easily encapsulate your request and be done with it. Fuck, thats what stored proceedures are for and you don't need any fucking programming language to do that correctly. Work with anything that requires more than a single join and a simple where statement and you give the user the ability to shape this, and you've gone beyond the ability of stored proceedures and views or the simple data encapsulations that you are offered in these languages. Probably why I see all these Perl and RoR applications that make a hundred calls to the database to get one tables worth of information and I find this a limitation.

      There are reasons and advantages to use a lot of languages...folks that don't understand this are doomed to keep using the same tools that they did 50 years ago with no advancement.

    9. Re:How difficult is it. by Goaway · · Score: 3, Informative

      You've never used Perl's or Python's database interfaces, have you? You use placeholders, and pass in values separately, and the interface itself takes care of proper escaping. You use a constant string for your query and don't build the SQL query by hand.

      It is both easier, and much more secure.

    10. Re:How difficult is it. by Aceticon · · Score: 4, Informative

      Or you could just use stored procedures.
      I've been doing that for years without any problems.
      I've also never had any issue with "business logic". I can keep my business logic
      seperate with stored procs. (I never understood that argument against them.)


      If your stored procedures are only very thin layers encapsulating low level database access operations (thus not much more than pre-packaged selects, updates, inserts and deletes) you should have no business logic in the database problems.

      On the other hand there's a couple of downsides to such a design:
      - It requires developers with a good level of expertise in both the language used to develop the core of the application and the one used for the stored procedures. This is true both for initial development and for maintenance.
      - It makes an application tightly couple to the database. If you want to port to another database, at the very least you will have to redo all the stored procedures.
      - It increases the likellyhood of having version conflict problems between the core application and the database application components. More specifically, the data-model is usually more stable across versions of the application than the actions executed on data in that model (eg "find all employees in more than Y departments and whose manager is level X"), and thus if you store in the database code which is tightly couple to the actions that the application executes on the data then previous versions of the database (for example, those restored from a backup) are not likelly to work with the lastest version of the application (nor are they likelly to be easilly "fixed" by a DBA).
      - It's harder to debug code that crosses platforms and languages

      More in general, the problem of SQL injection can be avoided simply by using prepared statements or any other type of SQL query that takes input parameters instead of using string concatenation to make SQL queries that include the input values.

      Using stored procedures to solve this specific problem is very much overkill.

      Beyond this, the only good reason i can see for using stored procedures like this is for performance reasons if you do some level of post-processing on the results or some sort of "smart" block updating of data. In this case, stored procedures should only be used in a very small number places (to solve high-impact IO bottlenecks between the application and the database) and not in a generic way.

      The last couple of reasons i see for such a design are:
      - A "job protection" measure by locking the application to the specific skillset combination of a specific developer
      - Because the developer prefers-to/is-more-confortable-with developing code in the database that in the core application
      Hardly good reasons IMHO

    11. Re:How difficult is it. by ttfkam · · Score: 3, Insightful
      PHP succeeds an older product, named PHP/FI. PHP/FI was created by Rasmus Lerdorf in 1995, initially as a simple set of Perl scripts for tracking accesses to his online resume. - PHP history page

      Let me get this straight: you are condemning a programming language but championing the language it spawned.

      As for your comment:
      Quite honestly, as a programmer, I expect the applications to do as I ask them to, and not hold my dick at every opportunity. If I want something passed to a SQL statement in the way I've asked it to, I don't expect my data to be munged by the application to protect me.
      Bwahahaha!! Since when is escaping a single-quote considered an attempt to "hold your dick"? Simple string concatenation for the creation of database is always a bad idea, even for 20-year veterans like you. The last time you were coding at 4am, were you as sharp as you were at midnight?

      Also you are falling into the same pseudo-libertarian trap (tripe?) that many programmers seem to these days. You think that as long as you are doing the right thing, who cares what someone else does? In fact, ridiculing others is a sufficient solution to most problems.

      It's not.

      SQL injection attacks affect me when it's my bank. When was the last time you personally interviewed the web development staff at your bank or credit union? How do you know they are as good as you are? Considering the fact that binding variables is as fast or faster than simple string concatenation in most cases (in some cases, they can be converted to stored procedures transparently on the back end), I have exactly zero problems with a language "holding some dicks" in the name of security. Especially since there is no speed loss in the process.

      Correctness, not "what works." It's the difference between modern chemistry and alchemy. You might end up with the right result, but only with trial and error... mostly error.

      But perhaps this all points to a greater Slashdot problem: too many people who refuse to get their dicks held once in a while. In more ways than one. ;-)
      --

      - I don't need to go outside, my CRT tan'll do me just fine.
  3. Qualifications by Chris+Graham · · Score: 5, Interesting

    Perhaps all programmers working on professional database systems should have to get a professional qualification to show that they can write secure code. I wouldn't say the same should be manditory for things like usability or stability (except for special sensitive areas), but being able to write code that actually allows serious danger without qualification is pretty weird. Builders need qualifications, electricians do, gas installers do, ...

  4. Checking input is a "pain in the ass"?!? by fractalus · · Score: 5, Insightful

    The only people who consider it a pain in the ass are people who are (a) lazy, (b) not adequately security-conscious, (c) programming without a framework that provides good tools to do this. The reason we have so many SQL injections is because we have legions of web programmers who were never taught how to write code in a hostile environment. Web programming is never presented in that light; it's always, "here's a quick little script that fetches twenty records from a database and displays them." Security is far too often a footnote or an appendix that beginning programmers never get to. Building apps for the web is not like doing your Data Structures I homework. You need a different mindset. It's a lot more like designing locks--for prisons full of inmates eager to get out.

    --
    People are never as simple as their stereotypes. This applies equally to Christians, Muslims, and Emacs-lovers.
    1. Re:Checking input is a "pain in the ass"?!? by ubergenius · · Score: 3, Interesting

      Hell, there are some PHP books out there that do this. I have been primarily a PHP developer for a while now (not because it's the only language I know, I just find it to be the fastest and easiest for me over my experiences with Perl, ASP, and *shudder* ColdFusion, but that's personal preference), and I have found that almost ALL the knowledge I learned from books from the beginning of my experience with PHP is virtually useless nowadays (with the exception of the basics, obviously, like printf() and such). I had to relearn the language as I went along, and I didn't develop a proper security sense of the language for quite a while. This is funny considering the books I read for learning other non-web languages, such as C, C++ and Java, were written with a much more solid foundation, and I still find the knowledge learned in those books useful today. Maybe it has something to do with the web language publishers.

      --
      Student Manager - Take control of your education!
  5. Hard for Devs? by CHR1S · · Score: 3, Insightful

    How can it be that hard for web developers to check data before it is submitted? I wouldn't imagine trusting the data that an anonymous user can enter into my website.. so maybe I'm just trained to check data. Of course, I'm also glad I use MySQL with PHP where a simple mysql_real_escape_string can prevent any popular SQL Injection attempt.

    1. Re:Hard for Devs? by Goaway · · Score: 5, Interesting

      You're glad that you use pretty much the only langauge where this is not done automatically for you, but which instead forces you to use a function with a name like mysql_real_escape_string()? And that actually has a similarly-named function without the "_real_" that doesn't do the job right? Just kidding with that other one, here's the real one!

    2. Re:Hard for Devs? by Bogtha · · Score: 3, Informative

      I am curious what language automatically checks your users input for any attempt at SQL Injection.

      You're approaching it with the wrong mindset. A database API shouldn't check for SQL injection attempts, it should encode the input appropriately. Avoiding SQL injection attacks is just a subset of correct operation, as anybody with an Irish surname could tell you.

      As for an example, well with Python's DB-API 2.0, you write code like this:

      cursor.execute("select foo from bar where baz = %s;", (quux,))

      It doesn't matter whether quux has apostrophes, it gets automatically escaped because the API is designed as an interface to input data, not an interface that accepts data that has been specially prepared and cannot be distinguished from data that hasn't been specially prepared.

      --
      Bogtha Bogtha Bogtha
  6. Input checking is a half-assed solution. by cduffy · · Score: 3, Interesting

    Checking input for escape attempts is error-prone. Passing in parameters as bind variables *isn't* error-prone (with regard to blocking SQL injection attacks); makes string quoting completely moot; and can result in a massive performance increase (particularly against Oracle) to boot.

    I continue to be in disbelief that anyone doing professional database work can *not* follow this widely accepted best practice and continue to be employed.

  7. Use PreparedStatements with Java by sbrown123 · · Score: 4, Insightful

    If your webapp is Java based, use PreparedStatements. Never use Statements. PreparedStatements are immune to SQL Injection based attacks since the variable replacements are never interpreted. PreparedStatements are also much, much faster.

    1. Re:Use PreparedStatements with Java by IPFreely · · Score: 3, Informative
      PreparedStatements can be immune to SQL Injection based attacks.

      You should stipulate that you must bind all parameters to placeholders. You could use PreparedStatement the same way as Statement and have the same problem. Bind all parameters, no matter what language you are using.

      --
      There is nothing so silly as other peoples traditions, and nothing so sacred as our own.
    2. Re:Use PreparedStatements with Java by (trb001) · · Score: 4, Informative

      Additionally, make sure you use PreparedStatements/CallableStatements correctly. I've seen people mark up a PreparedStatement like this:

      String SQL = new String("select * from user where username = '" + username + "'");
      PreparedStatement statemnet = connection.prepareStatement(SQL);

      That does *nothing* for you, and is just as insecure. Instead, make sure you use parameterized statements:

      String SQL = new String("select * from user where username = ?");
      CallableStatement cs = connection.prepareCall(SQL, ...);
      cs.setString(1, username);

      Most databases treat the two very differently. In the second case, the database compiles the statement and then compares the username field with your value. In the first, your value is inserted and then compiled, allowing injection.

      --trb

  8. No no No no No no NO by IPFreely · · Score: 5, Informative
    You don't need to escape strings.

    Just don't build your query on the fly.
    Bind ALL parameters to placeholders in a prebuilt query. Binding is an instant kill for any SQL injection attack. It is also much more effecient on many databases.

    --
    There is nothing so silly as other peoples traditions, and nothing so sacred as our own.
    1. Re:No no No no No no NO by wandernotlost · · Score: 4, Insightful

      That bears reiterating. If you are passing user input to a database in anything but a bind variable, you are incompetent. Period. End of story.

      I've seen it so many times. Why do programmers think that it's a good idea to write their own escape routines when every database has a facility for denoting what is variable data and what is not? Unbelievable.

  9. Re:Hooray for PHP! by baadger · · Score: 3, Insightful

    Since when is it the job of the language to protect you from SQL injection? I think you're confusing the language of PHP with the standard libraries it ships with, mysql_*() and co. It's worth noting that PHP *does* support prepared statement's using the 'new' object oriented mysqi interface much like the Perl DBI. This handles the casting of types and escaping of strings for you.

  10. "Careful" vs. "correct" by jc42 · · Score: 4, Insightful

    You have to be very careful ...

    This phrase is a common tipoff to one of the main problems.

    The computer doesn't give a damn how careful you are. If you spend hours carefully crafting a chunk of code that, through your ignorance, has a big security hole, all your care hasn't helped a bit. You have merely produced bad code.

    OTOH, someone with good knowledge of the subject might toss off a 30-second routine that, due to their understanding, is highly secure.

    Carefulness has little to do with doing a good job. Carefully doing it wrong is merely doing it wrong, no matter how careful you are. And doing it right is doing it right, even if you hardly gave it a thought.

    What we need here isn't useless exhortations to "be careful". What we need is education about how code gets into trouble, and training in writing code that doesn't have problems.

    Yeah, I routinely write code that checks input. But if there's some hidden gotcha that I don't know about (typically in some library routine that's not visible to me), I'm quite aware that my careful checking might do little good.

    --
    Those who do study history are doomed to stand helplessly by while everyone else repeats it.
  11. Multi-tiered approach by Billosaur · · Score: 3, Insightful

    First rule of writing CGI: never trust the data! I work in Perl, and when an app is exposed to the outside world, I have to assume someone is going to try and get in through some hole if they can (or worse, will do something stupid that would have a negative affect oon my systems).

    It starts with the web page -- validate input data. I know, I know, anyone can copy your page and rip out the JavaScript validation, but it doesn't hurt to put up a first line of defense. Next, before you actually use the data from the form for anythig validate it separately. In Perl, I have taint mode enabled by default for external apps and I treat all the data I receive as if it were dog crap. I massage it with regexes to make sure it is what it's supposed to be, and then pass it on to be processed. I find the best way to put up a wall is to have the form parameters sent to a validation script, then have the validation script call the script which would run the actual query, throwing back an error message to the user (and sending me a message in the process) if something's not right.

    Data validation is really not that hard, especially if you know exactly what the inout is supposed to be. It gets iffier if the user can put in pretty much anything -- then you have to be a little more paranoid.

    --
    GetOuttaMySpace - The Anti-Social Network
  12. Dynamic 'WHERE' clauses by TheRealBurKaZoiD · · Score: 5, Informative
    I think one thing everyone is overlooking, and I didn't see it mentioned before I posted, is that alot of newbies, and even intermediate SQL developers either can't use stored procedures because they're using some old version of MySQL, or they have problems writing stored procedures that include dynamic WHERE clauses, or they just don't know that you can do that. It's been my miserable privilege to have seen some pretty goddamn bad SQL code in my life, code that was so bad it would make you physically ill, simply because the developer didn't know any better. Remember kids:
    1. Stored Procedures
    2. Parameterized Queries
    3. Learn the SQL-92 Specification (so that you're familar with the language beyond just SELECT, INSERT, UPDATE, and DELETE. There are all kinds of things out there to help you get rid of that dynamic code, like COALESCE, and CASE WHEN, etc.)
    Here's the SQL-92 Specification (pops in a new window)
  13. Re:I'm not very experienced with SQL Security... by LeRandy · · Score: 4, Insightful

    Except, the web is international. So "traditional" alphanumerics are not good enough. Or are you telling me that René should spell his name Rene? (in French, the two are pronounced completely differently - Ren (Rene) and Renay (René)) Or how about non-alphabetic languages like Chinese?

    Many people use non-alphanumerics in their email. I, for example use underscore.

    With the gradual movement of the web to non-latin URLs, too, the need for the acceptance of all printable Unicode in webforms has never been greater.

    And as has often been pointed out, you can reduce the risk of your passwords being susceptible to dictionary attacks by using wierd (or perhaps unprintable) Unicode characters. Web & DB devs should do well to note that - I dislike sites immensely that restrict me to alphanumeric passwords - I'd like to use whatever alphabet I choose, to make my password more secure.

    I'm not saying that input validation is a bad idea. It just needs to accept and validate input in any appropriate language - which for things like "Name" could be anything, even if the user is an anglophone. Some fields, like DOB, or numeric fields are easily validated - others like "Name" would be better cross-checked against a list of banned inputs, and escaped (or use parameters).

  14. Re:Solution for PHP programmers by Bogtha · · Score: 3, Insightful

    Make sure you use strip_tags() on all incoming data that is headed for output on your page (to get rid of cross-site scripting).

    Please don't do this, it's bloody annoying when half your input gets chucked away because you used a special character. I really don't see why that function ever existed, it's a total fuckup and completely unnecessary when things like htmlspecialchars() exist. Encode your user-supplied data properly, don't simply chuck bits of it away.

    --
    Bogtha Bogtha Bogtha
  15. SQL Euphoria by digitaldc · · Score: 4, Funny

    The last time I did a SQL injection, I hallucinated that everything around me was displayed in an orderly array.

    --
    He who knows best knows how little he knows. - Thomas Jefferson
  16. Re:Injection preventation doesn't need input check by julesh · · Score: 3, Informative

    are there web application frameworks which don't support parameterized SQL statements?

    that would be PHP.


    Quit spreading FUD. PHP supports parameterized SQL just as well as any other language I've worked with. See, for example this doc page (search for "Example 2"). Even for databases whose native C APIs don't support the feature (i.e. MySQL), the database abstraction layer PEAR::DB that is distributed with PHP provides emulation.

  17. But ... but ... IT'S CHEAP! by Opportunist · · Score: 3, Interesting

    You get what you pay for. A lot of people already suggested easy solutions to the problem that are just as easy to implement and that would immediately make the problem disappear. So why is it not done?

    Simple: The people who write those insecure databases don't even know that those functions and features exist. Some ages ago, they learned a bit about SQL, maybe did a course about it (so they have a sheet of paper saying "Look, I can do it!") and that's it.

    HR managers tend to go by papers, and by price. Now, who do you think is cheaper to hire? A person with a well rounded education concerning computers, programs and the fallacies, pitfalls and security issues around them, or someone who learned his SQL statements by heart and has no clue what exactly is going down inside the server?

    Sure, both of them will create code that does what the specs say. As long as you only enter data according to spec (which is, interestingly enough, ALL that is checked, even under the SOA). The true quality of code is revealed as soon as you pit something unexpected and malicious against it.

    --
    We used to have a Bill of Rights. Now, with the rights gone, all we have left is the bill.
  18. Perl DBI is pretty good, actually by Anonymous Coward · · Score: 3, Interesting
    Considering you have "completely skipped" Perl, it surprises me to read your comments on how bad its database interface is.

    In fact, Perl's DBI is not only fast, but when used properly (variable substitutions, binding variables, etc) it works extremely well. Also the fact that everytime you change your data source (CSV, XLS, MySQL, SQLite, MSSQL Server, Oracle, PostGres, etc) all your functions don't change. You can always count on:

    my $dbh = DBI->connect(@DSN, \%flags);
    my $sth = $dbh->prepare($sql);
    $sth->execute( @vals );
    while( my $rec = $sth->fetchrow_hashref )
    {
    # Do stuff with $rec
    }
    $sth->finish();
    $dbh->disconnect();
    If you're not doing some kind of column binding or type-casting on your form-derived query arguments, you are always leaving yourself open to sql injection.