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.
Use a persistence library (Score:3, Informative)
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.
Re:Use a persistence library (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.
Comment removed (Score:5, Insightful)
Re: (Score:2)
Use parameterized SQL be in with dynamic SQL, procedures or views.
Re: (Score:3, Informative)
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
Re: (Score:2)
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)
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]
Re: (Score:2)
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.
Re: (Score:2, Insightful)
Using stored procedures is harder than just creating the SQL query.
You need to know even more about the DB.
Even it's harder if you have to get the DB guy to do stuff for you.
Yes you can run your own DB in development, but in the production environment, you may depend someone else (DBA) to set up all those stored procedures so that stuff works.
In contrast on sane programming languages using explicit SQL queries with "bind variables/parameters
Re:Use a persistence library (Score:4, 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.
Re: (Score:2)
PDO has been around for years, and offers standardized escaping and binding for all the major db platforms. If you're stuck with an "old PHP ways" host, they probably are still using PHP4 and have register_globals set to on - IOW, time to move to a modern host. Just like you wouldn't stick with a Java host only offering 1.3 or 1.4, it's time to vote with your wallet and move to modern hosting operations.
Re:Use a persistence library (Score:4, Insightful)
Re: (Score:3, Informative)
??
You can write stored procedures that take variables, for instance..one that will change the ORDER BY clause to what you want. Also, it isn't much of a problem to overload stored procedures...same name, but behaves differently by the number or types of parameters you call it with.
Re:Use a persistence library (Score:4, 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..
Re:Use a persistence library (Score:4, 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 .
Re:Use a persistence library (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?
Re:Use a persistence library (Score:4, 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.
Re: (Score:3, Interesting)
Re: (Score:3, Insightful)
This includes coders who insist Hibernate is the be all and end all of database interfaces. 'I don't need to know SQL well because I have just abstracted that whole icky database thingy.' Meanwhile you get both shit code (because they are all silver bullet use the latest technology and agile technobabble to write factory and strategy patterns everywh
Re: (Score:3, Insightful)
No, the logic belongs to the app. The database is there to store data, how we are going to use it is app-dependent.
Be careful with generalizations. It's a matter of requirements not some universal law.
If it makes sense to put it in the app and you don't particularly care about performance or security (because you trust your users) then put it in the app. I would have a problem with letting an untrusted user execute direct queries against my database though - the app has to log in somehow to the database with a username and password, and it's never hard to extract the username and password, and so suddenly a malicious us
Re:Use a persistence library (Score:4, 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.
Re:Use a persistence library (Score:4, Informative)
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.
Re:Use a persistence library (Score:4, 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.
Re: (Score:3)
I cringe at this particular example of boilerplate code, b/c I have seen it so often lately and it's such an obvious choice for refactoring. If your language of choice has string join operator, the above code can be expressed in two lines:
items = list.join(", ")
sql = "SELECT item FROM table WHERE keyword IN (" + items + ")"
Much more readable with a better chance to spot the bug in your code: What happens if list is empty?
IHMO, better yet is to put the values in a temporary table using a batch insert and th
Re:Use a persistence library (Score:5, 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.
Re: (Score:2, Informative)
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
Re:Use a persistence library (Score:4, Informative)
http://www.owasp.org/index.php/Interpreter_Injection#ORM_Injection [owasp.org]
Re: (Score:2)
Yeah, until someone comes at it with a cross-site scripting attack. ^^
Re: (Score:3, Insightful)
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)
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.
Re: (Score:2)
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
Re:Use a persistence library (Score:5, Insightful)
A more simple way is to use a parametrized statement [wikipedia.org]. No extra libraries if you are using Java, .NET, or PHP5.
Re: (Score:2)
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)
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:
curs.execute('select field1, field2 from table1 where field3 = ? and field4 = ?', ('foo', 7.6))
curs.execute('select field1, field2 from table1 where field3 =
Re: (Score:3, Insightful)
What about "The code was written and deployed when PHP3 was new and noone will give me any money for fixing it and probably blame me if anything breaks."?
I have written a lot of web stuff from 1995-2000 (first in C using Tom Boutell's cgic, then in perl, then in PHP) and yes, quite a bit is still in use today. What should I do about all those old vulnerabilities lying around (keep in mind that I mostly quit web development in 2001)?
Re: (Score:2)
Re: (Score:2)
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)
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)
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.
A cautionary tale' OR 1=1 (Score:5, Funny)
...for these modern times.
Aarghhhh (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.
Re: (Score:3, Insightful)
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)
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.
Re: (Score:2)
Please provide an example of how would it work.
For instance, in Perl I can do a query safely like this:
But, I also have a bit like this:
The second bit is also safe, but it creates a query by concatenation which could be used unsa
Re: (Score:2)
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
Re: (Score:2)
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)
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
Re: (Score:2)
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:2)
Is there really a need for "interesting solutions" in yet another 3-layer web app? It's a serious question as I don't do this kind of work. But it seems to me that this stuff is already so well known that production sites shouldn't be looking for new interesting (and thus untested) ways of hacking together queries. Forcing programmers to do things "the right way" for established designs and purposes doesn't really seem like a problem to me, though I'm sure it takes some of the fun out of it.
Re: (Score:3, Insightful)
Re: (Score:2, Insightful)
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)
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)
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)
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 :)
SQL is the problem, really. (Score:2)
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.
Re: (Score:2)
Re: (Score:2)
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)
long SomeNumericValue;
char SomeStringValue[SOME_SIZE];
StatementHandle Statement = Parse("INSERT INTO TableName (Col1, Col2) VALUES (?, ?)");
BindNumericVar(Statement, 0, &SomeNumericValue);
BindStringVar(Statement, 1, SomeStringValue, SOME_SIZ
Re:Aarghhhh (Score:5, Insightful)
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.
didn't you ever watch startrek? (Score:5, 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.
Re: (Score:3, Insightful)
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)
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.
Re: (Score:3, Insightful)
The counterpart to accepting any input is sanitizing any output. It's really very easy if you have centralized DB fetching (and you should).
Re: (Score:3, Insightful)
Heh, no. Finished MSc in CS in 2004, worked in large companies + CERN since then, and doing a PhD now. And yes, I believe it's easy and desirable to accept any input. Learn to escape and unescape (or parametrization when possible), along with the basics of Unicode, and your users will love your software even more.
Re: (Score:2)
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
Obligatory xkcd (Score:4, Funny)
http://xkcd.com/327/ [xkcd.com]
Re:Obligatory xkcd (Score:5, Funny)
Lemme be the first to say (Score:2)
Use perl. Because the support both in java and php for applying regexes and preparing SQL statements has been late, convoluted and lacking.
Re: (Score:2)
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
Re:Lemme be the first to say (Score:4, 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?
Re: (Score:3, Informative)
Re:Lemme be the first to say (Score:4, 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).
Re: (Score:2)
Re: (Score:2)
Re: (Score:2)
SQL Injections SHOULD NEVER WORK (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
Re:SQL Injections SHOULD NEVER WORK (Score:4, Interesting)
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)
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
Re: (Score:2)
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.
Re: (Score:2)
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
SQL is not always the answer ... (Score:2)
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
Re: (Score:2)
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/
Re:SQL Injections SHOULD NEVER WORK (Score:4, 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.
Re: (Score:2, Insightful)
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
USDA likes to put SQL strings in their URLS (Score:3, Informative)
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!"
Slash Dot Virus Sequel Injected in You (Score:5, Funny)
Re: (Score:2)
you will need to reformat your brain.
Does this mean I have to download the internet again?
It is a sad world we live in. (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.
Re: (Score:3, Interesting)
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)
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.
I produced a video on SQL injections - (Score:3, Informative)
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]
Re: (Score:2)
Little Bobby Tables:
http://xkcd.com/327/ [xkcd.com]
The author should be more careful... (Score:3, Insightful)
Re: (Score:3, Insightful)
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'!='
This lovely programmer has sold his code around (Score:5, 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.
Re:limit the length and content of what you accept (Score:5, Insightful)
Re: (Score:3, Interesting)
I agree. Just like any regular program, input must be reduced to an EXPECTED set of values. Bounds checking must be performed. Anything outside that strict set of values must be rejected offhand and an error message provided. This is programming 101.
Unfortunately when HTML, PHP and SQL went "mainstream", these core programming concepts didn't get passed along. Frankly I say let "evolution" take careof/teach sloppy web developers - the smarter ones will have backups and be able to fix their problems. What re
Re: (Score:3, Insightful)
I agree. Just like any regular program, input must be reduced to an EXPECTED set of values.
This is a good advice, but not when applied to this example. You do not want to restrict what users type for their name in any way (as a bunch of replies already point out, GP has missed a few obvious things... and then, what if I'm Russian or Japanese, and want to use my original alphabet?). All that needs to be done is properly escaping any unsafe chars (and for those, the set is known and well-defined); leave everything else be.
Re: (Score:3, Insightful)
Quick answer: A lot.
Long answer:
You are mistaking escaping with sanitising. These are two very different things.
Sanitising should occur as soon as possible, before the values are used. It involves validating and optionally filtering _each_ field, so that you know the data you are getting is exactly what you are expecting it to be. This is a lot of work, which is why a lot of people skip it, hence the large number of vulnerabilities in the wild. I suggest looking into libraries like Zend_Form to help with th