How security flaws work: SQL injection

Status
Not open for further replies.

accipiter81

Smack-Fu Master, in training
95
Subscriptor++
[url=http:/civis/viewtopic.php?p=32155945#p32155945:2pxiiv2n said:
bl968[/url]":2pxiiv2n]Rule 1 of the programmer hand book is and always has been never trust user input. It's that simple. It's called sloppy coding and skipping steps. Real programmers wrote code that was not SQL inject-able long before SQL injections were noticed by the hacker community.
Totally this. Way back when I was taking programming courses, I was asked to help a student who was in the library science program. They had to write a little program that would read cards and sort them into "returned book" "overdue book" and "loan renewed book". The student had not been able to get far in the code, so I tried to help in a tutorial kind of way, but then gave up and tried to write the damned thing myself. It was a nightmare! I was baffled that certain things were not permitted by the course instructor, but I couldn't see why, etc. etc. At the end of what felt like a year or two, I finally fell over some details the student had forgotten to mention. The data was assumed to be chronologically ordered, correctly typed with no typos ever in any field. I had this fantasy script done in 20 minutes, because I no longer needed data checks of any kind such as checking the cards for chronological order in the first place.
I have wondered, from time to time, whatever happened to those deluded people, living in a world where they are to assume all user data is not only not malicious, but also perfect.
 
Upvote
3 (3 / 0)

Darkness1231

Ars Praefectus
4,608
Subscriptor++
Funny. Yet again Peter came out with his holier than everyone that isn't busily coding "the one way that Peter learned how to fix this" message.

But he managed to get his shotgun out for C and C++ in the penultimate paragraph. Some targets are just too good to ignore, not even when they aren't part of the problem. Maybe it helps with the word count.
 
Upvote
-6 (3 / -9)
I've been seeing people blame incompetent devs for this problem for a decade, but that is sort of missing the point. This isn't the sort of problem that can be fixed through education or blame-games. Everyone starts knowing nothing but how to cry and drink mother's milk, so everyone has to go through that awkward phase where they know enough to get things done, but not enough to do them well. Today's internet has no affordance for people to be like that, so it has no affordance for new developers learning to work with today's tools. You have to fix the people or the tools, and you can't fix the people, so...

The solution is better tooling. Get rid of all the easy paths that let developers shoot themselves in the foot. There's no reason (aside from legacy) that the default DB API has to be text-based and susceptible to injection. In my view it could still be SQL-like, as long as it's not parsed as text, something like db.select("field", "field", "field").from("table").where(Query.equals("field", value).and(...). This problem is mainly the fault of the DB vendors for not having gotten together and standardized a SQL-object API decades ago. It's up to them to fix it.
 
Upvote
0 (0 / 0)
This is why I really wish PHP's MySQLi library wasn't such an inconsistent mess; prepared statements are far more secure thanks to using placeholders and then passing the values separately, but the extra overhead makes them a bit slower if you're not actually using them repeatedly in a way that makes sense to optimise (they're a lot faster if used a lot, especially if they require a complex optimisation strategy, otherwise direct queries are often better). But even then, the MySQLi prepared statement type is a pain in the ass to actually use in the first place.

But when it comes to direct queries PHP has nothing; it just takes the raw query and leaves it to the developer to have handled it all correctly, which I've never liked; despite being the developer in this scenario I don't trust me one bit, as I know I'm prone to making mistakes.

It's why I no longer use PHP's database libraries directly anymore, but instead use wrappers that let me run queries in the same style as prepared statements (passing the query and the values separately) as it makes things so much safer, and doesn't really add any meaningful overhead (especially on PHP7/HHVM).

Take WebSQL for example; I know it seems to have lost out to IndexedDB, but I really liked the style it encouraged for working with SQL queries, and feel like that should be a lot more common than it is.

So yeah, while SQL injection is something developers absolutely should be aware of, I do feel some responsibility must always lie with those providing the client APIs for each language, as developers make fewer mistakes when APIs are properly designed to prevent them!
 
Upvote
0 (0 / 0)

DrazenZ

Wise, Aged Ars Veteran
120
How many C/C++ developers are using strcpy() and how many (on Windows) strcpy_s()?
How many check result of malloc?
What about Linux and embedded development?

Problem today is, everyone could be a sw developer. Before it was Flash, today are various apps. Results are visible - enormous number of bugs! Take for example any sw. There are serious bugs, even from big professional companies like MS. I do not mean tricky problems but stupid ones. Putting everything into libs (or language) will not help. Soon problem will escalate. IoT is a perfect example. And result is? No responsibilities on companies, only on users. When you had last update on mobile? Not to mention cameras or TVs!

Of course, problem is not only on companies but mainly on governments! They force companies to embed backdoors, they spend billions finding holes in sw and algorithms. And they do nothing to minimize risk (legislation).
 
Upvote
-4 (0 / -4)

costyp

Smack-Fu Master, in training
63
Subscriptor
Really, really interesting article. I've very limited experience (using, not maintaining) SQL databases underpinning business objects reporting systems. Even with my modicum of knowledge, I was able to follow this article. This is why I keep reading Ars-not just for the news, but for in depth reads like this.

Now I'm going to push my luck and try and get my head around buffer overflows!

Edited because:
Typos Sir, thousands of them.
 
Upvote
1 (1 / 0)

rcpk

Seniorius Lurkius
8
I honestly can't believe this is still a thing.

Surely everyone involved in any kind of development using SQL has been aware of the issues with concatenation/injection for years.

I think the first official SQL course I did was in '92 and concatenation was discussed then in a 'Don't do this' session.

Also these days, code analysis in Visual Studio will even issue an warning/error if it spots a potential injection issue. I would imagine other toolsets must do something similar surely.
 
Upvote
2 (2 / 0)

vit.spinka

Smack-Fu Master, in training
75
I also can't believe this is still a thing. Maybe it's because my first database-involving job was with a decent size application based on Oracle Database.
And the 101 of performance tuning was: always use bind variables, in other words, prepared statements. Concatenating strings means a different SQL every time, meaning a hard parse, meaning mutexes, CPU hog, flooding the cache (shared pool), and generally making the performance suffer terribly.
The safety from SQL injection came as a nice bonus :)
 
Upvote
4 (4 / 0)

passivesmoking

Ars Tribunus Angusticlavius
8,632
[url=http://arstechnica.co.uk/civis/viewtopic.php?p=32164079#p32164079:2ar3iqoa said:
vit.spinka[/url]":2ar3iqoa]I also can't believe this is still a thing. Maybe it's because my first database-involving job was with a decent size application based on Oracle Database.
And the 101 of performance tuning was: always use bind variables, in other words, prepared statements. Concatenating strings means a different SQL every time, meaning a hard parse, meaning mutexes, CPU hog, flooding the cache (shared pool), and generally making the performance suffer terribly.
The safety from SQL injection came as a nice bonus :)

Most web apps only live as long as it takes to fetch the data and render the page before they release all their resources, so that kind of performance tuning doesn't really help (in fact for queries that are only fired once per request they're actually slower), but given the security benefits I'd still go with prepared statements anyway.
 
Upvote
-2 (0 / -2)

vit.spinka

Smack-Fu Master, in training
75
[url=http://arstechnica.co.uk/civis/viewtopic.php?p=32164421#p32164421:g7s1wrst said:
passivesmoking[/url]":g7s1wrst]
Most web apps only live as long as it takes to fetch the data and render the page before they release all their resources, so that kind of performance tuning doesn't really help (in fact for queries that are only fired once per request they're actually slower), but given the security benefits I'd still go with prepared statements anyway.
Not true.
If I run the same statement from a different session, the database has to parse it - but it's what Oracle calls a soft parse, a much cheaper operation than a hard parse. Because it only calculates hash from the SQL text, finds out that the statement is already in the shared pool, and that's it.

Excessive hard parsing kills performance dramatically; excessive soft parsing is a nuisance, but usually not something to worry about.
 
Upvote
4 (5 / -1)

peterrow

Ars Scholae Palatinae
642
As a developer I came here to leave an angry response at the condescending tone of the article when talking about developers whilst at the same time explaining things in a crap way.

SQL has nothing to do with Java/PHP/C# or any other language. No software that accesses a database is any more prone to SQL injection just because of the language used.

I know SQL syntax fairly well, I'm no DBA, but I can write stored procedures, views, triggers etc... without too much hassle. Nothing I've written has been found to have a SQL injection attack - as far as I know.

The main thing to say is that there is zero reason to have SQL code embedded in your C#/Java/PHP etc... that right there is a big problem and bad practice; it's like having your admin password hardcoded, doh!

You should either use stored procedures (parameterised queries stored in the database that you call by name and parameter values) or an ORM (object relational mapping, generates parameterised SQL on the fly based on your models of the data). So the one thing I agree with the article about there is no excuse whatsoever for SQL injection attacks.
 
Upvote
-3 (0 / -3)
Parameterized queries are one of those rare beasts where using them improves security, performance and resiliency all at the same time. It really is a win-win-win.

That said, I've committed some heinous crimes against security including producing software where the intended behaviour is to allow the users to write their own SQL to be executed. Of course, the only people with access to this would also have direct access to the database so what's the worst that could happen?
 
Upvote
3 (3 / 0)
The main thing to say is that there is zero reason to have SQL code embedded in your C#/Java/PHP etc... that right there is a big problem and bad practice; it's like having your admin password hardcoded, doh!
SQL is a pretty garbage language for anything other than set operations (by design, it's built for set operations!). It's reasonable to construct queries in code (for example to dynamically add terms to a 'where' clause depending on user input). What's not reasonable is filling parameters using string operations.

sprocs are nice, but not every problem is solved by sprocs. Parameterized queries can be sprocs and arguably should be sprocs when they can be, but if an sproc isn't a good fit, you should still parameterize.
 
Upvote
2 (2 / 0)

ChrisSD

Ars Tribunus Angusticlavius
6,213
[url=http:/civis/viewtopic.php?p=32165325#p32165325:2hz4zbwu said:
SomeGuy123456[/url]":2hz4zbwu]Parameterized queries are one of those rare beasts where using them improves security, performance and resiliency all at the same time. It really is a win-win-win.

That said, I've committed some heinous crimes against security including producing software where the intended behaviour is to allow the users to write their own SQL to be executed. Of course, the only people with access to this would also have direct access to the database so what's the worst that could happen?
Ah, those famous last words. ;)
 
Upvote
0 (0 / 0)

peterrow

Ars Scholae Palatinae
642
[url=http:/civis/viewtopic.php?p=32165521#p32165521:24tsxixe said:
DrPizza[/url]":24tsxixe]
The main thing to say is that there is zero reason to have SQL code embedded in your C#/Java/PHP etc... that right there is a big problem and bad practice; it's like having your admin password hardcoded, doh!
SQL is a pretty garbage language for anything other than set operations (by design, it's built for set operations!). It's reasonable to construct queries in code (for example to dynamically add terms to a 'where' clause depending on user input). What's not reasonable is filling parameters using string operations.

sprocs are nice, but not every problem is solved by sprocs. Parameterized queries can be sprocs and arguably should be sprocs when they can be, but if an sproc isn't a good fit, you should still parameterize.

Sorry but that is just wrong.
There is zero reason to use dynamic SQL that is compiled into your software ever, it may be quicker if you just need to do something pissy and trivial - but then you start a slippery slope.

Stored procedures allow you to do more than just a simple query if you need to encapsulate something with the data access.

At it's most basic a stored procedure is a the same as a parameterised query.

Other reasons for not hardcoding your SQL into your software:
1) It's faster, as your SQL tools, e.g. SQL Server Management Studio will give you syntax checking, colour coding etc.. etc.. hence less try-fix-try-fix. Your C#/Java/PHP IDE not so much.
2) If there is a subtle bug in the query with certain values of data then you can deploy a hotfix far quicker to the DB than if you have to redeploy your software.

Your response is laughable in that on the one hand you berate developers for allowing SQL injection attack, and asserting the library and frameworks should do more to solve the problem (as if they every could fully solve it) whilst at the same time arguing that dynamic SQL embedded into compiled code is a good idea in some cases. :facepalm:
 
Upvote
-1 (0 / -1)

passivesmoking

Ars Tribunus Angusticlavius
8,632
[url=http://arstechnica.co.uk/civis/viewtopic.php?p=32164717#p32164717:so7d48sf said:
vit.spinka[/url]":so7d48sf]
[url=http://arstechnica.co.uk/civis/viewtopic.php?p=32164421#p32164421:so7d48sf said:
passivesmoking[/url]":so7d48sf]
Most web apps only live as long as it takes to fetch the data and render the page before they release all their resources, so that kind of performance tuning doesn't really help (in fact for queries that are only fired once per request they're actually slower), but given the security benefits I'd still go with prepared statements anyway.
Not true.
If I run the same statement from a different session, the database has to parse it - but it's what Oracle calls a soft parse, a much cheaper operation than a hard parse. Because it only calculates hash from the SQL text, finds out that the statement is already in the shared pool, and that's it.

Excessive hard parsing kills performance dramatically; excessive soft parsing is a nuisance, but usually not something to worry about.

Of course all of that is predicated on the assumption that the application is using Oracle as its backend database. If it's not then however the statement prep is handled is entirely up to the database backend. In my experience Oracle is not very common as a backend for web applications. MySQL, Postgres and SQLite are far more common.

I'm not saying you shouldn't do it anyway! I'm just pointing out that a web application tends to operate in a very different mode from a traditional long-running app and you can't expect something that brings performance benefits in the latter to also bring performance benefits in the former.
 
Upvote
-1 (0 / -1)
[url=http:/civis/viewtopic.php?p=32165641#p32165641:2ia3xzik said:
peterrow[/url]":2ia3xzik]
[url=http:/civis/viewtopic.php?p=32165521#p32165521:2ia3xzik said:
DrPizza[/url]":2ia3xzik]
The main thing to say is that there is zero reason to have SQL code embedded in your C#/Java/PHP etc... that right there is a big problem and bad practice; it's like having your admin password hardcoded, doh!
SQL is a pretty garbage language for anything other than set operations (by design, it's built for set operations!). It's reasonable to construct queries in code (for example to dynamically add terms to a 'where' clause depending on user input). What's not reasonable is filling parameters using string operations.

sprocs are nice, but not every problem is solved by sprocs. Parameterized queries can be sprocs and arguably should be sprocs when they can be, but if an sproc isn't a good fit, you should still parameterize.

Sorry but that is just wrong.
There is zero reason to use dynamic SQL that is compiled into your software ever, it may be quicker if you just need to do something pissy and trivial - but then you start a slippery slope.

Stored procedures allow you to do more than just a simple query if you need to encapsulate something with the data access.
Which SQL dialect makes dynamically adding terms to a where clause straightforward, error-free, and elegant?

Your response is laughable in that on the one hand you berate developers for allowing SQL injection attack, and asserting the library and frameworks should do more to solve the problem (as if they every could fully solve it)
They can and do.

whilst at the same time arguing that dynamic SQL embedded into compiled code is a good idea in some cases. :facepalm:
Then what is your solution to the case I describe?

Consider in particular that dynamic SQL with purpose built queries will often yield better performance than queries such as:

Code:
SELECT first_name, last_name
  FROM employees
 WHERE (     employee_id = ? OR ? IS NULL)
   AND (   subsidiary_id = ? OR ? IS NULL)
   AND (UPPER(last_name) = ? OR ? IS NULL)
(which avoids the dynamic query to handle different search terms, but makes the query otherwise awkward)
 
Upvote
2 (2 / 0)

peterrow

Ars Scholae Palatinae
642
[url=http:/civis/viewtopic.php?p=32165989#p32165989:3b3x0wat said:
DrPizza[/url]":3b3x0wat]
[url=http:/civis/viewtopic.php?p=32165641#p32165641:3b3x0wat said:
peterrow[/url]":3b3x0wat]
[url=http:/civis/viewtopic.php?p=32165521#p32165521:3b3x0wat said:
DrPizza[/url]":3b3x0wat]
The main thing to say is that there is zero reason to have SQL code embedded in your C#/Java/PHP etc... that right there is a big problem and bad practice; it's like having your admin password hardcoded, doh!
SQL is a pretty garbage language for anything other than set operations (by design, it's built for set operations!). It's reasonable to construct queries in code (for example to dynamically add terms to a 'where' clause depending on user input). What's not reasonable is filling parameters using string operations.

sprocs are nice, but not every problem is solved by sprocs. Parameterized queries can be sprocs and arguably should be sprocs when they can be, but if an sproc isn't a good fit, you should still parameterize.

Sorry but that is just wrong.
There is zero reason to use dynamic SQL that is compiled into your software ever, it may be quicker if you just need to do something pissy and trivial - but then you start a slippery slope.

Stored procedures allow you to do more than just a simple query if you need to encapsulate something with the data access.
Which SQL dialect makes dynamically adding terms to a where clause straightforward, error-free, and elegant?

Your response is laughable in that on the one hand you berate developers for allowing SQL injection attack, and asserting the library and frameworks should do more to solve the problem (as if they every could fully solve it)
They can and do.

whilst at the same time arguing that dynamic SQL embedded into compiled code is a good idea in some cases. :facepalm:
Then what is your solution to the case I describe?

Consider in particular that dynamic SQL with purpose built queries will often yield better performance than queries such as:

Code:
SELECT first_name, last_name
  FROM employees
 WHERE (     employee_id = ? OR ? IS NULL)
   AND (   subsidiary_id = ? OR ? IS NULL)
   AND (UPPER(last_name) = ? OR ? IS NULL)
(which avoids the dynamic query to handle different search terms, but makes the query otherwise awkward)

Well that query right there has a bad case of RBAR right there!
Before the SQL engine can compare UPPER(last_name)) = ? it has to call the upper() function of every row in the table, therefore fail!

Doing a search on an arbitrary field isn't going to help you if performance is your aim the field hasn't got an index.
Besides if you really, really have such a nasty situation to require such horrid SQL then you could still do that without hardcoding the SQL into your code.
 
Upvote
-2 (0 / -2)
[url=http:/civis/viewtopic.php?p=32162315#p32162315:39viu0u4 said:
Darkness1231[/url]":39viu0u4]Funny. Yet again Peter came out with his holier than everyone that isn't busily coding "the one way that Peter learned how to fix this" message.

But he managed to get his shotgun out for C and C++ in the penultimate paragraph. Some targets are just too good to ignore, not even when they aren't part of the problem. Maybe it helps with the word count.

But surely script kiddies are going around uncovering and exploiting buffer overflows on open ports left right and center that the only solution is to blow up C and C++!
 
Upvote
0 (0 / 0)
[url=http:/civis/viewtopic.php?p=32164421#p32164421:3a6exqx8 said:
passivesmoking[/url]":3a6exqx8]
[url=http://arstechnica.co.uk/civis/viewtopic.php?p=32164079#p32164079:3a6exqx8 said:
vit.spinka[/url]":3a6exqx8]I also can't believe this is still a thing. Maybe it's because my first database-involving job was with a decent size application based on Oracle Database.
And the 101 of performance tuning was: always use bind variables, in other words, prepared statements. Concatenating strings means a different SQL every time, meaning a hard parse, meaning mutexes, CPU hog, flooding the cache (shared pool), and generally making the performance suffer terribly.
The safety from SQL injection came as a nice bonus :)

Most web apps only live as long as it takes to fetch the data and render the page before they release all their resources, so that kind of performance tuning doesn't really help (in fact for queries that are only fired once per request they're actually slower), but given the security benefits I'd still go with prepared statements anyway.

I have no idea where you could have learned such a thing, because it's completely wrong. In Oracle (and lots of other DBMSes), the query cache stays around for along time after execution, and cached queries are reused if another instance makes the same one. In fact, in oracle, the dba can have queries hang in the cache forever, if they're frequently done and they can do some improvement to them - thus you can even improve the performance of a third party application for which you have no source code. I can tell you this for a fact because I supported such an app for several years, written by people who wrote really crappy SQL and didn't know how to properly optimize it out of the box, but since their crappy SQL was properly parameterized, we could apply all sorts of fixes ourselves. We had some queries running more than a hundred times faster than the stock configuration in very short order.

All of that flies out the window if you use string-concatenated queries though, because then the optimizer is unable to recognize that it's the same query as some other one with different hardcoded values in it. The person you were responding to was right, AND had some great advice.

Just going to say this again - there is no defense for string-concatenated queries. None at all.
 
Upvote
2 (3 / -1)
[url=http:/civis/viewtopic.php?p=32165989#p32165989:27inozql said:
DrPizza[/url]":27inozql]
[url=http:/civis/viewtopic.php?p=32165641#p32165641:27inozql said:
peterrow[/url]":27inozql]
[url=http:/civis/viewtopic.php?p=32165521#p32165521:27inozql said:
DrPizza[/url]":27inozql]
The main thing to say is that there is zero reason to have SQL code embedded in your C#/Java/PHP etc... that right there is a big problem and bad practice; it's like having your admin password hardcoded, doh!
SQL is a pretty garbage language for anything other than set operations (by design, it's built for set operations!). It's reasonable to construct queries in code (for example to dynamically add terms to a 'where' clause depending on user input). What's not reasonable is filling parameters using string operations.

sprocs are nice, but not every problem is solved by sprocs. Parameterized queries can be sprocs and arguably should be sprocs when they can be, but if an sproc isn't a good fit, you should still parameterize.

Sorry but that is just wrong.
There is zero reason to use dynamic SQL that is compiled into your software ever, it may be quicker if you just need to do something pissy and trivial - but then you start a slippery slope.

Stored procedures allow you to do more than just a simple query if you need to encapsulate something with the data access.
Which SQL dialect makes dynamically adding terms to a where clause straightforward, error-free, and elegant?

Have you ever played with MOCA? It's pretty cool.
 
Upvote
0 (0 / 0)

passivesmoking

Ars Tribunus Angusticlavius
8,632
[url=http://arstechnica.co.uk/civis/viewtopic.php?p=32167681#p32167681:yi7l590w said:
Peevester[/url]":yi7l590w]
[url=http:/civis/viewtopic.php?p=32164421#p32164421:yi7l590w said:
passivesmoking[/url]":yi7l590w]
[url=http://arstechnica.co.uk/civis/viewtopic.php?p=32164079#p32164079:yi7l590w said:
vit.spinka[/url]":yi7l590w]I also can't believe this is still a thing. Maybe it's because my first database-involving job was with a decent size application based on Oracle Database.
And the 101 of performance tuning was: always use bind variables, in other words, prepared statements. Concatenating strings means a different SQL every time, meaning a hard parse, meaning mutexes, CPU hog, flooding the cache (shared pool), and generally making the performance suffer terribly.
The safety from SQL injection came as a nice bonus :)

Most web apps only live as long as it takes to fetch the data and render the page before they release all their resources, so that kind of performance tuning doesn't really help (in fact for queries that are only fired once per request they're actually slower), but given the security benefits I'd still go with prepared statements anyway.

I have no idea where you could have learned such a thing, because it's completely wrong. In Oracle (and lots of other DBMSes), the query cache stays around for along time after execution, and cached queries are reused if another instance makes the same one. In fact, in oracle, the dba can have queries hang in the cache forever, if they're frequently done and they can do some improvement to them - thus you can even improve the performance of a third party application for which you have no source code. I can tell you this for a fact because I supported such an app for several years, written by people who wrote really crappy SQL and didn't know how to properly optimize it out of the box, but since their crappy SQL was properly parameterized, we could apply all sorts of fixes ourselves. We had some queries running more than a hundred times faster than the stock configuration in very short order.

All of that flies out the window if you use string-concatenated queries though, because then the optimizer is unable to recognize that it's the same query as some other one with different hardcoded values in it. The person you were responding to was right, AND had some great advice.

Just going to say this again - there is no defense for string-concatenated queries. None at all.

First off, I'm not defending not using prepared statements, just pointing out that in some scenarios they're not cost-free.

Second off, have you read the documentation for any DBMS other than Oracle regarding prepared statements, how long they're cached for and what statements are available to which sessions?

For example the MySQL documentation (https://dev.mysql.com/doc/refman/5.6/en ... ching.html) says:
The server maintains caches for prepared statements and stored programs on a per-session basis. Statements cached for one session are not accessible to other sessions. When a session ends, the server discards any statements cached for it.

And the Postgres documentation (https://www.postgresql.org/docs/current ... epare.html) says:
Prepared statements only last for the duration of the current database session. When the session ends, the prepared statement is forgotten, so it must be recreated before being used again. This also means that a single prepared statement cannot be used by multiple simultaneous database clients; however, each client can create their own prepared statement to use. Prepared statements can be manually cleaned up using the DEALLOCATE command.

It would therefore seem that Oracle is the outlier.
 
Upvote
1 (1 / 0)
[url=http:/civis/viewtopic.php?p=32166101#p32166101:5i89jgro said:
peterrow[/url]":5i89jgro]
Well that query right there has a bad case of RBAR right there!
Before the SQL engine can compare UPPER(last_name)) = ? it has to call the upper() function of every row in the table, therefore fail!
A computed column or function-based index can address that.

Doing a search on an arbitrary field isn't going to help you if performance is your aim the field hasn't got an index.
Any or all of those columns could have indices; that's an orthogonal question.

Besides if you really, really have such a nasty situation to require such horrid SQL then you could still do that without hardcoding the SQL into your code.
The question is, how do you get queries that are at least as efficient as the dynamic SQL queries that can handle multiple numbers of search filters? Thus far you've avoided the question. I've included one not uncommon solution to "avoid" dynamic SQL, but it's an inferior solution as it performs worst.
 
Upvote
2 (2 / 0)

peterrow

Ars Scholae Palatinae
642
[url=http:/civis/viewtopic.php?p=32170767#p32170767:1jqf4xxh said:
DrPizza[/url]":1jqf4xxh]
[url=http:/civis/viewtopic.php?p=32166101#p32166101:1jqf4xxh said:
peterrow[/url]":1jqf4xxh]
Well that query right there has a bad case of RBAR right there!
Before the SQL engine can compare UPPER(last_name)) = ? it has to call the upper() function of every row in the table, therefore fail!
A computed column or function-based index can address that.

Doing a search on an arbitrary field isn't going to help you if performance is your aim the field hasn't got an index.
Any or all of those columns could have indices; that's an orthogonal question.

Besides if you really, really have such a nasty situation to require such horrid SQL then you could still do that without hardcoding the SQL into your code.
The question is, how do you get queries that are at least as efficient as the dynamic SQL queries that can handle multiple numbers of search filters? Thus far you've avoided the question. I've included one not uncommon solution to "avoid" dynamic SQL, but it's an inferior solution as it performs worst.

To answer the question you simply pass your parameters to the stored procedure and have it generate the dynamic SQL. Thus you have the flexibility of the dynamic SQL if you really must have it whilst at the same time making it easy to patch without a redeployment of the code. And don't say the parameters could change - because once the code is compiled and deployed no they won't change not unless you deploy a new version. Alternatively you could use an ORM.

Having SQL such as UPPER() shows RBAR - you could work around that in other ways but your example did not do that and therefore is RBAR which is bad.

It's like tutorials which promote SQL injection attacks - don't show code without contextual explanation - especially not relating to an article about what not to do.
 
Upvote
0 (0 / 0)

peterrow

Ars Scholae Palatinae
642
[url=http:/civis/viewtopic.php?p=32173349#p32173349:ym3lypvw said:
DrPizza[/url]":ym3lypvw]
And don't say the parameters could change - because once the code is compiled and deployed no they won't change not unless you deploy a new version.
wat.

That is... not how things work.

I don't think you understand what I'm saying.

Say you code your application to pass some combination of parameters X, Y and Z to your dynamic SQL that you generate.
You compile and deploy your application, there is no way for your application to now take a W parameter as well such that it can take W, X, Y, Z without changing the code, compiling and deploying.

Thus the whole dynamic SQL thing is only as dynamic as your code that builds the SQL statement. So the need to embed that SQL in your application is not dependant on a need to create dynamic SQL.
 
Upvote
0 (0 / 0)
[url=http:/civis/viewtopic.php?p=32161171#p32161171:1ocplz66 said:
Dayvid[/url]":1ocplz66]
[url=http:/civis/viewtopic.php?p=32157207#p32157207:1ocplz66 said:
ARaybould[/url]":1ocplz66]
[url=http:/civis/viewtopic.php?p=32154417#p32154417:1ocplz66 said:
Dayvid[/url]":1ocplz66]
[url=http:/civis/viewtopic.php?p=32150185#p32150185:1ocplz66 said:
millad[/url]":1ocplz66]
[url=http:/civis/viewtopic.php?p=32148031#p32148031:1ocplz66 said:
Dayvid[/url]":1ocplz66]... but as an arbitrary example SELECT A, ?field FROM TABLE is doomed - there's no way I can specify that as a particular field from that database table in a prepared statement. There's workarounds (eg using a giant case/if else/whatever statement to build the query from comparing ?field to preapproved values if they're static) but they're ugly enough that people can avoid them.

"preapproved values" are already extant within the database schema. White listing your column names is trivial:
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='yourDB' AND `TABLE_NAME`='yourTable'

if the column name you want is in that list, you're good to go. It's not a "giant case/if else/whatever statement", it's a very simple and performant conditional that can be run in 1 line of code in eg: PHP.

Except it's not because you just doubled your queries at best. What if it's two fields? You're then adding yet another query or returning multiple fields at once from information_schema. Hope your string comparisons are exactly the same in your code and database collation (they're probably not, unicode is fun).

That and you're *still* building your query through string concat anyway so it's less obviously correct on examination than a prepared statement.

It's easy to think you've come up with half baked solutions to a trivial example. The issue here isn't that there's no solutions, it's that they have their own issues.

Talking of half-baked things, your argument is that sometimes it is OK to use a mechanism that permits arbitrary SQL execution in a public-facing application, on the grounds of convenience - you have already conceded that there is no argument on the basis of necessity.

This is the wrong approach to the situation. If it looks like using prepared statements is going to be complicated, then you should first review your design, to see if the complexity is an avoidable consequence of a suboptimal design. If you cannot simplify the problem, then the right approach is to suck it up and do whatever is necessary to make your application secure. The few cases where there are no security concerns in untrusted users being able to perform arbitrary SQL - if there are any - are not relevant here, as the topic of the article is SQL injection in relation to security.

No, I'm not arguing that at all - although "this is not necessary" and "this is not necessary to make perform well" are wildly different statements. I'm saying why I see people still use string concat to build queries in response to "why do people do this when it's so easy to avoid". Because in some cases it's actually exceedingly complex to do so - to the point that it doesn't happen and people write crappy software that continues to be full of bugs.

Saying "don't do that" might feel good but it's just not going to happen - this is common in HR analytics/reporting software for example and a bunch of different areas in which there's serious money involved. If you want to get rid of SQL injection completely you need a better solution than what we have currently as some of the limits around prepared statements lead to people doing this.

'No, I'm not arguing that at all...' - but you are, and you have just doubled-down in this post.

'Saying "don't do that" might feel good but it's just not going to happen' - true, but not for the reason that you are giving. We all appreciate that doing arbitrary database actions through prepared statements is difficult, but we don't think that any more than a tiny minority (if any) of the many programmers who do query construction by string concatenation are being forced into doing so because they have no reasonable alternative. You have consistently failed to present us with a plausible case of any significant magnitude, and no, the observation that arbitrary database actions through prepared statements is difficult is not that case: firstly, it doesn't show who it actually presents a problem for, and secondly, it does not address the objection that the closer a system approaches enabling arbitrary database actions by users, the closer it approaches being completely insecure. An attacker does not need SQL injection against a system that is insecure by design (i.e.made insecure by its intentional capabilities). I would need better arguments than I have seen from you so far before I would accept that there is any gap between the set of system designs that can be practically implemented through prepared statements, and the set of those that are too open by intent to be secure.

Furthermore, even if you were right that the solution we have now is not good enough, that would not make string concatenation safe. The truth is that we have a good enough solution, but too many developers are too ignorant, dumb, lazy, pressured or complacent to use it. The chances of there ever being a solution that is both safer and easier than the unsafe method is slim to none.
 
Upvote
0 (0 / 0)

gml142

Wise, Aged Ars Veteran
108
[url=http:/civis/viewtopic.php?p=32147575#p32147575:3ldu850n said:
ChrisSD[/url]":3ldu850n]It is baffling to me that there are web devs writing for some major sites who are writing code in such a flawed way. I don't want to call them incompetent exactly but at this point there is little excuse for such elementary problems.

Personally I've found the slogan "parametrize, not sanitize" helps inexperienced devs to remember good practice. The only issue is they sometimes take it a bit too literally but I can't figure out a pithy catchphrase that explains sanity checks have their place so long as it's built on top of prepared statements and not as a replacement to it.

How about, "parameterize before you sanitize?"
 
Upvote
1 (1 / 0)
[url=http:/civis/viewtopic.php?p=32179161#p32179161:1t14iy7c said:
peterrow[/url]":1t14iy7c]
[url=http:/civis/viewtopic.php?p=32173349#p32173349:1t14iy7c said:
DrPizza[/url]":1t14iy7c]
And don't say the parameters could change - because once the code is compiled and deployed no they won't change not unless you deploy a new version.
wat.

That is... not how things work.

I don't think you understand what I'm saying.

Say you code your application to pass some combination of parameters X, Y and Z to your dynamic SQL that you generate.
You compile and deploy your application, there is no way for your application to now take a W parameter as well such that it can take W, X, Y, Z without changing the code, compiling and deploying.
Says who?
 
Upvote
0 (0 / 0)
Status
Not open for further replies.