Follow Slashdot blog updates by subscribing to our blog RSS feed

 



Forgot your password?
typodupeerror
×
Security Databases IT

Anatomy of a SQL Injection Attack 267

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.
This discussion has been archived. No new comments can be posted.

Anatomy of a SQL Injection Attack

Comments Filter:
  • by ls671 ( 1122017 ) * on Friday February 26, 2010 @06:03AM (#31283036) Homepage

    One should definitely use a persistence library instead of concatenating strings to help mitigate the possibilities of being victim of SQL injections. They are pretty good at it. Hibernate is a widely used one.

     

    • by Splab ( 574204 ) on Friday February 26, 2010 @06:11AM (#31283082)

      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.

      • Comment removed (Score:5, Insightful)

        by account_deleted ( 4530225 ) on Friday February 26, 2010 @07:22AM (#31283374)
        Comment removed based on user account deletion
      • And use of procedures do nothing to prevent SQL injections besides they generally show down your queries. Views also don't help much until you disable thier abaility to be used in insert and updates.
        Use parameterized SQL be in with dynamic SQL, procedures or views.
        • Re: (Score:3, Informative)

          by Splab ( 574204 )

          That really depends on your database flavour. SolidDB which I primarily work with, it is impossible to construct dynamic queries within a procedure.

          Also your claim that procedures only slow down databases is just plain wrong. Databases with procedures where the SQL is immutable will genrally run much faster than your dynamically generated versions. Philippe Bonnet and Dennis Sasha claims (their book, "Database Tuning") that as much as 9/10 of your average query time spend in the database is spend on the que

          • Don't know SolidDB when doing this type of stuff it is in MS-SQL Server and Oracle.
            The statement to use store procedures usually comes from MS-SQL server people who read and continue to repeat information from over a decade ago when MS-SQL server treated procedures and dynamic SQL differently; unfortunatly this has spread into Oracle space. With the query optimizer under MS-SQL Server and Oracle you don't have to worry about using procedures since dynamic SQL is treated the same way, especially if you use
      • Re: (Score:3, Informative)

        by weicco ( 645927 )

        Use procedures/views where possible and never allow dynamically created queries.

        There's an excellent article on dynamic queries and little bit about SQL injections here but it's Sql Server specific so I don't know if it's any good for the Slashdot crowd: http://www.sommarskog.se/dynamic_sql.html [sommarskog.se]

      • by SQLGuru ( 980662 )

        Vendor products tend to shy away from stored procs and views because it ties them to a particular back-end (and can limit sales). Instead of spending time writing database code, they just show it all into the front-end. That doesn't mean they can't take steps to prevent SQL Injection.

    • by AuMatar ( 183847 ) on Friday February 26, 2010 @06:20AM (#31283120)

      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.

      • Re: (Score:2, Informative)

        by Anonymous Coward

        I have found, that if used correctly, hibernate can be quite powerful; you can still run native and database independent HQL queries if you like.

        You can also map your native queries to objects; it is quite easy, and I believe it is same as binding to variables.

        The entity manage also helped me to reduce the amount of queries that I hard code into my DAOs; you can query for objects based on their class and ID (yes, it does support composite IDs).

        Also provides control for optimizations, and will automaticall

      • Yeah, until someone comes at it with a cross-site scripting attack. ^^

      • Re: (Score:3, Insightful)

        by edumacator ( 910819 )

        Note: I even admit in my profile I'm a bad web developer.

        I have JFGI, but most of the stuff I've found leads me to articles I don't fully understand how to implement. I mostly code simple websites for my school and friends that have little db interaction, but I'd rather learn to do it right from the beginning, so if anyone has some links to good articles for beginners to understand how to properly secure their SQL code, I'd be happy for the help.

        • Re: (Score:3, Funny)

          by TheSunborn ( 68004 )

          IT's very simple. Don't use any of the mysql_* functions.

          Use the PDO prepare function (http://dk2.php.net/manual/en/pdo.prepare.php) and remember newer to pass any input you got from the user directly into the string you give to prepare.

          In most cases(99%) the string you give to the prepare function should really be constant and not depend on user input at all.

      • by DrXym ( 126579 )
        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.

        That assumes performance is somebody's number 1 priority. An app might use something like OpenJPA or Hibernate because code correctness, scalability, time to market or portability are more important than performance. Besides, I bet for typical database queries, the performance boost from handwriting SQL vs Hibernate (hql) / OpenJPA (jpql) generating it would be neg

    • by mk_is_here ( 912747 ) on Friday February 26, 2010 @06:27AM (#31283152)

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

      • by moreati ( 119629 )

        Sure you're aware of this, but to make to clear for everyone. Python, Perl and other languages don't require extra libraries to do parameterized queries either. In Python the pattern is

        import db_module
        conn = db_module.connect('user/pass@host')
        curs = conn.cursor()
        curs.execute('select field1, field2 from table1 where field3 = ? and field4 = ?', ('foo', 7.6))
        curs.fetchall()

        Exactly the same number of lines as doing it with string munging, but type safe and zero chance of sql injection.

        • Re: (Score:3, Informative)

          by QuoteMstr ( 55051 )

          Except that Python's DB-API [python.org] is a horrible mess. Depending on what db_module is, you might need to spell your query as:


          1. curs.execute('select field1, field2 from table1 where field3 = ? and field4 = ?', ('foo', 7.6))

          2. curs.execute('select field1, field2 from table1 where field3 = :1 and field4 = :2', ('foo', 7.6))
          3. curs.execute('select field1, field2 from table1 where field3 = :field3 and field4 = :field4', {field3:'foo', field4:7.6})
          4. curs.execute('select field1, field2 from table1 where field3 = %s and field4 = %
    • No need to use a persistency library, but there is no excuse to set up queries by concatenating string. Use wildcards instead! All modern databases support them. executeQuery("update users set score=? where id=?", 95, 113); There is no way anybody could abuse that. The only place where concatenating may be accepatble is for variable ordering: executeQuery("Select * from users order by "+column+(desc ?" desc":"")) And here you better make sure you compare column against the list of valid columns first.
    • by Yaa 101 ( 664725 )

      Nah, just interpret the arguments and stop your program when it goes out of type or range, never use arguments directly.

      • Re: (Score:3, Informative)

        by DavidTC ( 10147 )

        Yeah, all this SQL stuff always confuses me. Partially because I often am in the Joomla framework, which doesn't let you do parameterized queries, and, while I guess you could do stored procedures, I've never seen the need.

        Instead, I simply take all input and make sure it is sane. Is it supposed to be a number? Put an (int) before assigning it out of $_POST. (Now there's a JRequest::getInt that I'm learning to use instead.) Am I putting a string from a user into a database? I use $db->getEscaped(). When

    • Re: (Score:3, Interesting)

      by Simon Brooke ( 45012 )

      One should definitely use a persistence library instead of concatenating strings to help mitigate the possibilities of being victim of SQL injections. They are pretty good at it. Hibernate is a widely used one.

      Speaking as someone who has used both approaches, Hibernate is a lot of overhead for, in many cases, very little gain, and having used it on a number of large projects my team has decided not to use it in future. Of course you must sanitise all values passed in from untrusted clients carefully before they are spliced into any SQL string, but there are a number of frameworks which do this which are far lighter weight than Hibernate.

  • by kyz ( 225372 ) on Friday February 26, 2010 @06:12AM (#31283086) Homepage

    ...for these modern times.

  • Aarghhhh (Score:5, Insightful)

    by boner ( 27505 ) on Friday February 26, 2010 @06:23AM (#31283134)

    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.

    • Re: (Score:3, Insightful)

      by dltaylor ( 7510 )

      Sanity input checking was EASY when it was programmed into the 3270s.

      To make a "Web Programmer", whatever kinda tool (operator) that is do some real work and provide a sane interface is like having just the one chimp pound away at the keyboard and produce Shakespeare immediately.

      • Re:Aarghhhh (Score:5, Insightful)

        by xtracto ( 837672 ) on Friday February 26, 2010 @06:53AM (#31283270) Journal

        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.

        • by vadim_t ( 324782 )

          Please provide an example of how would it work.

          For instance, in Perl I can do a query safely like this:

          my $sth = $dhb->prepare("SELECT * FROM users WHERE user_id = ?");
          $sth->execute($user_id);

          But, I also have a bit like this:

          if ( $filter_owner ) {
          $cmd .= " WHERE owner_id = ?"
          push @args, $filter_owner;
          }

          ...

          my $sth = $dbh->prepare($cmd);
          $sth->execute(@args);

          The second bit is also safe, but it creates a query by concatenation which could be used unsa

          • by WiFiBro ( 784621 )

            It's not such a big deal to filter all user input inorder to prevent SQL injection. It's simply a habit you need to learn and stick to.

            It is more difficult to make a site that allows some people to provide content including html and script, and still prevent evil content to enter your database / pages.

            And it is difficult to enforce a strict password regime because many a client have asked to remove the safety measures for convenience sake. I guess we all know examples of dumb passwords. Like 'coconuts' for

            • by dkf ( 304284 )

              It is more difficult to make a site that allows some people to provide content including html and script, and still prevent evil content to enter your database / pages.

              The issue there is that you're allowing that at all (see CWE-79 [mitre.org]). The solution is to not allow general HTML/script input from non-trusted sources (i.e., they can upload new HTML with sftp, but not through a web form) and instead support some greatly restricted syntax (e.g., bbcode or wikisyntax) that is easy to convert to guaranteed fang-free content. And use a proper templating library for output of content from the database instead of hacking things.

            • Re: (Score:3, Interesting)

              by vadim_t ( 324782 )

              I think you didn't understand my question. The grandparent said: "That is, the only possible way to get or insert data from a database should be the correct one". That excludes any kind of "habit you need to learn and stick to", it must simply be impossible to do otherwise.

              My question is, how do you actually implement a system like that? I'd like an example code of a hypothetical system that would allow me to compose an arbitrary SQL query with variable amounts of selected columns, JOIN and WHERE clauses, e

        • by Kjella ( 173770 )

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

          Libraries do, but they're powerless against string concatenation unless it's impossible to run raw SQL. I think the only thing you could do is deny non-paramter values at all, but it'd make everything a lot more annoying and probably have a performance impact. Like you couldn't say "WHERE is_active = 1" but had to use "WHERE is_active = ?" and bind the value.

      • Re: (Score:3, Insightful)

        Yeah and a bungee cord is easier to hold your front door closed with than a deadbolt or even a standard doorknob but you'd still have to be a fucking moron to use one.
    • Re: (Score:2, Insightful)

      by gmack ( 197796 )

      The problem is that what a programmer does is largely behind the scenes and no one really know what they do anyways. The current crop of "programmers" are web designers who learned a bit of web programming to add to their skill set. 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.

      • Re:Aarghhhh (Score:5, Insightful)

        by ZeroExistenZ ( 721849 ) on Friday February 26, 2010 @08:52AM (#31283792)

        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

        • Re:Aarghhhh (Score:5, Insightful)

          by gmack ( 197796 ) <gmack@noSpAM.innerfire.net> on Friday February 26, 2010 @09:07AM (#31283884) Homepage Journal

          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.

          • Re:Aarghhhh (Score:5, Interesting)

            by ZeroExistenZ ( 721849 ) on Friday February 26, 2010 @09:15AM (#31283942)

            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 have been doing a bit of work with sqlite lately and I am surprised to find that the C api is basically a way to pass in strings containing SQL commands. Now even in C I could imagine an API which allows you to build up queries to do everything SQL does without using commands in text strings.

      With an OO language it should be dead easy.

      • by GvG ( 776789 )
        Sounds like a problem with sqlite, not SQL in general.
        • Sounds like a problem with sqlite, not SQL in general.

          So why can sql code ever be injected on other platforms?

          Instead of execute_command("create table X")

          I want to see create_table("X")

          • Re: (Score:3, Informative)

            by GvG ( 776789 )
            "CREATE TABLE" is probably a bad example, if your web code needs to create a table you're doing something wrong. However, for e.g. an INSERT statement you'd typically use bind variables, something like this:

            long SomeNumericValue;
            char SomeStringValue[SOME_SIZE];

            StatementHandle Statement = Parse("INSERT INTO TableName (Col1, Col2) VALUES (?, ?)");
            BindNumericVar(Statement, 0, &SomeNumericValue); // Binds SomeNumericValue to first "?" in statement
            BindStringVar(Statement, 1, SomeStringValue, SOME_SIZ
    • Re:Aarghhhh (Score:5, Insightful)

      by ZeroExistenZ ( 721849 ) on Friday February 26, 2010 @07:42AM (#31283462)

      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.

      • by Colin Smith ( 2679 ) on Friday February 26, 2010 @09:14AM (#31283920)

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

        I'm up to a multiple of 16 now.

         

      • Re: (Score:3, Insightful)

        by gpuk ( 712102 )

        Ok but seriously what we are talking about here is really not that hard. It should be standard procedure to escape user input before it hits the dbms. I mean all we're talking about is casting strings to floats or integers where numbers are expected and escaping string input. In PHP you'd run the input through intval()/floatval() or mysql_real_escape_string() before you shunt it to the db - it isn't rocket science...

    • Re:Aarghhhh (Score:5, Insightful)

      by l0b0 ( 803611 ) on Friday February 26, 2010 @08:18AM (#31283618) Homepage

      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.

    • by grumbel ( 592662 )

      Whoever, in their right mind thought it was a good idea to expose SQL query inputs on the Web?

      Most people are not doing it because they want to, but because the software they use allows such things to silently happen behind their back. It is a classic case of in-band signaling, you are pumping data through the same pipe as code and when the data isn't properly escaped, things break in bad and unexpected ways. To get rid of this once and for all you need to seperate the pipes, seperate the data and the code and don't allow them to be mixed. LINQ for example does that by moving the query language into

  • by tangent3 ( 449222 ) on Friday February 26, 2010 @06:48AM (#31283236)
  • Use perl. Because the support both in java and php for applying regexes and preparing SQL statements has been late, convoluted and lacking.

    • by Max_W ( 812974 )

      I used Perl in 90's. Then switched over to PHP.

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

      And also the architecture of the language was not suited for web pages. When I saw PHP3, I switched to it immediately and never looked back.

      PHP also has got its minuses (why I cannot create RAR or ZIP archive locked by a password on a website?), but in general it is OK, if one pays attention to what he gets from users.

      I

      • Re: (Score:3, Informative)

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

        Funny, the thing I -like- about Perl is that it is very stable in the sense that variables never get strange values inexplicably. It is a very deterministic environment, set it up and it just works as promised.

        And also the architecture of the language was not suited for web pages. When I saw PHP3, I switched to it immediately and never looked back.

        There are packages that make it very well suited for web pages. OK, you can't really just sprinkle code into your html like you can with php (or maybe you can, but really, why the hell would you want to do that?) but it generates web pages just fine.

        I totally agree with you about sanity checking in

      • by pooh666 ( 624584 ) on Friday February 26, 2010 @09:42AM (#31284216)

        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?

      • Re: (Score:3, Informative)

        by Jimmy King ( 828214 )
        In regards to your experience with inexplicable values in Perl, it sounds like at the time you had issues with some combo of not using the strict pragma and not understanding how Perl works. If you don't fully understand what is going on, it can be confusing. If you're not using strict, it can be an extra confusing clusterfuck. I think there were a lot of tutorials and such in the mid 90s not using strict.
      • by ztransform ( 929641 ) on Friday February 26, 2010 @11:41AM (#31285534)

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

    • Although there might be lots of reasons to use Perl rather than Java (and vice-versa), security against SQL injections is not one of them. Java JDBC has been supporting wildcards (parameters) [sun.com] (using statement.setObject(pos,value);) since day one.
      • by pooh666 ( 624584 )
        Yeah totally agree on that. DBI and JDBC have a great deal in common, but I still think JDBC is beautiful. With either you have to work fairly hard to be an idiot, or else just not bother to learn the whole of their specs. I don't think that should take more than a couple of weeks they just make *sense*
    • by pooh666 ( 624584 )
      Support for binding params in PHP has been there a LONG LONG time(5 years maybe more?), it is the culture that tends not to use it. I discovered it as a kind of odd hack sort of thing, not commonly documented when it first came out. One reason is it had to be adopted, it wasn't a part of PHP to begin with. WHY PHP didn't have it to BEGIN with, that is my issue with PHP. To hold true to its credo, I would think that binding params would be seemless and transparent with no need for a developer to make a choic
  • by mcalwell ( 669361 ) on Friday February 26, 2010 @07:33AM (#31283432) Homepage

    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

    • by will_die ( 586523 ) on Friday February 26, 2010 @08:11AM (#31283580) Homepage
      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.
      • Re: (Score:2, Informative)

        by mcalwell ( 669361 )

        The user can see the table structure, perhaps the view definition, but not the data they have no rights to.

        You deny select on the table, and grant access to the view. The view contains a constraint that forces the view only to return the data the connecting user is allowed to see.

        I have implemented this in Postgres/PHP.

        You have a group role that has read access to the public tables (eg products). The webserver runs, by default, at this user level.

        When a user logs in, they reconnect to the database. They are

        • by Bengie ( 1121981 )

          how does your design method apply to blog/twitter style web sites where everyone about inserts to tables and about everyone reads everyone else inserts?

          Your view method may work well in your Postgres DB setup, but in the MS world, a view causes a full table scan and cannot be indexed unless your fork out $25k per socket for enterprise ed. using views sounds bad to me.

    • by Eivind ( 15695 )

      Uhm. No.

      Well, yes, but it don't help much. True, the web-sql-user should only have access to information it needs to see. But that doesn't help you at all against the fact that a single web-user shouldn't nessecarily be able to see everything and do everything the web-server as such can see and do.

      To make a concrete example, if you're making a internet-bank, then the web-frontend need to be able to see the account-balance and movements of everyone who has internet-banking, it also needs to be able to put in

      • You're right -- because it's SQL, which has assumptions about how it's used.

        LDAP, on the other hand, you can set up to bind as the individual user, and you adjust which attributes a user is allowed to see or modify in their own entry, and which entries they can see in other entries.

        So, part of the solution is using the correct data store for the situation, and SQL isn't always it. (I haven't played with any of the "NoSQL" stuff yet, but much of the behaviour with replication and and flexibility of storage

      • by Qzukk ( 229616 )

        The idea is that instead of creating a "users" table and filling it with your users, the user is created as a database user, and their username and password is handed straight to the database during the connection process. If it connects, the user had a valid username/password. If it doesn't connect, the user didn't. If you have a million users, then your database server would need to be able to handle having a million different users each with different levels of access on different tables/rows/columns/

    • by ArsenneLupin ( 766289 ) on Friday February 26, 2010 @08:43AM (#31283750)

      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.

    • Re: (Score:2, Insightful)

      by Anonymous Coward

      That is assuming that each web user has their own database account, and more importantly, their own set of views; this introduces a couple of problems.

      1. No SQL database engine I'm aware of supports "generic views" taking the user as a parameter in a reasonable way. If they did, you might have a case, but the
      2. One db-user per web-user? If your web-application has more than a few hundred users, your DBA will kill you for this.
      3. Most web app servers use connection pooling; some DB engines support "switching

  • by RaigetheFury ( 1000827 ) on Friday February 26, 2010 @08:43AM (#31283754)

    If you look for a while you'll find them. The developers replied to me with "It's perfectly fine". While it seems they do parse this information isn't that screaming "Exploit me!"

  • by h00manist ( 800926 ) on Friday February 26, 2010 @08:45AM (#31283760) Journal
    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.
  • by TaggartAleslayer ( 840739 ) on Friday February 26, 2010 @08:58AM (#31283828)

    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.

    • Re: (Score:3, Interesting)

      by asdf7890 ( 1518587 )
      One to add to you list if we stray beyond just SQL injection and consider other attack vectors too:

      5. Output matters. Check data from the layer below, ensuring any characters that might carry unintended meaning but need to be in the data are escaped as required.

      Always check the data on the way out as well as on the way in, in case something malicious got in by any means (due to a failure in steps 1 through 4, or direct database access by other means). This is implied by your supplementary text, but I thin
    • Re: (Score:3, Interesting)

      by DarkOx ( 621550 )

      I am with you on thee through 4, and you probably should or are doing 1 because you want to be able to help the user put the right information in fields, check onblur an give some useful feedback but spending allot of time on careful input validation at the client level with web is pretty pointless. Anyone doing something malicious does not have to use your interface at all.

  • by JRHelgeson ( 576325 ) on Friday February 26, 2010 @09:28AM (#31284060) Homepage Journal

    I wanted it to be short, easy for management to understand (even non-technical). Definitely worth watching, IMHO.

    http://www.youtube.com/watch?v=jMQ2wdOmMIA [youtube.com]

  • by joshuao3 ( 776721 ) on Friday February 26, 2010 @10:30AM (#31284732) Homepage
    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...
    • Re: (Score:3, Insightful)

      by cerberusss ( 660701 )

      You're right.

      On the other hand, Google hides nothing. Just google for 'client login' or 'customer login' plus maybe some random word such as 'enterprise', or 'sales' or what have you.

      I can guarantee you that in the first fifty results, you are in. Just fill in as the username:

      ' or 'a'!='

  • by Trailer Trash ( 60756 ) on Friday February 26, 2010 @11:09AM (#31285150) Homepage

    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.

He has not acquired a fortune; the fortune has acquired him. -- Bion

Working...