Slashdot Mirror


Anatomy of a SQL Injection Attack

Trailrunner7 writes "SQL injection has become perhaps the most widely used technique for compromising Web applications, thanks to both its relative simplicity and high success rate. It's not often that outsiders get a look at the way these attacks work, but a well-known researcher is providing just that. Rafal Los showed a skeptical group of executives just how quickly he could compromise one of their sites using SQL injection, and in the process found that the site had already been hacked and was serving the Zeus Trojan to visitors." Los's original blog post has more and better illustrations, too.

35 of 267 comments (clear)

  1. Re:Use a persistence library by Splab · · Score: 5, Informative

    One should use positional/named bindings and let the driver handle escape sequences, make sure the Web user only has access to what is needed, rather than running everything as root. Use procedures/views where possible and never allow dynamically created queries.

  2. A cautionary tale' OR 1=1 by kyz · · Score: 4, Funny

    ...for these modern times.

    --
    Does my bum look big in this?
  3. Re:Use a persistence library by AuMatar · · Score: 4, Insightful

    Persistence is just a bad idea, it hides the real performance issues of how databases work, and limits how you can easily manipulate the data. A better idea is just to always use bind variables. Problem solved.

    --
    I still have more fans than freaks. WTF is wrong with you people?
  4. Aarghhhh by boner · · Score: 5, Insightful

    I for one am sick and tired of these types of attack. Whoever, in their right mind thought it was a good idea to expose SQL query inputs on the Web?

    Ever heard of input sanity checking? It was very popular in the say, 60's, 70's and 80's. It means you reject fields you don't expect to be there, instead of arbitrarily passing them onto the backend database. These types of attacks illustrate what is wrong with web security: developer convenience trumps common sense everytime...

    Next time we see Ballmer hopping along shouting developers, maybe could he please add the words 'SECURITY BY DESIGN', please, pretty please?

    SQL injection attacks are asinine because they are so prevalent, easy for the hackers AND easy to fix. We should name and shame every site, and every web-application stack that allows these attacks to take place.

    nuf said.

    1. Re:Aarghhhh by xtracto · · Score: 5, Insightful

      Then what needs to be done is make the libraries have this security implemented *by design*.

      That is, the only possible way to get or insert data from a database should be the correct one. Security should be an enforced feature of the library (PHP, Java, etc).

      It is kind of like "accessibility", it is available there (at least say, in Java and Flash) but *because* it is not compulsory, very few programmers implement it.

      --
      Ubuntu is an African word meaning 'I can't configure Debian'
    2. Re:Aarghhhh by ZeroExistenZ · · Score: 4, Insightful

      developer convenience trumps common sense everytime

      You're clearly not writing software for a living...

      There are a few things more important than security: time to delivery and budget.

      Colour this with unrealistic expecations and you get situations like these:
      "What's your estimate?" *honest assessment* "Ok, so if you work harder, you can do it in less time right? (all programmers are soo lazy.. I read that somewhere)"
      "Well, it depends on what I encounter while bringing this analysis into reality..."
      "Just make it work so we have something to show for by date xx-xx-xxxx"
      ^

      Even in large coorperations with large budgets, the smaller one's usually are more idealistic but are on a tight budget.

      Because alot of developers are struggling with getting the "damn thing to work", and there are so many shifts in deadlines, "security", as a seperate item, often is neglected because people are relieved they're having something "up and running".

      I do agree though, that initial design and architecture should be welldefined and requires extra attention with security measures and considerations built-in, whereas many developers are running around with such a sense of urgency and pressure they just want to get to "coding thing" instead of thinking first what and how they'll code it, yet it doesn't change or improve the environment and pressure which results in these things.

      --
      I think we can keep recursing like this until someone returns 1
    3. Re:Aarghhhh by l0b0 · · Score: 4, Insightful

      Ever heard of input sanity checking?

      Yep, it's that enormously annoying thing that almost no developers get right. They filter out emails that contain + or -, names with accents, and zip codes / phone numbers for other countries. You should never reject a value from a user: If it looks wrong to you, suggest that they change it, but for f's sake put it in your DB. And don't tell me about quotes or backspaces - RTFM or Google it.

    4. Re:Aarghhhh by ZeroExistenZ · · Score: 5, Insightful

      They don't understand any of the implications of what they are doing and only know how to take results from a database and display it in a nice looking web page.

      Well, there are many like that, and in essence that's webdevelopment, right?

      Consider an application where you can control the logical flow, you need to know your basic language and your GUI's behave the way you expect. Done.

      Now, for being a webdeveloper you need to know HTML, XHTML, CSS, JavaScript, PHP, MySQL, MS SQL, .NET (preferably working knowledge of 3.5 and playing around with WCF/WPF), AJAX-concepts and implementation, various toolkits and libraries in place, XML, XSLT, JSON, WebServices, COM+ interaction, and need strong afinity around security concepts and be aware of injection methods, sniffing, current state of hashing algorithms, make sense of server technology and scaling (if your server is in fumes, you need to kickstart it) so that extends to IIS, Apache. If you're going more the el cheapo/opensource approach, it's mostly a box running Apache, MySQL and PHP (for which you need to subtle differences through different releases) often Mediawiki too, so you'll need to find your way around a Linux station and often are deploying and setting up such a box ad hoc as well... It adds up quite fast if you've consulted a bit and in each environment encounter different setups, architectures and approaches.

      "Web development" has gotten pretty involving to get the pretty display, for which there isn't really a good methodology anymore as the web has evolved in such a way the "hypertext markup" combined with "style sheets" sortof feels dated. (that's why you have XAML, Flash, Flex, .. trying to solve the problem adding to complexity).

      I do agree; webdev is pulling data and storing data while showing it in a pretty way, modify the page based on that and have a fluid user experience. However, those lasts are pretty difficult if there's a clear idea about the result and you need to depend on external parties (IE bugs, FF bugs, toolkits bugs, API frameworks with bugs, ...) to get your thing done.

      I think webdevs are the gluers between all these frameworks and layers, there's maybe not much writing logic, but trying to make sense of the mess and compiling and stringing very specific technologies (legacy or hyped new) together in order to have a functional and pleasing result.

      It's odd to me that there's a general looking down on webdevelopers, not just from non-techies, but also from techies whoe feel their work is "so much more significant" because "they have to think more and aren't a code monkey", yet wouldn't survive in an unstructured choatic environment where you have to think on your feet and act quick when things fall out and can't have flow in a straight line (say "I'll write function x and y today, and nobody will bother me all day while I do so") but are constantly interrupted or required to take some action, asap and efficient, while you're juggling a dosen projects, maintaining another handful and are trying to please clients. Plus ofcourse, get new projects worked out, writing analyses and following up/leading communication of 3rd parties in order "to hook up that webservice the client wanted to implement" and god knows what.

      But yes, it's just displaying stuff on a page, right? I can show you complex systems (webbased stockmarket software fe.) which makes your head spin and cry in desperation (I've seen some break up and give up on the legacy mess), yet it's all "just showing data in pretty boxes" and "pulling it from a datasource" (stock market floor) and "saving it" (processing orders with business rules and automating processing of orders all within legal limitations) all to meticious specification of the clients, all with their own perculior wishes?

      "But they are the lazy programmers and we don't know what the hell they are doing, but they have no concept of the implications of their work, sir.". Put

      --
      I think we can keep recursing like this until someone returns 1
    5. Re:Aarghhhh by gmack · · Score: 4, Insightful

      The problem is not the web devs it's the managers who didn't realize they need both a programmer and a webdev.

      They are very different functions. If you have only webdevs you tend towards the sort of security mess we are seeing here. If you have only programmers you end up with a site that is butt ugly and useless from a user interface perspective.

      Your stock market display software is a good example of a case where the entire project will fall apart unless you have programmers who can move the data efficiently and securely and then some skilled webdevs to handle the user interface work.

    6. Re:Aarghhhh by ZeroExistenZ · · Score: 4, Interesting

      If you have only webdevs you tend towards the sort of security mess we are seeing here. If you have only programmers you end up with a site that is butt ugly and useless from a user interface perspective.

      This is a very valid point, yet "programmer" and "webdev" is often seen as very closely related with a blurry line; in my experience a "webdev" is a programmer who's proficient with webtechnologies, but usually has a blind spot for design. (or the inability to be visually creative and create pretty interfaces, but might be brilliant with logical creativy and finding solutions). The agencies I've worked for had the design part done by "designers" who drew a few designs, shook hands on one and had a "webdev" implement it. They never touched the websites, just sliced up images when they were done.

      Maybe my strong reaction was rather based on the difference of concept we have from "webdev" and "programmer", for me they're very closely related wheras you seem to see the "webdev" as a designer with a course of HTML or something alike :)

      --
      I think we can keep recursing like this until someone returns 1
  5. Re:Use a persistence library by mk_is_here · · Score: 5, Insightful

    A more simple way is to use a parametrized statement. No extra libraries if you are using Java, .NET, or PHP5.

  6. Obligatory xkcd by tangent3 · · Score: 4, Funny
    1. Re:Obligatory xkcd by Inda · · Score: 4, Funny

      Oh, oh, oh, please let it be Bobby DropTables, please, please.

      --
      This post contains benzene, nitrosamines, formaldehyde and hydrogen cyanide.
  7. Re:Use a persistence library by SpazmodeusG · · Score: 3, Informative

    You still need bind variables mentioned by the gp if using HQL.
    http://www.owasp.org/index.php/Interpreter_Injection#ORM_Injection

  8. Comment removed by account_deleted · · Score: 4, Insightful

    Comment removed based on user account deletion

  9. SQL Injections SHOULD NEVER WORK by mcalwell · · Score: 5, Insightful

    If your code is running at the correct privilege level, SQL injections should be completely irrelevant.

    If your user is connecting with the correct credentials, they should only be able to see public data and their own records, nothing else.

    This is implemented by using views in the database, and only allowing users rights to views, not tables.

    If your website user is connecting with credentials that allow a crafted SQL query to see priveleged data, you have set everything up wrong

    If you have set everything up correctly, even a successful SQL injection will only return data the user can see

    1. Re:SQL Injections SHOULD NEVER WORK by will_die · · Score: 3, Interesting

      Couple of problems with this.
      If the attacker can still input SQL commands they can display the views,tables, procedures,etc that the account accessing the database can access. Besides most current databases allow you to use views for update and insert.
      That means you need to implement a solution using multiple database credentials that way they attempt to access something the account used to access the database has the least permissions needed for the specific page and the rights of that current user. There are very few tools that understand using multiple database credentials and those that do are expensive and a pain, been a few years so maybe they are better.
      So that leaves you having to write your own code and adding alot of code to handle the switching of database credentials or having different area, including duplicate pages, that handle the different database credentials.

    2. Re:SQL Injections SHOULD NEVER WORK by ArsenneLupin · · Score: 3, Interesting

      If your code is running at the correct privilege level, SQL injections should be completely irrelevant.

      True, if you run your web app at the correct privilige level, there is no way an SQL injection can be used to root the machine.

      But it can still be used to corrupt the application itself, which is often more valuable that the system.

      Example: a gaming application that wants to store a score per user. Even if the app uses a separate DB user per game user, and even if the DB only allows the user himself to update his score, this would not be good enough, because SQL injection might allow a player to assign himself an arbitrary score of his chosing.

  10. Re:Use a persistence library by Archon-X · · Score: 3, Interesting

    My only issue w/ stored procedures comes from an abstraction quarrel:
    Where should the logic be? The code? The DB?
    What if I need to debug, what if someone else needs to debug?

    I've seen way too many nasty examples of shit going awry in databases, because someone has crazy triggers or stored procedures in place without documentation..

  11. Re:Use a persistence library by Splab · · Score: 3, Interesting

    For PHP + *SQL, use DBO, first proper interface for databases in PHP IMO.

    Where I work there is no interface to the database other than stored procedures, yes writing programs takes longer and requires one of the DBAs to make the procedure, however, we have never had a single incident of some cowboy programmer forgetting to add a where clause to an update/delete, nor some insane environment where random pageviews clobbers the databases.

  12. Re:Use a persistence library by Splab · · Score: 3, Interesting

    The logic for the dataset should be in the database where it belongs.

    Crazy trigger/Crazy procedure problems are the same as every where else, if it's undocumented the code is hard to maintain.

    Not sure what your problem with debugging a procedure is, most databases has interfaces for tracing procedures, I actually find SolidDb procedure trace to be preferred over normal print statements in .

  13. Re:limit the length and content of what you accept by pedestrian+crossing · · Score: 4, Insightful

    Unless you are trying to put Chris O'Connor into your database, and his name must be spelled correctly...

    --
    A house divided against itself cannot stand.
  14. Slash Dot Virus Sequel Injected in You by h00manist · · Score: 4, Funny

    You can't stop reading slashdot. Full of nonsensensical arguments, but you read on, your brain oozes, your eyes are red, dry and hurt. Still, you read on, and participate in the debate. You don't recognize your odd behavior. There's a sequel reply injected into your brain. It's a slash dot sequel brain virus injection. There's no cleaning utility, you will need to reformat your brain.

    --
    Build your own energy sources from scratch. http://otherpower.com/
  15. It is a sad world we live in. by TaggartAleslayer · · Score: 5, Informative

    I go through this all of the time. Though I call it laziness, it is actually a combination of ignorance, indignation, and laziness.

    Here is a very, very, very simple and very, very, very standard way of keeping SQL injections out. Validate everything at every level. There you go. Done.

    1) Client side matters. Check input, validate it and pass it through to the application layer.
    2) Application layer matters. Check variable, strictly type it, validate it and pass it through to your data layer.
    3) Data layer matters. Check argument against strict type, validate it, paramaterize it, and pass it off to the database.
    4) Database matters. Check paramater against strict type, validate it, and run it.

    You run into problems when someone only follows any one of the steps above. You could handle it with a medium level of confidence in areas 2 and 3 (and if you're asking why not 1 and 4, go sit in the corner while the grown-ups talk), but good practice for keeping it clean is validate it at every layer. That doesn't mean every time you touch the information you have to recheck the input, but every time it moves from one core area of the platform to another or hits an area it could be compromised, you do.

    As I said above, the only reason for not following 1-4 is laziness, ignorance, or indignation. SQL injections aren't hard to keep out.

    We're in an age where web development IS enterprise level programming and developers need to treat it as such.

    There, I just saved your organization millions of dollars. Go get a raise on my behalf or something.

  16. didn't you ever watch startrek? by Colin+Smith · · Score: 4, Insightful

    learn from Scotty. always double your estimates... Especially when they ask for an honest estimate.

    I'm up to a multiple of 16 now.

     

    --
    Deleted
  17. Re:Lemme be the first to say by pooh666 · · Score: 3, Funny

    I remember that Perl was not too good for web programming. It was unstable in a sense that variables sometimes got strange values inexplicably.

    Perhaps less(or more) drinking would help?

  18. Re:Use a persistence library by SQLGuru · · Score: 3, Insightful

    You define it up front in the project and stick to it.

    Look at the skill set of the team. If you don't have a strong database guy, your logic will probably be in the app layer.
    If the database is shared between apps/services/etc., then more logic needs to be enforced there. Data integrity triggers to prevent bad data from getting into the database from any side. Access to tables going through stored procs.

    If you have to debug, you work through it regardless of where it is. Just like testing anything with multiple layers (gui, app layer, remote web services, database code, etc.), you test each layer individually but using the same call as a collective test. Eventually, you will isolate the layer with the issue. Dig in deep and root out the problem.

  19. Re:Use a persistence library by aldousd666 · · Score: 3, Insightful

    Stored procedures are not the cure-all for everything. They are good if you have only a few ways of doing things, but it's ridiculous to write a different stored proc for every single column that you want to sort by. Its stupid to write a new stored proc for every possible way of varying the query. Yes they do guaruntee some kind of type checking and parsing compliance, but you can do that with a prepared statement as well. Dynamic SQL is a lot more flexible, especially when the number of stored procs would be combinatorial in number. You just have to be smart, and know what to do. Try converting your values to the types you want. Make your own parser if there is no other way, but for example, in the .NET world you can use ADO.NET with the typed parameters on text queries and it's every bit as safe and efficient as a stored proc. I'm not sure how well or not this translates to PHP and MySQL but I think the db module has most of the same stuff, if I recall correctly.

    --
    Speak for yourself.
  20. The author should be more careful... by joshuao3 · · Score: 3, Insightful

    Simply searching on google fo the tail end of the URL shows exactly which sites are vulnerable and the provider of the sites... Now the entire database of restaurants is open to attack. If the author was trying to teach their client a lesson or two (or 50)--well, good job...

    --
    Monitor bandwidth usage on IIS6 in real-time: http://www.waetech.com/services/iisbm/
  21. Re:Use a persistence library by ShannaraFan · · Score: 5, Insightful

    Putting the logic in stored procedures allows ME, the DBA, the guy with the SQL know-how, to tune the gawd-awful query that you, the pointy-clicky .NET monkey, is using to bring my server to its knees. NINE left joins again subqueries, each with a GROUP BY, then another GROUP BY applied over the query as a whole? WTF are you thinking? Fixing your code requires a new build & deployment cycle. Fixing a stored proc, I can do that with a simple DROP/CREATE script.

    Yes, I'm bitter. I'm surrounded by pointy-clicky types who insist on procedural thinking when writing queries. Set theory? What's that?

  22. This lovely programmer has sold his code around by Trailer+Trash · · Score: 4, Insightful

    Took me 2 minutes with Google to find other sites that are apparently using the same crappy code with the same vulnerabilities. "inurl:" does wonders.

  23. Re:Lemme be the first to say by ztransform · · Score: 3, Informative

    It was unstable in a sense that variables sometimes got strange values inexplicably.

    Perl doesn't stop you from programming like a rodeo clown (for those who don't even qualify as cowboys...).

    If you're going to make zealous use of globals and then use mod_perl you will get hurt.

    Universities teach about something called "coupling". Every professional programmer will talk about something called "use strict". If either of these concepts are too difficult you're better off with a language that does its best to help you from yourself (but be aware Java threads are not going to stop any determined doofus from causing real pain).

  24. Re:Use a persistence library by CastrTroy · · Score: 3, Informative
    It's ok to create dynamic queries as long as you aren't generating those based on user content. Doing the following (VB/Pseudocode) is perfectly fine.

    sql = "SELECT item FROM table WHERE keyword IN ("
    FirstValue = True
    ParamNo = 1

    For each Value in MyValueList
    If Not FirstValue Then
    sql &= ","
    Else
    FirstValue = False
    End If

    sql &= "@Param_" & i
    cmd.Parameters.AddWithValue("@Param_" & i,Value)
    ParamNo += 1
    Next

    sql &= ")"

    Since there is no user input used in generating the query, you can never have an SQL inection attack, and still use dynamic queries. There are ways to do dynamic queries, without opening yourself up to attacks.

    --

    Anthropic principle: We see the universe the way it is because if it were different we would not be here to see it.
  25. Re:Use a persistence library by jlechem · · Score: 3, Interesting

    I was going to MOD this up as super informative but I had to pipe in myself ;)

    Having worked in a small startup, a major Fortune 500, and in between companies this kind of thing is by far the best approach over the long run. The places where the DB/Code guys are separate always end up with a better product. Simply because it allows people who excel at something to really apply that benefit to what their doing. I love writing code but hate writing SQL and maintaining databases. So I tend to focus on the code and the DB stuff gets done but pretty half assed. Now people could say you should do it all equally well but in real life that never happens. Let the database go do his thing and the programmer guy do his thing. Get them talking together and your product will benefit greatly.

    Also when logic is in procs, views, whatever you don't need to redeploy anything to achieve results. Simply change the database and it's done.

    --
    Hold up, wait a minute, let me put some pimpin in it
  26. Re:Use a persistence library by Qzukk · · Score: 3, Informative

    What if "item"s came from the users in the first place? Most databases don't return the strings pre-escaped for reuse in the database.

    Personally, web programming is where "Hungarian Notation" style variable names shine: I have htVariableName, dbVariableName and the original inVariableName, and it's blindingly obvious when I'm using the wrongly-escaped string in the wrong place or re-escaping something I already escaped.

    --
    If I have been able to see further than others, it is because I bought a pair of binoculars.