Showing posts with label injection. Show all posts
Showing posts with label injection. Show all posts

Monday, February 20, 2012

Preventing SQL Injection with paramaterized queries

I use paramaterized queries when using ad-hoc queries in my code-behind. Everywhere website I visit says to use stored procedures or paramaterized queries if stored procedures cannot be used. I understand how SQL injection attacks work, but could someone please enlighten me why a paramaterized query helps prevent these attacks? It seems to me that the text that is entered on the web form would just be passed into the paramater, but I'm obviously missing something. Thanks.

Hi,

If you run the below statement it returns all the records.

declare @.pwd nvarchar(50)
declare @.username nvarchar(50)

set @.username = N''' or 1=1--'
set @.pwd = N'xxx'


declare @.sql nvarchar(1000)
SET @.sql = N'select username, password, userid from Users where username = N''' + @.username + ''' and Password = N''' + @.pwd + ''''

exec sp_executesql @.sql

select @.sql

But if you use create a procedure like below.

create proc login (
@.pwd nvarchar(50),
@.username nvarchar(50)
)
as
select username, password, userid from Users where username = @.username and Password = @.pwd
go

And run the below code, it returns nothing.

declare @.pwd nvarchar(50)
declare @.username nvarchar(50)

set @.username = N''' or 1=1--'
set @.pwd = N'xxx'

exec login @.pwd, @.username

In stored procedures parameter values are exactly used as values of the parameters, but if you are creating dynamically sql statements the final sql sentence may change according to the entered values

|||

Eralper is right, that's why. If his explaination wasn't clear enough, try this:

SELECT * FROM MyTable WHERE field='value' OR 1=1 OR ''=''

This would be similiar to someone building a SQL String like:

SQL="SELECT * FROM MyTable WHERE field='" & textbox1.text & "'"

and then someone types invalue' OR 1=1 OR ''=' into the textbox. This will return every row in MyTable instead of just the one you wanted. You could do sorts of things as well, like typingvalue' DELETE FROM MyTable SELECT ' will delete the contents of MyTable on you, etc. But this won't work:

DECLARE @.MyText varchar(8000)
SET @.MyText='value'' DELETE FROM MyTable SELECT '''
SELECT * FROM MyTable WHEREfield=@.MyText

This will return no records at all, because field never matches @.MyText (unless you have that weird value in a fieldBig Smile [:D])

Because @.MyText is a parameter value, it will not even attempt to execute or use anything within it as a command, partial command, etc. It is a value, and it can't be anything other than a value.

|||

Sql injection really has me freaked but I'm trying to find an effective/efficient way of writing dynamic sql.

This this instance: You have a GridView binded to an ObjectDataSource with some TextBoxes used for Parameters that Filter the GridView. The GridView allows Sorting on all Fields and Custom Paging is implemented in a Sql Stored Procedure because the DataSource contains 100 million records.

With Custom Paging, Sorting must be done in the Stored Procedure. My issue is finding an appropriate method to allow Order By and Where to be dynamically created. Not all Fields would necessarily be filtered and the Order By may sort multiple Fields.

This would be easiest to do with Dynamic Sql, but I can't fathom the risk of exposing too much information because of an injection attack.

The only other option I know of is to use CASE statements in the SProc but that ends up being nasty and huge.

My concern with injection is the fact you have no idea what could be coming through. It may be a simple single quite or a hex derivative. You might say to use Regular Expressions to validate the input, but when filtering, some of the Fields may be free-text Fields.

Any thoughts related to this?

Nathan

|||

Hi,

One more step further than the dynamic sql, if you have 100 million records and if you will let the user to sort the data on any column and filter on any column will cause the indexes on the sourcce tables to be insufficiently used or will not be used perhaps. So you will struggle with the performance problems. So you will limit the columns that the users will sort on or filter on, and will create indexes on those fields, otherwise performance will be a headache.

One more alternative is creating sp's for each condition. But this may be impossible if you have so many conditions.

As far as I remember, I once faced a problem with "order by" clause which was related with the record size. Since it was too big for sql server to manage an order process on it. So you can perhaps first build a table with only identity columns and necessary fields to be build for an order. And if you do not need a joined table for an order process do not include it. After managing the order by process, you can gather the other fields that will be displayed on the grid using the primary key values.

Eralper

http://www.kodyaz.com

|||

I don't think I understand what you mean by the Indexes to be insufficiently used. Assume that each Field has an Index set.

A quick question too now that I think about it. I saw in an instance of one of my databases where there were some indexes set to 1 field while some were set to multiple fields. How does this affect the order by clause? Let's say 3 fields, A, B and C each have a single index set on it.

If I order by A and B then are their indexes inconsequential since both are being ordered? Is that why you would have indexes with multiple fields. If that is the case, then you're right about limiting their sorting capabilities as this one table that has millions of records also has over 20 fields and doing combinations of indexes would be gnarly.

If that is the case that multiple field indexes must be created for multiple order by field parameters then I will stick with single indexes and order by field parameters.

It just came to mind as you can order multiple columns in an Excel Worksheet, I thought I'd allow that in a GridView.

Nathan

|||

Hi,

For multiple field indexes, let's say you select A and B from Table1 and you have index on A

For the criterias or the sorting, the SELECT will reference the index A then will go to physical data pages and get the column B values.

But if you have an index both covering A and B, then the SELECT can get all information from the index and will not go the physical data pages. This will be very fast when compared with reading data pages. The end point of this approach is creating covering indexes.

For the first part of your reply, if you have an index for each colum you display on the grid then no problem. But if you display field A, and there is not an index on A. Then to filter all data in table for a specific value on field A, you will have do full table scan or at least a clustered index scan will run on the table.

Eralper

http://www.kodyaz.com

|||

So... Stored procedures provide protection against sql injection attacks... But what about parameterized queries?

I've always assumed that parameterized queries, even those generated dynamically, provide the same level of protection as stored procedures. Is this a proper assumption?

|||

Yes, you are right. As I know they are simply the same like running a stored procedure. They can be used against sql injections.

Eralper

http://www.kodyaz.com

Preventing SQL Injection attacks

My site has come under attack from sql injections. I thought I had
things handled by replacing all single quotes with two single quotes,
aka

Replace(inputString, "'", "''")

Alas, clever hackers have still managed to find a way to drop columns
from some of my tables. Can anybody direct me towards a best practice
document on preventing these attacks?

Thank you thank you,

KevinKevin Audleman wrote:
> My site has come under attack from sql injections. I thought I had
> things handled by replacing all single quotes with two single quotes,
> aka
> Replace(inputString, "'", "''")
> Alas, clever hackers have still managed to find a way to drop columns
> from some of my tables. Can anybody direct me towards a best practice
> document on preventing these attacks?
> Thank you thank you,
> Kevin|||http://www.wwwcoder.com/main/parent...68/default.aspx

http://www.vbmysql.com/articles/sqlinjection.html

http://msdn.microsoft.com/msdnmag/i...9/SQLInjection/

http://shiflett.org/articles/security-corner-apr2004

http://www.microsoft.com/technet/pr...n/sp3sec03.mspx|||Thank you Jennifer =)|||Kevin Audleman (audleman@.quasika.net) writes:
> My site has come under attack from sql injections. I thought I had
> things handled by replacing all single quotes with two single quotes,
> aka
> Replace(inputString, "'", "''")
> Alas, clever hackers have still managed to find a way to drop columns
> from some of my tables. Can anybody direct me towards a best practice
> document on preventing these attacks?

Learn about using parameterised commands in whichever API you are using.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx

Preventing Injection - Client Side

Thanks
I am building an office application which uses Microsoft Access as a
client and SQL Server as the server. I am new to SQL Server and I
don't want to anything that is too stupid. I am assuming the db
administrator would create a database specifically for this
application. The program must be able to create and drop tables and
works fine when hosted over the internet.
I am preventing everything but characters and numbers in my WHERE
clauses and data to prevent injection.
But besides this measure, the program has these access/security
needs/issues.
Tables - Create Drop Read Write
SPs -- Create Execute
In addition the program needs to read from
system_user
db_name()
information_schema.tables
Information_schema.columns
sysobjects
Am I doing anything too stupid if the admin would prefer a more secure
situation, maybe on a company database?
Willywilly wrote:
> Tables - Create Drop Read Write
> SPs -- Create Execute
> In addition the program needs to read from
> system_user
> db_name()
> information_schema.tables
> Information_schema.columns
> sysobjects
Who is the owner of these tables? Are they owned by "dbo"? If so, all
users would have to be aliased as the dbo in the database, which means
they probably have too many rights. They could be limited to creating
tables under their user names (e.g. Joe.MyTable), but this would not
give other users access to these tables. Creating and Dropping tables is
generally a system admin or database owner function and not normal for
an application. Unless, of course, you mean temp tables.
To perform DML operations on tables, I would use stored procedures. You
can use them for SELECT statements as well, but some users choose to
embed SQL in the app (I prefer SPs all around).
The other objects/functions are available to all users.
Maybe you could explain the need to create/drop tables a little more.
Same for stored procedures.
David Gugick
Quest Software
www.imceda.com
www.quest.com|||> I am preventing everything but characters and numbers in my WHERE
> clauses and data to prevent injection.
Consider using parameters rather than concatenating user-supplied values to
build the SQL statement. This is more secure.
Hope this helps.
Dan Guzman
SQL Server MVP
"willy" <willrich33@.yahoo.com> wrote in message
news:1131557696.739603.25830@.g14g2000cwa.googlegroups.com...
> Thanks
> I am building an office application which uses Microsoft Access as a
> client and SQL Server as the server. I am new to SQL Server and I
> don't want to anything that is too stupid. I am assuming the db
> administrator would create a database specifically for this
> application. The program must be able to create and drop tables and
> works fine when hosted over the internet.
> I am preventing everything but characters and numbers in my WHERE
> clauses and data to prevent injection.
> But besides this measure, the program has these access/security
> needs/issues.
> Tables - Create Drop Read Write
> SPs -- Create Execute
> In addition the program needs to read from
> system_user
> db_name()
> information_schema.tables
> Information_schema.columns
> sysobjects
> Am I doing anything too stupid if the admin would prefer a more secure
> situation, maybe on a company database?
> Willy
>|||Dan,David:
Thank you for making me think about security.
My application does not allow the user to use tables under any other
username (such as dbo) so he is fairly isolated. I realize Access
defaults to dbo but I will be shutting the database window down.
I tried to import a file to my database under a different username (like
dbo) but Access converted it back to the username of the new
database/login so that seems somewhat secure. This is why I am using
Access for a client program.
I am not coding for characters other than Like *[A-Z0-9] so the purging
of other characters from the column and table names that the user has
control of will have to do for now.
In the documentation I am going to highly recommend "isolating" the
application in separate db for "security reasons."
Thank you for suggesting parameters and DML as solutions for preventing
injection. I will keep my eye out for information on them.
I really need to learn more about SQL Server permissions and security.
Willy
*** Sent via Developersdex http://www.codecomments.com ***|||Comments inline
"willy" <willrich33@.yahoo.com> wrote in message
news:1131557696.739603.25830@.g14g2000cwa.googlegroups.com...
> Thanks
> I am building an office application which uses Microsoft Access as a
> client and SQL Server as the server. I am new to SQL Server and I
> don't want to anything that is too stupid.
You already missed this goal by using Access as the front end.

> I am assuming the db
> administrator would create a database specifically for this
> application. The program must be able to create and drop tables and
> works fine when hosted over the internet.
>
This would require opening a SQL port to the internet. Not a particularly
good idea from a security standpoint, especially when you are talking about
the privileges necessary to do what you ask.

> I am preventing everything but characters and numbers in my WHERE
> clauses and data to prevent injection.
>
Doesn't matter. With open network ports and SQL credentials in the Access
app, your server is open to conection via Query Analyzer or any other SQL
client app. Who cares about SQL injection when I can send any SQL command I
desire.
> But besides this measure, the program has these access/security
> needs/issues.
> Tables - Create Drop Read Write
> SPs -- Create Execute
> In addition the program needs to read from
> system_user
> db_name()
> information_schema.tables
> Information_schema.columns
> sysobjects
> Am I doing anything too stupid if the admin would prefer a more secure
> situation, maybe on a company database?
Maybe on a throwaway system. I certainly wouldn't allow any such
application anywhere near any of my servers.
> Willy
>
Sorry if I sound harsh, but I am trying to discourage you from making some
fundamental mistakes in building a SQL application. Access front end
'applications' have caused me more headaches than any other single app dev
environment when connecting to SQL Server.
Geoff N. Hiten
Senior Database Administrator
Microsoft SQL Server MVP

Preventing ALL text SQL Injection by removing single-quotes ?

I need to ask the user for some string (not INT) input... to
build a T-SQL "find" query in SQL Server 2000.
I do *NOT* need the user to ever search for "'"... so I'm removing the
single-quote character entirely.

> s = Replace(s, "'", "")
Can someone give a working example where SQL INJECTION would still be
possible?Hi Susan
You may want to read:
http://www.sqlsecurity.com/DesktopDefault.aspx?tabid=23
http://www.sommarskog.se/dynamic_sql.html#Security2
John
"Susan S via droptable.com" <forum@.droptable.com> wrote in message
news:50B826701CBE0@.droptable.com...
>I need to ask the user for some string (not INT) input... to
> build a T-SQL "find" query in SQL Server 2000.
> I do *NOT* need the user to ever search for "'"... so I'm removing the
> single-quote character entirely.
>
> Can someone give a working example where SQL INJECTION would still be
> possible?|||I can't find a single line of that article that *SHOWS* how a
string, fully stripped of all single-quotes... can be used for
Injection.
I'm not saying that it can't.
I just need someone to post the actual code.
Ever wonder why no one has the code?
Message posted via http://www.droptable.com|||Hi
You are assuming a certain business rule is applied which is probably
quite rare. You may be able to provide dropdowns if your values are so
specific and remove the need to type in anything!!
The parameterised query option is generic and can cater for all
sutuations, it should also be fast.
John|||John... that wasn't the question at all.
I *DO* have a need to search for text without containing any single-quotes.
(I couldn't possible have a dropdown box with 1000 different searches in it.
)
Why not simple say "I don't know" instead of answering a totally different
question?
John Bell wrote:
>Hi
>You are assuming a certain business rule is applied which is probably
>quite rare. You may be able to provide dropdowns if your values are so
>specific and remove the need to type in anything!!
>The parameterised query option is generic and can cater for all
>sutuations, it should also be fast.
>John
Message posted via droptable.com
http://www.droptable.com/Uwe/Forum...curity/200507/1|||"Susan S via droptable.com" <forum@.droptable.com> wrote in message
news:510817BAE9A30@.droptable.com...
> John... that wasn't the question at all.
> I *DO* have a need to search for text without containing any
> single-quotes.
> (I couldn't possible have a dropdown box with 1000 different searches in
> it.)
> Why not simple say "I don't know" instead of answering a totally different
> question?
You don't provide us with an example of your code that builds dynamic SQL so
we can only guess as to what might or might not work. Have you considered
char(39) being mixed in somehow?
But the larger question is, what is your aversion to parameterizing your
queries? If you were truly concerned about SQL injection, that's the route
you would go. Will you feel safe if nobody here can come up with an
example? Will that mean that it can't be done? You'd learn more hanging
out in hacker's circles, if that is your approach..
So, sorry if it offends you, and I'll admit that "I don't know" of a
specific example, but the real answer to your rhetorical question is:
parameterize, then you won't need to worry about it, there are no reasons it
can't be done, only excuses.
Good Luck,
Mark
[vbcol=seagreen]
> John Bell wrote:|||Well I started out the other day writing down a list from the sql server
perspective, but they all seem to start with the programmer making a
blunder. There are so many ways you can facilitate your site getting hacked
that it is really quite absurd. This is where a lot of the challenge exists.
If ever in the design of the system someone has said "It will never do such
and such" so you haven't coded defensively for the day you will have say
multiple sites on the one server (as an EG) then you have introduced time
bombs.
The most important thing about security is like so many things - expend your
effort where it will have most benefit.
I suggest you check your program code and ensure that no strings can
overflow buffers, that you use parameterised queries, that you check every
string not just for single quotes but also script and other HTML tags, for
code that can be evaluated to quotes, script, or html, that wherever
possible you remove as much need for free text entry as you can, do not
reflect errors verbatum back to the user - IE avoid replay attacks - do not
store data ever without sanitising it, do not show data with it being
santised (again), make everything as type safe as possible, normalise your
database properly, use maximum error and warning reporting when compiling,
use proper error handling, test the system thoroughly, try to break it, do
not accept warnings during compiles, and so on.
Add to that, use a DMZ, secure your web server, secure your database server,
enforce strong security... strong passwords,... I think you get the idea.
Now, look at your original question and ask yourself "was it responsible"?
Or do you think you can now check off the single quote character in
isolation? It is never a done task.
I suggest you re-read John's answer and references as a starter.
"Mark J. McGinty" <mmcginty@.spamfromyou.com> wrote in message
news:uX1WrSUhFHA.3256@.TK2MSFTNGP12.phx.gbl...
> "Susan S via droptable.com" <forum@.droptable.com> wrote in message
> news:510817BAE9A30@.droptable.com...
> You don't provide us with an example of your code that builds dynamic SQL
> so we can only guess as to what might or might not work. Have you
> considered char(39) being mixed in somehow?
> But the larger question is, what is your aversion to parameterizing your
> queries? If you were truly concerned about SQL injection, that's the
> route you would go. Will you feel safe if nobody here can come up with an
> example? Will that mean that it can't be done? You'd learn more hanging
> out in hacker's circles, if that is your approach..
> So, sorry if it offends you, and I'll admit that "I don't know" of a
> specific example, but the real answer to your rhetorical question is:
> parameterize, then you won't need to worry about it, there are no reasons
> it can't be done, only excuses.
>
> Good Luck,
> Mark
>
>
>
>|||Oh, of course, the biggest sin of them all - as Mark points out. Never use
dynamic SQL. You never need to for a correctly designed database.
"Mark J. McGinty" <mmcginty@.spamfromyou.com> wrote in message
news:uX1WrSUhFHA.3256@.TK2MSFTNGP12.phx.gbl...
> "Susan S via droptable.com" <forum@.droptable.com> wrote in message
> news:510817BAE9A30@.droptable.com...
> You don't provide us with an example of your code that builds dynamic SQL
> so we can only guess as to what might or might not work. Have you
> considered char(39) being mixed in somehow?
> But the larger question is, what is your aversion to parameterizing your
> queries? If you were truly concerned about SQL injection, that's the
> route you would go. Will you feel safe if nobody here can come up with an
> example? Will that mean that it can't be done? You'd learn more hanging
> out in hacker's circles, if that is your approach..
> So, sorry if it offends you, and I'll admit that "I don't know" of a
> specific example, but the real answer to your rhetorical question is:
> parameterize, then you won't need to worry about it, there are no reasons
> it can't be done, only excuses.
>
> Good Luck,
> Mark
>
>
>
>|||Wow.. it was just *ONE* simple request:
Post some *ACTUAL* code... that can cause SQL injection... where *ALL* singl
e
quote
characters have been removed from the string input by the user.
Seems like everyone is talking about eveything *OTHER* than that 1 simple
request.:

> Why not use another method instead?
> Why not fully secure your servers instead?
> Why not post your code?
> What are you using this for?
> You might needs users to enter single quotes some day.
> Why not write/use long parameterized methods instead?
> What if it's an INT, not a VarChar field?
> Why don't you go back and change 1000s of lines of code that you already w
rote?
> Let's talk about some totally different problems, instead of this one.
Sheezesss. That wasn't the question here. Here it is again:
s = GetUsersString() ' Get the input
s = Replace(s, "'", "") ' Remove all single-quotes
sql = "SELECT * FROM MyTable WHERE MyField='" & s & "'" ' Execute this
The Question:
In *ONE* line... without *ANY* explaination... what text would the user ente
r
as a value for "s",
that would break the above code sample?
So simple. No one can answer that? Or prove it can't be done?
Message posted via droptable.com
http://www.droptable.com/Uwe/Forum...curity/200507/1|||"Susan S via droptable.com" <forum@.droptable.com> wrote in message
news:5131626AFB930@.droptable.com...
> Wow.. it was just *ONE* simple request:
Considering all the good and relevant (despite your views) advice you've
received, it's obvious that you just don't get it; so go ahead and feel as
though you've written safe, secure code. Clearly, your mind is made up. I
think you've insulted the NG with your narrow-minded replies quite enough
for one thread.
What you refuse to accept is that it doesn't matter whether or not anyone in
this or any NG can provide you with an example. It simply doesn't matter.
It proves/disproves nothing. It does not mean it can't be done. You want
someone to prove for you that it *can* be done, otherwise you'll assume it
can't? That is a reckless approach at best.
So you choose to believe what you want to believe -- ok, fine. You chose to
ignore widely accepted best practices and now you want to justify that
choice -- that's all up to you. But don't expect the NG to validate those
choices, because -- and you know this as well as we do -- there is a body of
knowledge that says your chosen methodology is not the most secure, PERIOD,
bottom line, end of story.
And given today's Internet climate, why anyone would choose to do something
any way other than the most secure defies all reason. That's what we're on
about. That's why we can't get behind your over-simplification of the
issues.
And now I suppose you'll post another rude, frustrated, closed-minded reply
because I didn't stick to a one line answer... whatever... best of luck to
you too.
-Mark