What is SQL injection? [duplicate] - sql

This question already has answers here:
Closed 13 years ago.
Possible Duplicates:
XKCD sql injection - please explain
What is SQL injection?
I have seen the term "SQL injection" but still do not understand it. What is it?

SQL injection is where someone inserts something malicious into one of your SQL queries.
Let's assume that you have an SQL query like this:
select * from people where name = '<name>' and password = '<password>'
Now let's assume that <name> and <password> are replaced by something someone types on your webpage. If someone typed this as their password...
' or '' = '
...then the resulting query would be:
select * from people where name = 'someone' and password = '' or '' = ''
...which was clearly not your intent. You can read more about it here.

SQL Injection is where an attacker is able to manipulate the data they send you in a manner that fools your program to using some of it as SQL commands.
For examples you could visit here

When you build an SQL query it usually contain all sort of bits and fragments, some of which come from user input. For example, if you have a "Search Book" facility in your app, then the name of the book is a string coming from the user.
Smart, evil users can manipulate the inputs that they send to your app such that the SQL query built from this input will be harmful.
So if you build your query like this:
String q = "Select * from books where name='" + bookName + "'"
Then a hacker can search for a book called "x'; delete from books where name like '%"
The net result will be that the following query will be executed:
Select * from books where name='x'; delete from books where name like '%'
This will delete all records of the book table. The standard way to avoid this is to always use prepared statements when building queries that include user-supplied pieces.

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.

Will it avoid SQL Injections by not allowing sql keywords in params?

I know that sanitizing parameters (removing quotes for example) is not a perfect solution against SQL injection when you can't use setParameters().
But is it safe to sanitize parameters by checking if they (parameters) don't contain strings with an empty space after it as you see below???
'DELETE ', 'ALTER ', 'DROP ', 'SELECT ', 'TABLE '
For example, email parameter was passed to server but it contains DROP keyword:
String param = "john#mail'DROP myTable"
SELECT * from Users where email = 'john#mail'DROP mytable'
So, my table is dropped;
Notice the space I left after each keyword. This way if a data in db contain the listed keywords but without space, then it will be allowed to use, otherwise it should be a hacker trying to harm my data (ALTER TABLE mydb).
Please feel free to add as example any SQL engine: SQL, Oracle, HANA, MySQL
Thanks
No this is not sufficient.
Please follow the industry standards for preventing SQL Injection that are laid out by OWASP.
One obvious example of SQL injection for the query you posted would be if someone provided the following input for user:
john#mail' OR '1' = '1
Which would produce the query:
SELECT * from Users where email = 'john#mail' OR '1' = '1'
They could also inject a UNION to start selecting data from other tables. There are probably even more devastating examples.
The bottom line is never try to "roll your own" SQL Injection protection. Much smarter people than you and I have tried to solve this problem and the currently accepted standard of using parameterized queries is simply the best solution we currently have available.

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).

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

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);"

Constructing sql in ruby on rails

The following SQL I am trying to run is returning sql_string of "SELECT id FROM people WHERE id IN ("16")":
#ids = ["1", "6"]
sql_string = <<-SQL
SELECT id
FROM people
WHERE id IN ("#{#ids}")
SQL
Can someone please help modify the above query so it will create the sql_string of "SELECT id FROM people WHERE id IN (1, 6)"
Just throwing #ids in the query will concatenate the array and give you "16". You'll want to run #ids.join(',') to comma separate them. Plus you need to wrap the expression part of the string in #{}. Otherwise it will treat it as literal.
#ids = ["1", "6"]
sql_string = <<-SQL
SELECT id
FROM people
WHERE id IN (#{#ids.join(',')})
SQL
P.S. There are very few valid reasons for manually writing a whole SQL query in Rails. You should look into using ActiveRecord to do something like People.find_all_by_id(#ids) instead.
With the code fragment in one of the answers above, "#ids" is not sanitised. This is fine if your code 'knows' that "#ids" contains only valid integer IDs, but very dangerous if any ID came in from user input or a URL. See:
http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M001831
...for a possible solution. This is a protected method so we have to call via 'send' to demonstrate its use at the console:
>> ActiveRecord::Base.send(:sanitize_sql_for_conditions, { :id => [1,6] }, :people)
=> "people.\"id\" IN (1,6)"
...i.e. insert the above result after the SQL WHERE keyword. As the previous answer says, unless you have a really complex case which can't be built up using standard Rails calls (which is indeed the case for Coderama but may not be for future readers), you should always try to avoid writing SQL by hand.
Bearing this in mind, an alternative way to build up complex queries is the "ez_where" plugin which is worth a look if anyone reading is thinking of resorting to SQL:
http://github.com/ezmobius/ez-where