What are "parameters" and how do they prevent SQL injections? [duplicate] - sql

This question already has answers here:
How does SQLParameter prevent SQL Injection?
(4 answers)
How does the SQL injection from the "Bobby Tables" XKCD comic work?
(13 answers)
Closed 8 years ago.
I'm very early on in learning SQL, but I've encountered the topic of SQL injections, and understand that parameters are probably the best way to prevent them. But I couldn't find any explanation of what they actually ARE.
So, for instance, in this code in ASP.NET (from w3schools):
txtUserId = getRequestString("UserId");
sql = "SELECT * FROM Customers WHERE CustomerId = #0";
command = new SqlCommand(sql);
command.Parameters.AddWithValue("#0",txtUserID);
command.ExecuteReader();
What dos the "command.parameters.addwithvalue" actually do?
I'm sorry if this is a stupid question, but I couldn't find the answer to it - everywhere I look they just say "use parameters" but don't explain what that actually means...
Thanks!

actually you need to make prepared statement to stop sql injection , another thing is you need to escape the query or add slashed before single quotes in order to qvoid SQL Injection
Form w3schools
"Some web developers use a "blacklist" of words or characters to
search for in SQL input, to prevent SQL injection attacks.
This is not a very good idea. Many of these words (like delete or
drop) and characters (like semicolons and quotation marks), are used
in common language, and should be allowed in many types of input.
(In fact it should be perfectly legal to input an SQL statement in a
database field.)
The only proven way to protect a web site from SQL injection attacks,
is to use SQL parameters.
SQL parameters are values that are added to an SQL query at execution
time, in a controlled manner.
ASP.NET Razor Example
txtUserId = getRequestString("UserId"); txtSQL = "SELECT * FROM Users
WHERE UserId = #0"; db.Execute(txtSQL,txtUserId);
Note that parameters are represented in the SQL statement by a #
marker.
The SQL engine checks each parameter to ensure that it is correct for
its column and are treated literally, and not as part of the SQL to be
executed. Another Example txtNam = getRequestString("CustomerName");
txtAdd = getRequestString("Address"); txtCit =
getRequestString("City"); txtSQL = "INSERT INTO Customers
(CustomerName,Address,City) Values(#0,#1,#2)";
db.Execute(txtSQL,txtNam,txtAdd,txtCit);"

Related

What programming language is this code from?

I am looking at some SQL code:
txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId;
I know in php it uses $_GET or $_POST to retrieve the values entered in a form so I am just wondering what is the language the first statement is written in that is retrieving the values?
I'm going to answer this definitively. No, not the language question, but the actual, important part of that code snippet.
Do Not Open Yourself To SQL Injection Attacks.
That code puts in the text contents of UserId directly into the SQL statement. Which means that someone can enter something like:
UserId=-1 or (1=1)
... and get the entire table. Or:
UserId=-1; NewSQLStatementStartsHere
... and start running malicious SQL statements on your server.
Never inject raw values into SQL. Always use parameterized values. SQL Injection Attack is still the #1 cause of security vulnerabilities in software.

Dapper.net: How to print query with parameter values [duplicate]

This question already has answers here:
Is there any way to trace\log the sql using Dapper?
(6 answers)
Closed 3 years ago.
Lets take an example:
const string PERSON_SQL = "SELECT Id " +
"FROM Persons " +
"WHERE LastName=#LastName AND FirstName=#FirstName";
patientId = connection.ExecuteScalar<int>(PERSON_SQL, new
{
LastName = _entity.Lastname,
FirstName = _entity.Firstname
});
I would like to print out actual SQL query with parameter values for debugging purposes. I am sure there is some extension or helper function for it...
Dapper doesn't include that functionality itself, the authors tend to use MiniProfiler for capturing SQL queries (see Marc Gravell's answer about something similar).
You could also use SQL Profiler, presuming you're using a SQL database.
Finally, if nothing "off the shelf" suits your needs, you could wrap the database connections and commands that you use with Dapper and capture / log the queries (and parameters) when ExecuteReader, ExecuteScalar, etc.. are called. I had some sample code for this in my answer to a question someone had about using Dapper with Access (though the sample code is database-agnostic, so you could use the "WrappedDbConnection" with whatever database you are using at the moment).

How does separated clause and args protect against SQL injection? [duplicate]

This question already has answers here:
How can prepared statements protect from SQL injection attacks?
(10 answers)
Closed 8 years ago.
I heard that separated SQL clause and args can protect against SQL injection. For example,
clause = SELECT * WHERE ID = ? AND NAME = ?
with ID = 23, and NAME = "Tom".
Can someone explain to me how it works?
Basically, you're making the distinction between data and the actual code (query part) very clear. You're telling the SQL server: this is clearly data and this is clearly code.
This way, you're basically skipping the part where the server has to pull apart the code and data from your query so there's no chance the server can misinterpret bits of data as part of your query.
Edit: as per the link in the comments, this answer pretty much answers your question much better than I've explained here.

what is use of question mark in sql [duplicate]

This question already has answers here:
What is the question mark's significance in MySQL at "WHERE column = ?"?
(4 answers)
What does a question mark represent in SQL queries?
(6 answers)
Closed 9 years ago.
I was just surfing the net and found a query something like:
sql = "select milk_rate from special_milk_rate
where code_producer_id=? and effective_from <= ?
and effective_till >= ?"
what exactly this query means i means what is the use of ? in this statement.
and one thing more what is use of & in sql.
This usually implies a prepared statement, where the parameters are filled in later. (see e.g. http://en.wikipedia.org/wiki/Prepared_statements#Parameterized_statements).
what exactly this query means i means what is the use of ? in this statement.
The question marks are for parameters.
and one thing more what is use of & in sql.
& is a bitwise AND operator in sql
The question marks are supposed to contain the actual parameters.
E.g.
"select milk_rate from special_milk_rate
where code_producer_id=2 and effective_from <= '20101231'
and effective_till >= '20110124'"
& usually denotes a variable or substitution value which you may be prompted for at run time
Here is nice article:
http://publib.boulder.ibm.com/infocenter/idshelp/v10/topic/com.ibm.sqls.doc/sqls610.htm#sii-02prep-18104
In some statements, parameters are
unknown when the statement is prepared
because a different value can be
inserted each time the statement is
executed. In these statements, you can
use a question-mark ( ? ) placeholder
where a parameter must be supplied
when the statement is executed.
Question marks are found in prepared statements, meaning it is parametrized and can be called again and again without having to reconstruct the whole sql statement, just by changing the parameters. Some frameworks use those that together with SqlCommands. Those encapsulate escaping and prevent sql injection attacks.
Some frameworks also allow named parameters.

How do I deal with quotes ' in SQL [duplicate]

This question already has answers here:
How to anticipate and escape single quote ' in oracle
(2 answers)
Closed 7 years ago.
I have a database with names in it such as John Doe etc. Unfortunately some of these names contain quotes like Keiran O'Keefe. Now when I try and search for such names as follows:
SELECT * FROM PEOPLE WHERE SURNAME='O'Keefe'
I (understandably) get an error.
How do I prevent this error from occurring. I am using Oracle and PLSQL.
The escape character is ', so you would need to replace the quote with two quotes.
For example,
SELECT * FROM PEOPLE WHERE SURNAME='O'Keefe'
becomes
SELECT * FROM PEOPLE WHERE SURNAME='O''Keefe'
That said, it's probably incorrect to do this yourself. Your language may have a function to escape strings for use in SQL, but an even better option is to use parameters. Usually this works as follows.
Your SQL command would be :
SELECT * FROM PEOPLE WHERE SURNAME=?
Then, when you execute it, you pass in "O'Keefe" as a parameter.
Because the SQL is parsed before the parameter value is set, there's no way for the parameter value to alter the structure of the SQL (and it's even a little faster if you want to run the same statement several times with different parameters).
I should also point out that, while your example just causes an error, you open youself up to a lot of other problems by not escaping strings appropriately. See http://en.wikipedia.org/wiki/SQL_injection for a good starting point or the following classic xkcd comic.
Oracle 10 solution is
SELECT * FROM PEOPLE WHERE SURNAME=q'{O'Keefe}'
Parameterized queries are your friend, as suggested by Matt.
Command = SELECT * FROM PEOPLE WHERE SURNAME=?
They will protect you from headaches involved with
Strings with quotes
Querying using dates
SQL Injection
Use of parameterized SQL has other benefits, it reduces CPU overhead (as well as other resources) in Oracle by reducing the amount of work Oracle requires in order to parse the statement. If you do not use parameters (we call them bind variables in Oracle) then "select * from foo where bar='cat'" and "select * from foo where bar='dog'" are treated as separate statements, where as "select * from foo where bar=:b1" is the same statement, meaning things like syntax, validity of objects that are referenced etc...do not need to be checked again. There are occasional problems that arise when using bind variables which usually manifests itself in not getting the most efficient SQL execution plan but there are workarounds for this and these problems really depend on the predicates you are using, indexing and data skew.
Input filtering is usually done on the language level rather than database layers.
php and .NET both have their respective libraries for escaping sql statements. Check your language, see waht's available.
If your data are trustable, then you can just do a string replace to add another ' infront of the ' to escape it. Usually that is enough if there isn't any risks that the input is malicious.
I suppose a good question is what language are you using?
In PHP you would do: SELECT * FROM PEOPLE WHERE SURNAME='mysql_escape_string(O'Keefe)'
But since you didn't specify the language I will suggest that you look into a escape string function mysql or otherwise in your language.
To deal quotes if you're using Zend Framework here is the code
$db = Zend_Db_Table_Abstract::getDefaultAdapter();
$db->quoteInto('your_query_here = ?','your_value_here');
for example ;
//SELECT * FROM PEOPLE WHERE SURNAME='O'Keefe' will become
SELECT * FROM PEOPLE WHERE SURNAME='\'O\'Keefe\''
Found in under 30s on Google...
Oracle SQL FAQ