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.[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.
[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![]()
Not true.[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.
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.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!
Ah, those famous last words.[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?
[url=http:/civis/viewtopic.php?p=32165521#p32165521:24tsxixe said:DrPizza[/url]":24tsxixe]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.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!
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.
[url=http://arstechnica.co.uk/civis/viewtopic.php?p=32164717#p32164717:so7d48sf said:vit.spinka[/url]":so7d48sf]Not true.[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.
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.
Which SQL dialect makes dynamically adding terms to a where clause straightforward, error-free, and elegant?[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]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.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!
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.
They can and do.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)
Then what is your solution to the case I describe?whilst at the same time arguing that dynamic SQL embedded into compiled code is a good idea in some cases. :facepalm:
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)
[url=http:/civis/viewtopic.php?p=32165989#p32165989:3b3x0wat said:DrPizza[/url]":3b3x0wat]Which SQL dialect makes dynamically adding terms to a where clause straightforward, error-free, and elegant?[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]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.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!
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.
They can and do.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)
Then what is your solution to the case I describe?whilst at the same time arguing that dynamic SQL embedded into compiled code is a good idea in some cases. :facepalm:
Consider in particular that dynamic SQL with purpose built queries will often yield better performance than queries such as:
(which avoids the dynamic query to handle different search terms, but makes the query otherwise awkward)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)
[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.
[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.
[url=http:/civis/viewtopic.php?p=32165989#p32165989:27inozql said:DrPizza[/url]":27inozql]Which SQL dialect makes dynamically adding terms to a where clause straightforward, error-free, and elegant?[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]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.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!
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.
[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.
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.
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.
A computed column or function-based index can address that.[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!
Any or all of those columns could have indices; that's an orthogonal question.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.
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.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.
[url=http:/civis/viewtopic.php?p=32170767#p32170767:1jqf4xxh said:DrPizza[/url]":1jqf4xxh]A computed column or function-based index can address that.[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!
Any or all of those columns could have indices; that's an orthogonal question.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.
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.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.
wat.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.
[url=http:/civis/viewtopic.php?p=32173349#p32173349:ym3lypvw said:DrPizza[/url]":ym3lypvw]wat.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.
That is... not how things work.
[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.
[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.
Says who?[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]wat.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.
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.