How to change symbol in string using c# - c#

My C# application is able store the data into a SQL Server database. Currently I have to problem when user insert symbol ' in their string/sentences:
Example: I want to 'test' your system
So, when inserting into db the ' symbol will return an error while inserting by using sql query.
My query example :
INSERT INTO TABLE_NAME (POST_BODY)
VALUES ('i want to 'test' your system')
and then my plan here is to change that check the string if contains that ' symbol it will change to " symbol.
I have try using this code, but cannot:
void ChangeSymbol(String str)
{
Console.WriteLine("\"{0}\"", str);
Console.WriteLine("\"{0}\"", str.Replace(''', '"'));
}
Please anybody help to give some idea to face this problem. Thanks in advance.

There is no problem inserting a single quote into a database using SQL code. If you want to insert a text literal then you simply escape the single quote with another single quote, e.g.
INSERT INTO MyTable (GivenName, FamilyName) VALUES ('James', 'O''Connell')
If you're inserting a separate value into a SQL statement then you should be using parameters no matter the data type, so an issue with single quotes never arises, e.g.
mySqlCommand.CommandText = "INSERT INTO MyTable (GivenName, FamilyName) VALUES (#GivenName, #FamilyName)";
mySqlCommand.Parameters.AddWithValue("#GivenName", givenName);
mySqlCommand.Parameters.AddWithValue("#FamilyName", familyName);

Use parameter binding. I don't have a sample code to put in since we dont use MSSQL
here's a sample
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters(v=vs.110).aspx

You escape single quotes by doubling them. So try this:
string example = "I want to ''test'' your system";

Related

SQLInjection with Npgsql/Postgres

I want to learn how SQLInjection is working with the PostgresqlDb. I am using the Npgsql in C#.
So this is my Query, which is called, when I rename a folder:
cmd.CommandText = "UPDATE allfolder.folder SET folder_name = '" + foldernamenew + "'";
cmd.ExecuteNonQuery();
I now tried to pass the following value into the textfield:
abcdef; INSERT INTO allfolder.folder (id, folder_name) VALUES (56,"aaaaaaa");
Then AJAX is fired.
The output I assumed is, that all folders in the table has the folder_name "abcdef" and that I have a new folder with the id "56" called "aaaaaa". This is not the case, because the semicolon is not recognized as delimiter and so the name of each folder_name are "abcdef; INSERT INTO ....". I do not want to change it on DB side that multiqueries are allowed.
So my questions are:
How do I need to prepare the SQL statement, that I achieve a Injection?
Is an injection even possible, when you are not allowed to execute a second qry because the semicolon isn't recognized?
I am only talking about Npgsql and postgres.
As Laurenz mentioned above, this should work:
abcdef'; INSERT INTO allfolder.folder (id, folder_name) VALUES (56,'aaaaaaa'); -- test
Make sure, that you don't mix single and double quotes. A common mistake in SQL. You need the single quote before the semicolon, otherwise it is in the textstring, because you have no delimiter.
“Multiqueries” (several queries in one line, separated by semicolon) are always allowed in PostgreSQL.
Your problem are the multiple errors in your SQL:
Missing single quote after abcdef.
Double quotes instead of single quotes around aaaaaaa.
No single quote or line comment at the end of the statement.
Speaking pointedly: you have to learn SQL before you can learn SQL injection.

Invalid Character inserting row in Oracle C#

I have a small test to insert some values in a table (Oracle) from C# the thing is that I have a sql sentence (all types are numbers except for the date):
insert into historicos values (2,1,1,to_date('01/08/2013','dd/mm/yyyy'), 0,1,25,25,36);
I've tried many forms to insert (switching commas, changing functions, etc...)
I can insert with that sql command if I paste it in the SQLDeveloper, but when I try to execute that command from C# i get an ORA-00911 Invalid character
Do you know where's the problem? Thank you so much
Do not forgot removing " ; " at end of the query...

I want to store apostrophe in message box such as john's watch.It show erreor near 's

Please help me to store apostrophe. I m creating a website (C#, .net, SQL Server) and want to have a message box for the users but the problem is that when I inserts any message such as John's it shows an error near ''s'.
Please tell me how could I store apostrophe in database
I used nvarchar, varchar and everything but failed to store apostrophe containing messages.
A general solution is to write message with double apostrophe but this is not a solution for a website
You are open for SQL-Injection. Don't concatenate strings to build your query. Instead use SQL-Parameters. That also makes your code more readable and prevents errors like yours.
Here's an example:
int amt;
using (var con = new SqlConnection(ConnectionString)) {
var sql = "INSERT INTO dbo.Message(UserID, Message) VALUES(#UserID, #Message);";
using (var cmd = new SqlCommand(sql, con)) {
cmd.Parameters.AddWithValue("#UserID", userID); // passed as argument
cmd.Parameters.AddWithValue("#Message", txtMessage.Text); // f.e. "John's"
con.Open();
int inserted = cmd.ExecuteNonQuery();
}
}
The same works also with other sql like UPDATE commands.
The problem is that you need to escape Apostrophe by another Apostrophe.
For example have a look at:http://sqlfiddle.com/#!3/d2f75/1
CREATE TABLE tblTEst( col1 NVARCHAR(50))
INSERT INTO tblTest
(Col1)
SELECT 'John''s'
The best solution is to use a prepared statement (or whatever the equivalent in C# is) where your SQL only contains placeholders and you pass the actual values through a different method.
In a character literal, the single quote ' can be used by simply doubling it:
insert into foo (bar)
values
('John''s');
use CHAR(39)between john & s like this: 'john'+CHAR(39)+'s'

C# ODBC Exception Incorrect String value

I am using C# to parse a chat log and insert messages into a database.
When trying to insert the string "Don't worry, it's unloaded"
(with the double quotes) it gives me the following exception:
System.Data.Odbc.OdbcException: ERROR [HY000] [MySQL][ODBC 5.1 Driver][mysqld-5.5.11]Incorrect string value: '\xEF\xBB\xBF it...' for column 'msg' at row 1
at void System.Data.Odbc.OdbcConnection.HandleError(OdbcHandle hrHandle, RetCode retcode)
The database is using latin-1 default collation for the encoding scheme.
I have tried switching to utf-8 but this gave me the error on the same line.
Not sure what it means to your specific error, but EF BB BF is the UTF BOM character which could be causing an issue.
This answer pointed out that the client connection needs to be set to the proper character set as well. It could be that the C# client character isn't matching the MySQL encoding.
Depending on your chosen way to insert data (I assume by building the SQL directly), the ' character needs to be escaped. That's because ' is string delimiting character in most databases.
What you need to insert is "Don''t worry, it''s unloaded", with the single quotes escaped by doubling them.
!Important: You need to be careful about raw using raw SQL as it can easily create security holes that can SQL injection. Use parametrized queries whenever possible or fully escape the query sent to the server.
Don't forget that if you're constructing the SQL statement (don't! -- use a parameterized query instead), if the construct winds up looking like:
insert foo ( bar ) values( "This is my data" )
The insert will fail because the double quote introduces a quoted column name. It is not the same as a string literal which is quoted with the apostrophe (').
User SQL Parameters instead of using raw sql. There can be SQL Injection security issue and these sort of issues.
See how to use sql parameters mysql-c#
Eg:
MySqlCommand mySqlCommand1;
...
mySqlCommand1.CommandText = "INSERT INTO dept (deptno, dname, desc) VALUES (?, ?, ?)";
mySqlCommand1.Parameters.Add("param1", 30);
mySqlCommand1.Parameters.Add("param2", "SALES");
mySqlCommand1.Parameters.Add("param3", #"Don''t worry, it''s unloaded");

How to escape simple SQL queries in C# for SqlServer

I use an API that expects a SQL string. I take a user input, escape it and pass it along to the API. The user input is quite simple. It asks for column values. Like so:
string name = userInput.Value;
Then I construct a SQL query:
string sql = string.Format("SELECT * FROM SOME_TABLE WHERE Name = '{0}'",
name.replace("'", "''"));
Is this safe enough? If it isn't, is there a simple library function that make column values safe:
string sql = string.Format("SELECT * FROM SOME_TABLE WHERE Name = '{0}'",
SqlSafeColumnValue(name));
The API uses SQLServer as the database.
Since using SqlParameter is not an option, just replace ' with '' (that's two single quotes, not one double quote) in the string literals. That's it.
To would-be downvoters: re-read the first line of the question. "Use parameters" was my gut reaction also.
EDIT: yes, I know about SQL injection attacks. If you think this quoting is vulnerable to those, please provide a working counterexample. I think it's not.
I was using dynamic sql (I can hear the firing squad loading their rifles) for search functionality, but it would break whenever a user searched for somebody with a surname like "O'Reilly".
I managed to figure out a work-around (read "hack"):
Created a scalar-valued function in sql that replaced a single quote with two single quotes, effectively escaping the offending single quote, so
"...Surname LIKE '%O'Reilly%' AND..."
becomes
"...Surname LIKE '%O''Reilly%' AND..."
This function gets invoked from within sql whenever I suspect fields could contain a single quote character ie: firstname, lastname.
CREATE FUNCTION [dbo].[fnEscapeSingleQuote]
(#StringToCheck NVARCHAR(MAX))
RETURNS NVARCHAR(MAX)
AS
BEGIN
DECLARE #Result NVARCHAR(MAX)
SELECT #Result = REPLACE(#StringToCheck, CHAR(39), CHAR(39) + CHAR(39))
RETURN #Result
END
Not very elegant or efficient, but it works when you're in a pinch.
One may wish to replace ' with '' instead of parameterizing when needing to address the ' problem in a large amount of ad hoc sql in a short time with minimal risk of breakage and minimal testing.
SqlCommand and Entity Framework use exec sp_executesql....
So there really is an alternative to raw strings with your own escaping pattern presumably. With SqlCommand you are technically using parameterised queries but you're bypassing the ADO.Net abstraction of the underlying SQL code.
So while your code doesn't prevent SQL Injection, the ultimate answer is sp_executesql not SqlCommand.
Having said that, I'm sure there are special handling requirements for generating an SQL Injection-proof string which utilizes sp_executesql.
see: How to return values from a dynamic SQL Stored Procedure to the Entity Framework?
Simple:
const string sql = "SELECT * FROM SOME_TABLE WHERE Name = #name";
and add the #name parameter with value:
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("#name", name);
If you need to escape a string for a MSSQL query try this:
System.Security.SecurityElement.Escape(Value)

Categories

Resources