How can this SQL query code be broken/exploited by user input? [duplicate] - sql

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Can I protect against SQL Injection by escaping single-quote and surrounding user input with single-quotes?
We have a legacy app that doesn't do queries using positional parameters, and there's SQL everywhere. It was decided (before I started here) that since user input can contain apostrophes, every string input should be manually escaped for those apostrophes.
Here is the essential original code (not written by me), translated into C# for easier consumption:
private string _Escape(string input)
{
return input.Replace("'", "''");
}
private bool _IsValidLogin(string userName, string password)
{
string sql =
string.Format
(
#"SELECT COUNT(*) FROM UserAccounts
WHERE UserName = '{0}' AND Password = '{1}'",
_Escape(userName),
_Escape(password)
);
// ...
}
This really seems like it can be broken in some way, but I'm at a loss as to how it could be exploited by user input. Assume user input is unfiltered until it hits _IsValidLogin, and forget that passwords appear to be stored in plain text.
The solution to shore it up for good is obvious -- use positional parameters -- but I need some ammunition to demonstrate to management why/how this code is insecure so time/$ can be allocated for it to get fixed.
Note: I'm assuming this can be broken, but that may not actually be the case. I'm not a SQL superstar.
Note 2: I've expressed this question as database-agnostic, but if you can exploit this code for a certain engine, I welcome your contribution.

It could be exlpoited by backslashes.
password = foo\' OR 1=1 --
becomes:
password = foo\'' OR 1=1 --
the query:
"SELECT COUNT(*) FROM UserAccounts
WHERE UserName = '{0}' AND Password = 'foo\'' OR 1=1 --'"
-- Is the comment mark in this example.
The solution assumes the program only filters (duplicates) apostrophes.

Well, I can't see a way it's vulnerable. So, let's argue a different reason why it should be changed --- it's rather ineffiecent. In MSSQL (and, I think, most other high end SQL servers), queries are parsed, and execution plan is devised, and then the query and plan are stored. If an exact copy of the query is requested again, the saved execution plan is used. Parameter don't affect this, so if you use parameters, it will reuse the plans; if you embed the text, it never will.

Related

How do I prevent my SQL statements from SQL injection when using CLR/C++ with multiple variables?

I am having a major problem where I do not know how to prevent SQL injection when writing SQL statements in CLR/C++
Below is the code
String^ sqlstr = "SELECT * FROM ";
sqlstr += tableName + " WHERE " + field + " = " + fieldEntity;
I need to be able to input correct SQL Injection preventions to this statement.
Background code
class database
{
protected:
string fieldEntity;
string tableName;
string field;
...
____
OleDbDataReader^ openData(String^ fieldEntity, String^ field, String^ tableName)
{
String^ sqlstr = "SELECT * FROM ";
sqlstr += tableName + " WHERE " + field + " = " + fieldEntity;
...
___
OleDbDataReader^ reader2 = testData.openData(effectID, "effectID", "effectOnUser");
while (reader2->Read())
{
Object^ dHealthptr = reader2["effectOnHealth"];
Object^ dTirednessptr = reader2["effectOnTiredness"];
Object^ dHappinessptr = reader2["effectOnHappiness"];
...
There are two ways to prevent SQL Injection and the environment of SQLCLR does not change this:
The preferred mechanism is by using parameterized queries. Different languages and libraries go about this in different ways, but at the very least you should be able to use prepared statements. Please note that this does not apply to scenarios that could not accept a variable, such as with tableName and field in your code.
Please see:
Issuing a Parameterized Query
Using Stored Procedures
Sanitize the inputs:
Bare minimum, and by far the most common, requirement is to escape single quotes by doubling them (i.e. ' becomes '')
Additionally (below is a quote from a related answer of mine on DBA.StackExchange):
There is a lesser known type of attack in which the attacker tries to fill up the input field with apostrophes such that a string inside of the Stored Procedure that would be used to construct the Dynamic SQL but which is declared too small can't fit everything and pushes out the ending apostrophe and somehow ends up with the correct number of apostrophes so as to no longer be "escaped" within the string. This is called SQL Truncation and was talked about in an MSDN magazine article titled "New SQL Truncation Attacks And How To Avoid Them", by Bala Neerumalla, but the article is no longer online. The issue containing this article — the November, 2006 edition of MSDN Magazine — is only available as a Windows Help file (in .chm format). If you download it, it might not open due to default security settings. If this happens, then right-click on the MSDNMagazineNovember2006en-us.chm file and select "Properties". In one of those tabs there will be an option for "Trust this type of file" (or something like that) which needs to be checked / enabled. Click the "OK" button and then try opening the .chm file again.
So, be sure to properly size the string input parameters. You don't need VARCHAR(500) for a column that is declared as VARCHAR(25). Please see my answer on DBA.StackExchange for more details and examples:
Why does SQL Injection not happen on this query inside a stored procedure?
For tableName and field variables, those are being used as SQL identifiers in your query. You can't use either common method of query parameters or escaping. You just have to make sure to whitelist the values for those variables. In other words, check them against known identifiers of tables and columns in your database.
For the other variable fieldEntity, I suppose this should be used like a constant value in your SQL query. You can protect this from SQL injection by using a query parameter.
I don't know CLR, but there are lots of examples of using SQL query parameters in C++ or C#.
https://owasp.org/www-project-cheat-sheets/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html

use variable as expression (condition) in informatica powercenter

IC=IC
ACC=ACC
v_statement='ACC = '1052502',0.035,IC = 'IC130',0.0675'
v_decode_out=DECODE(TRUE,v_statement,0)
i am getting error
is the above expression correct.Is there anyway we can achieve this
There are two problems in your query
First, the v_statement variable you have written won't be validated. If you
really want to write a string in this format, then use pipes to append as
'ACC='||1052502||','||0.035||'IC='||'IC130'||','||'0.0675'
Note that you cannot loop quotes.
Second, the reason your decode statement wont work is because of the data type mismatch. True is a boolean value and v_statement is a string. Any variable expansion would happen during run time but not before that. So, informatica does not allow you this kind of decode statement, unless you are comparing some kind of string input/variable with another string or any other data type for that matter
Also, decide on your case
When it is If ACC else IC to be evaluated (this seems to be your case)
v_decode_out=DECODE(ACC,'1052502',0.035,DECODE(IC,'IC130',0.0675))
When it is both ACC and IC together
v_decode_out=DECODE(TRUE,ACC='1052502' and/or IC='IC130',0.035,0.0675)
These are fundamental concepts. It's advisable that you try out everything available on internet before you post a question here, because someone could easily down rate you if they feel that you have not put any effort at all to find an answer yourself.
Cheers!
the v_statement variable you have written won't be validated. If you really want to write a string in this format, then use pipes to append.

Protecting against SQL injection in python

I have some code in Python that sets a char(80) value in an sqlite DB.
The string is obtained directly from the user through a text input field and sent back to the server with a POST method in a JSON structure.
On the server side I currently pass the string to a method calling the SQL UPDATE operation.
It works, but I'm aware it is not safe at all.
I expect that the client side is unsafe anyway, so any protection is to be put on the server side. What can I do to secure the UPDATE operation agains SQL injection ?
A function that would "quote" the text so that it can't confuse the SQL parser is what I'm looking for. I expect such function exist but couldn't find it.
Edit:
Here is my current code setting the char field name label:
def setLabel( self, userId, refId, label ):
self._db.cursor().execute( """
UPDATE items SET label = ? WHERE userId IS ? AND refId IS ?""", ( label, userId, refId) )
self._db.commit()
From the documentation:
con.execute("insert into person(firstname) values (?)", ("Joe",))
This escapes "Joe", so what you want is
con.execute("insert into person(firstname) values (?)", (firstname_from_client,))
The DB-API's .execute() supports parameter substitution which will take care of escaping for you, its mentioned near the top of the docs; http://docs.python.org/library/sqlite3.html above Never do this -- insecure.
Noooo... USE BIND VARIABLES! That's what they're there for. See this
Another name for the technique is parameterized sql (I think "bind variables" may be the name used with Oracle specifically).

SQLiteQueryBuilder.buildQuery not using selectArgs?

Alright, I'm trying to query a sqlite database. I was trying to be good and use the query method of SQLiteDatabase and pass in the values in the selectArgs parameter to ensure everything got properly escaped, but it wouldn't work. I never got any rows returned (no errors, either).
I started getting curious about the SQL that this generated so I did some more poking around and found SQLiteQueryBuilder (and apparently Stack Overflow doesn't handle links with parentheses in them well, so I can't link to the anchor for the buildQuery method), which I assume uses the same logic to generate the SQL statement. I did this:
SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
builder.setTables(BarcodeDb.Barcodes.TABLE_NAME);
String sql = builder.buildQuery(new String[] { BarcodeDb.Barcodes.ID, BarcodeDb.Barcodes.TIMESTAMP, BarcodeDb.Barcodes.TYPE, BarcodeDb.Barcodes.VALUE },
"? = '?' AND ? = '?'",
new String[] { BarcodeDb.Barcodes.VALUE, barcode.getValue(), BarcodeDb.Barcodes.TYPE, barcode.getType()},
null, null, null, null);
Log.d(tag, "Query is: " + sql);
The SQL that gets logged at this point is:
SELECT _id, timestamp, type, value FROM barcodes WHERE (? = '?' AND ? = '?')
However, here's what the documentation for SQLiteQueryBuilder.buildQuery says about the selectAgs parameter:
You may include ?s in selection, which
will be replaced by the values from
selectionArgs, in order that they
appear in the selection.
...but it isn't working. Any ideas?
The doc for SQLiteQueryBuilder.buildQuery also says, "The values will be bound as Strings." This tells me that it is doing the straight-forward thing, which is writing the SQL leaving the ? parameter markers in place, which is what you are seeing, and binding the selectArgs as input parameters.
The ? are replaced by sqlite when it runs the query, not in the SQL string. The first string in the array will go where you see the first ?, and so on, when the query actually executes. I would expect the logged SQL to still have the ? markers.
Probably, your query fails because you are quoting the ?. For example, don't use WHERE ID = '?', just use WHERE ID = ?, and make sure the selectArgs is a string that satisfies the query.
Two things:
The ? substitution will not be done at this point, but only when the query is executed by the SQLiteDatabase.
From what I've seen, ? substitution only works for the right side of comparison clauses. For example, some people have tried to use ? for the table name, which blows up. I haven't seen anyone try using ? for the left side of the comparison clause, so it might work -- I'm just warning you that it might not.

Split SQL statements

I am writing a backend application which needs to be able to send multiple SQL commands to a MySQL server.
MySQL >= 5.x support multiple statements, but unfortunately we are interfacing with MySQL 4.x.
I am trying to find a way (hint: regex) to split SQL statements by their semicolon, but it should ignore semicolons in single and double quotes strings.
http://www.dev-explorer.com/articles/multiple-mysql-queries has a very nice regex to do that, but doesn't support double quotes.
I'd be happy to hear your suggestions.
Can't be done with regex, it's insufficiently powerful to parse SQL. There may be an SQL parser available for your language — which is it? — but parsing SQL is quite hard, especially given the range of different syntaxes available. Even in MySQL alone there are many SQL_MODE flags on a server and connection level that can affect how basic strings and comments are parsed, making statements behave quite differently.
The example at dev-explorer goes to amusing lengths to try to cope with escaped apostrophes and trailing strings, but will still fail for many valid combinations of them, not to mention the double quotes, backticks, the various comment syntaxes, or ANSI SQL_MODE.
As bobince said, regular expressions are probably not going to be powerful enough to do this. They're certainly not going to be powerful enough to do it in any halfway elegant manner. The second link cdonner provided also does not address this; most answers there were trying to talk the questioner out of doing this without semicolons; if he had taken the general advice, then he'd have ended up where you are.
I think the quickest path to solving this is going to be with a string scanner function, that examines every character of the string in sequence, and reacts based on a bit of stored state. Rough pseudocode:
Read in a character
If the character is not special, CONTINUE
If the character is escaped (checking this probably requires examining the previous character), CONTINUE
If the character would start a new string or end an existing one, toggle a flag IN_STRING (you might need multiple flags for different string types... I've honestly tried and succeeded at remaining ignorant of the minutiae of SQL quoting/escaping) and CONTINUE
If the character is a semicolon AND we are not currently in a string, we have found a query! OUTPUT it and CONTINUE scanning until the end of the string.
Language parsing is not any of my areas of experience, so you'll want to consider that approach carefully; nonetheless, it's going to be fast (with C-style strings, none of those steps are at all expensive, save possibly for the OUTPUT, depending on what "outputting" means in your context) and I think it should get the job done.
maybe with the following Java Regexp? check the test...
#Test
public void testRegexp() {
String s = //
"SELECT 'hello;world' \n" + //
"FROM DUAL; \n" + //
"\n" + //
"SELECT 'hello;world' \n" + //
"FROM DUAL; \n" + //
"\n";
String regexp = "([^;]*?('.*?')?)*?;\\s*";
assertEquals("<statement><statement>", s.replaceAll(regexp, "<statement>"));
}
I would suggest seeing if you can redefine the problem space so the need to send multiple queries separated only by their terminator is not required.
Try this. Just replaced the 1st ' with \" and it seems to work for both ' and "
;+(?=([^\"|^\\']['|\\'][^'|^\\']['|\\'])[^'|^\\'][^'|^\\']$)