How to get around the ' (quote) problem when saving text using SQL - asp.net

I've a textbox that I save to a SQL Database using ASP.NET C#.
The problem is using quotes, for instance with words like he's and it's. When you save it, I get an SQL error.
From experience to get around the issue, I use to use replace command to find all occurances of quotes and replace them with another character. Then if I was to read the database and the text that was previously saved, I'd replace again.
Is there a better of doing this? Or do you still have to use this 'old' way.

Use parametrized queries.
Using replace is dangerous and can lead to unintentional SQL injection vulnerabilities.

Always use parameterized queries. Never concatenate strings together (with un-sanitised input information) to create SQL on the fly. You run the risk of being vulnerable to SQL-injection attacks.
Read the following guide carefully:
http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson06.aspx
And when you understand the following comic strip, you are ready to code:
http://xkcd.com/327/

As the other answers point out, the correct answer here is to use parameterized queries.
However, this is sometimes not possible. In these cases, you're better off doubling the quotes:
String str = "he's";
str = str.Replace("'", "''");

There's two ways to get around this issue:
Use a parameterised query, e.g. in http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson06.aspx - this will also help avoid basic SQL injection if you're worried about that
Create 2 new functions, one to double up every apostrophe, so that it's saved into the database correctly, and another to remove extra apostrophes when retrieving data from the database.
I would recommend the first method as it's a lot cleaner (and safer) in my opinion. If you're using C# for your ASP.NET you can do things like in my below example:
string clientName = "Test client";
SqlCommand sqlCommand = new SqlCommand("SELECT COUNT(*) FROM Client WHERE UPPER(ClientName) = UPPER(#ClientName)", connection);
sqlCommand.Parameters.AddWithValue("#ClientName", clientName);

Related

Error with SQLite query, What am I missing?

I've been attempting to increase my knowledge and trying out some challenges. I've been going at this for a solid two weeks now finished most of the challenge but this one part remains. The error is shown below, what am i not understanding?
Error in sqlite query: update users set last_browser= 'mozilla' + select sql from sqlite_master'', last_time= '13-04-2019' where id = '14'
edited for clarity:
I'm trying a CTF challenge and I'm completely new to this kind of thing so I'm learning as I go. There is a login page with test credentials we can use for obtaining many of the flags. I have obtained most of the flags and this is the last one that remains.
After I login on the webapp with the provided test credentials, the following messages appear: this link
The question for the flag is "What value is hidden in the database table secret?"
So from the previous image, I have attempted to use sql injection to obtain value. This is done by using burp suite and attempting to inject through the user-agent.
I have gone through trying to use many variants of the injection attempt shown above. Im struggling to find out where I am going wrong, especially since the second single-quote is added automatically in the query. I've gone through the sqlite documentation and examples of sql injection, but I cannot sem to understand what I am doing wrong or how to get that to work.
A subquery such as select sql from sqlite_master should be enclosed in brackets.
So you'd want
update user set last_browser= 'mozilla' + (select sql from sqlite_master''), last_time= '13-04-2019' where id = '14';
Although I don't think that will achieve what you want, which isn't clear. A simple test results in :-
You may want a concatenation of the strings, so instead of + use ||. e.g.
update user set last_browser= 'mozilla' || (select sql from sqlite_master''), last_time= '13-04-2019' where id = '14';
In which case you'd get something like :-
Thanks for everyone's input, I've worked this out.
The sql query was set up like this:
update users set last_browser= '$user-agent', last_time= '$current_date' where id = '$id_of_user'
edited user-agent with burp suite to be:
Mozilla', last_browser=(select sql from sqlite_master where type='table' limit 0,1), last_time='13-04-2019
Iterated with that found all tables and columns and flags. Rather time consuming but could not find a way to optimise.

Print sql statement craeted by DBI::dbBind

I want to print the sql syntax created with DBI::dbBind while creating safe parametrized query:
conn <- #create connection
stmt <- "select * from dbo.mytable where mycolumn = ?"
params = list("myvalue")
query <- DBI::dbSendQuery(conn, stmt)
DBI::dbBind(query, params) # how print created sql syntax?
in the last line the sql syntax is created. How to view it?
I'll formalize my comment into an answer.
"Binding" does not change the query, it merely "augments" a query with objects that are treated solely as data, vice intermingled with code.
The latter intermingling can be problematic for a few reasons:
Malevolent code deploying "SQL Injection" (https://xkcd.com/327/, and a wiki explanation). In short, it takes advantage of closing out a quoted string or literal and executing SQL code directly, perhaps to delete or modify data, perhaps to extract data.
Innocently enough, if the "data" you add to the query contains quotes that are not escaped properly, you could inadvertently perform your own SQL injection, though perhaps less likely to do as "Bad Things" as #1 would do.
Optimization of SQL code. Most DBMSes will analyze and optimize a SQL query so that it performs better, takes advantage of keys, etc. They often remember queries, so that a repeated query does not need to be re-analyzed, saving time. If you intermingle data/parameters in with the raw SQL query text, then when you change one thing about it (even just one digit in a parameter), the DBMS will likely need to re-analyze the query. Inefficient.
There are functions that facilitate escaping or quoting literals and strings, and if you feel you must put literals in your SQL query, then I urge you to use them. These include (but are not limited to) DBI::dbQuoteString, DBI::dbQuoteLiteral, and DBI::dbQuoteIdentifier.
Another such function is glue::glue_sql, which handles correct quoting/escaping of literals and identifiers, to "make[s] constructing SQL statements safe and easy" (quoted from the github repo). This is "just" string interpolation, so while it should protect you just fine against #1 and #2 above, it does not necessarily permit/encourage #3.
(It only takes one mis-quoting to remind you which is used where for your particular DBMS.)
For the record, binding is rather simple, as provided in its documentation:
iris_result <- dbSendQuery(con, "SELECT * FROM iris WHERE [Petal.Width] > ?")
dbBind(iris_result, list(2.3))
results <- dbFetch(iris_result)
If you want, you can re-use the same res (at least in some DBMSes, not tested on all), as in
# same iris_result as above
dbBind(iris_result, list(2.5))
dbFetch(iris_result)
dbBind(iris_result, list(3))
dbFetch(iris_result)
dbBind(iris_result, list(3.2))
dbFetch(iris_result)
As many times as you need, ultimately finishing with
DBI::dbClearResult(iris_result)

Constructing a good search query using system.data.oracleclient

I am constructing a search function in a class to be used by several of our asp pages. The idea is simple, take a search term from the user and query the database for the item. Currently I am doing this the wrong way, which is vulnerable to SQL injection attacks (and ELMAH is in there to save the day if something goes wrong):
Public Shared Function SearchByName(ByVal searchterm As String) As DataTable
SearchByName = New DataTable
Dim con As New OracleConnection(System.Configuration.ConfigurationManager.ConnectionStrings("OracleDB").ConnectionString)
Try
con.Open()
Dim SqlStr As String = "select ID_ELEMENT, ELEMENT_NAME from table_of_elements where upper(ELEMENT_NAME) like upper('%" & searchterm & "%')"
Dim cmd As New OracleCommand(SqlStr, con)
SearchByName.Load(cmd.ExecuteReader)
Catch ex As Exception
Elmah.ErrorSignal.FromCurrentContext().Raise(ex)
End Try
con.Close()
con.Dispose()
Return SearchByName
End Function
String concatenation is BAD. Next thing you know, Bobby Tables wrecks my system.
Now, the correct way to do this is to to make a proper oracle variable, by putting :searchterm in the string and adding the following line:
cmd.Parameters.Add(New OracleParameter("SEARCHTERM", searchterm))
The problem is since I am using a like statement, I need to be able to have % on either side of the search word, and I can't seem to do that with '%:searchterm%', it just gives an error of ORA-01036: illegal variable name/number.
Can I parameterize but still have my flexible like statement be a part of it?
Instead of doing the concatenation in your VB code, do the concatenation in the SQL statement. Then what you're trying to do should work. Here's some SQL illustrating what I'm talking about:
select ID_ELEMENT, ELEMENT_NAME
from table_of_elements
where upper(ELEMENT_NAME) like ('%' || upper(:searchterm) || '%')
BTW, you might end up with more efficient queries if you switch the collation on ELEMENT_NAME to case-insensitive and then remove the calls to upper().
Since you're using oracle, another option would be to use Oracle Text to perform the search.
It can take a bit to set up properly, but if you have a large amount of text to search, or have some sort of structured data, it can offer you many more options than a simple wild-card comparison.
It also has some nice features for dealing with multiple languages, if you happen to have that problem as well.

SQL statement merging/simplifying

I'm not sure whether my SQL code and practise here is any good, so hopefully someone could enlighten me. In order to try and separate my DAL from the Business layer, I'm not using an SQLDataSource on the page. Instead, I've created a gridview to display the results and called an SQL command to retrieve results. I have the following SQL command:
string CommandText = "SELECT User.FName + User.Surname, Product.Name, Product.Quantity, Product.Price FROM User, Products WHERE Product.UserID = User.UserID";
The results are then loaded into a datareader and bound to the gridview control. This works fine. However, is the SQL statement inefficient? I've noticed some SQL statements have square brackets around each field, but when I try and put it around my fields, no results are displayed.
I'm also trying to merge the firstname and surname into one column, with a space between them, but the above doesn't put a space between them, and I can't seem to add a space in the SQL statement.
Finally, this all occurs in the code-behind of the shopping-cart page. However, is it insecure to have the connectionstring and above SQL statement in the codebehind? My connectionstring is encrypted within the web.config file and is called via the Configuration API.
Thanks for any help.
Firstly, using square brackets is optional in most cases (IIRC, there are very few instances where they are actually necessary, such as using keywords in the statement). Square brackets go around each identifier, for example,
SELECT [Server_Name].[Database_Name].[Table_Name].[Field_Name], ...
Secondly, to add a space, you can use SELECT User.FName + ' ' + User.Surname. You also might want to alias it - SELECT User.FName + ' ' + User.Surname AS [name]
Thirdly, keep the connection string in the web.config and encrypt it using a key.
Finally, you may want to consider introducing a data access layer into the project that can return objects from your datasource (might be worth having a look at NHibernate, LINQ to SQL or Entity Framework for this). You can then bind a collection of objects to your GridView.
Long time no SQL usage, but I don't see a problem with your query, as long as the database is designed well. To concatenate two string columns use something like this:
User.FName + ' ' + User.Surname AS UserName
Simply add a space between two strings.
As for security concerns: all other people can see is a rendered web page. If you don't expose connection string nor queries in the rendered HTML/JS code (like in comments etc.), you should not worry. The connection string stored in web.config and database structure visible in queries in server code are safe as long as the server is safe.
Try this:
string CommandText = "SELECT
User.FName + ' ' + User.Surname AS Fullname,
Product.Name,
Product.Quantity,
ProductDetail.Price
FROM
User, Products
WHERE
Product.UserID = User.UserID";
Best wishes,
Fabian

Are Parameters really enough to prevent Sql injections?

I've been preaching both to my colleagues and here on SO about the goodness of using parameters in SQL queries, especially in .NET applications. I've even gone so far as to promise them as giving immunity against SQL injection attacks.
But I'm starting to wonder if this really is true. Are there any known SQL injection attacks that will be successfull against a parameterized query? Can you for example send a string that causes a buffer overflow on the server?
There are of course other considerations to make to ensure that a web application is safe (like sanitizing user input and all that stuff) but now I am thinking of SQL injections. I'm especially interested in attacks against MsSQL 2005 and 2008 since they are my primary databases, but all databases are interesting.
Edit: To clarify what I mean by parameters and parameterized queries. By using parameters I mean using "variables" instead of building the sql query in a string.
So instead of doing this:
SELECT * FROM Table WHERE Name = 'a name'
We do this:
SELECT * FROM Table WHERE Name = #Name
and then set the value of the #Name parameter on the query / command object.
Placeholders are enough to prevent injections. You might still be open to buffer overflows, but that is a completely different flavor of attack from an SQL injection (the attack vector would not be SQL syntax but binary). Since the parameters passed will all be escaped properly, there isn't any way for an attacker to pass data that will be treated like "live" SQL.
You can't use functions inside placeholders, and you can't use placeholders as column or table names, because they are escaped and quoted as string literals.
However, if you use parameters as part of a string concatenation inside your dynamic query, you are still vulnerable to injection, because your strings will not be escaped but will be literal. Using other types for parameters (such as integer) is safe.
That said, if you're using use input to set the value of something like security_level, then someone could just make themselves administrators in your system and have a free-for-all. But that's just basic input validation, and has nothing to do with SQL injection.
No, there is still risk of SQL injection any time you interpolate unvalidated data into an SQL query.
Query parameters help to avoid this risk by separating literal values from the SQL syntax.
'SELECT * FROM mytable WHERE colname = ?'
That's fine, but there are other purposes of interpolating data into a dynamic SQL query that cannot use query parameters, because it's not an SQL value but instead a table name, column name, expression, or some other syntax.
'SELECT * FROM ' + #tablename + ' WHERE colname IN (' + #comma_list + ')'
' ORDER BY ' + #colname'
It doesn't matter whether you're using stored procedures or executing dynamic SQL queries directly from application code. The risk is still there.
The remedy in these cases is to employ FIEO as needed:
Filter Input: validate that the data look like legitimate integers, table names, column names, etc. before you interpolate them.
Escape Output: in this case "output" means putting data into a SQL query. We use functions to transform variables used as string literals in an SQL expression, so that quote marks and other special characters inside the string are escaped. We should also use functions to transform variables that would be used as table names, column names, etc. As for other syntax, like writing whole SQL expressions dynamically, that's a more complex problem.
There seems to be some confusion in this thread about the definition of a "parameterised query".
SQL such as a stored proc that accepts parameters.
SQL that is called using the DBMS Parameters collection.
Given the former definition, many of the links show working attacks.
But the "normal" definition is the latter one. Given that definition, I don't know of any SQL injection attack that will work. That doesn't mean that there isn't one, but I have yet to see it.
From the comments, I'm not expressing myself clearly enough, so here's an example that will hopefully be clearer:
This approach is open to SQL injection
exec dbo.MyStoredProc 'DodgyText'
This approach isn't open to SQL injection
using (SqlCommand cmd = new SqlCommand("dbo.MyStoredProc", testConnection))
{
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter newParam = new SqlParameter(paramName, SqlDbType.Varchar);
newParam.Value = "DodgyText";
.....
cmd.Parameters.Add(newParam);
.....
cmd.ExecuteNonQuery();
}
any sql parameter of string type (varchar, nvarchar, etc) that is used to construct a dynamic query is still vulnerable
otherwise the parameter type conversion (e.g. to int, decimal, date, etc.) should eliminate any attempt to inject sql via the parameter
EDIT: an example, where parameter #p1 is intended to be a table name
create procedure dbo.uspBeAfraidBeVeryAfraid ( #p1 varchar(64) )
AS
SET NOCOUNT ON
declare #sql varchar(512)
set #sql = 'select * from ' + #p1
exec(#sql)
GO
If #p1 is selected from a drop-down list it is a potential sql-injection attack vector;
If #p1 is formulated programmatically w/out the ability of the user to intervene then it is not a potential sql-injection attack vector
A buffer overflow is not SQL injection.
Parametrized queries guarantee you are safe against SQL injection. They don't guarantee there aren't possible exploits in the form of bugs in your SQL server, but nothing will guarantee that.
Your data is not safe if you use dynamic sql in any way shape or form because the permissions must be at the table level. Yes you have limited the type and amount of injection attack from that particular query, but not limited the access a user can get if he or she finds a way into the system and you are completely vunerable to internal users accessing what they shouldn't in order to commit fraud or steal personal information to sell. Dynamic SQL of any type is a dangerous practice. If you use non-dynamic stored procs, you can set permissions at the procesdure level and no user can do anything except what is defined by the procs (except system admins of course).
It is possible for a stored proc to be vulnerable to special types of SQL injection via overflow/truncation, see: Injection Enabled by Data Truncation here:
http://msdn.microsoft.com/en-us/library/ms161953.aspx
Just remember that with parameters you can easily store the string, or say username if you don't have any policies, "); drop table users; --"
This in itself won't cause any harm, but you better know where and how that date is used further on in your application (e.g. stored in a cookie, retrieved later on to do other stuff.
You can run dynamic sql as example
DECLARE #SQL NVARCHAR(4000);
DECLARE #ParameterDefinition NVARCHAR(4000);
SELECT #ParameterDefinition = '#date varchar(10)'
SET #SQL='Select CAST(#date AS DATETIME) Date'
EXEC sp_executeSQL #SQL,#ParameterDefinition,#date='04/15/2011'

Resources