Have I found an SQL injection bug in SQL server? - sql-server-2008

So I was playing with my MS SQL Server 2008 app to see how good it is protected against SQL injections. The app lets users to create views in the database.
Now consider the following:
create view dbo.[]]; drop database foo--] as select 1 as [hi!]
This creates a view with a name of ]; drop database foo--. It is valid and you can select from it (returns the number 1, obviously).
Strange thing #1:
In SQL Management Studio, the query SELECT [hi!] FROM [dbo].[]]; drop database foo--] is red-underlined as incorrect, claiming that the object name is not valid. Nevertheless, it executes and returns the 1.
Strange thing #2:
Call to OBJECT_ID(']; drop database foo--') yields NULL (which means the object does not exist), but the following query returns information about the view properly:
select * from sys.objects where name = ']; drop database foo--';
Are those bugs or am I missing a point?

You're missing the point. SQL Server can't protect itself against SQL injection - if somebody has direct access to your database then you've already been pwned. It's your application that needs to protect against SQL injection by parameterizing queries, and preventing these kinds of statements from ever making it to the database.

1: that only means the intellisense parser is not up to par witht the finer details of SQL syntax. While it may be an intellisense bug, it is not an injection vector.
2: object_id() accepts multipart names, so it needs the name in quotes if ambiguous: select object_id('[]]; drop database foo--]')

That's like using your key to get into your car and then saying "hey there's a security hole, I'm allowed to steal the radio"

It seems the problem is that you are yourself causing SQL injection by accepting user input and using it as SQL statement text.
The fact that you "properly escaped" the ] (by substituting with ]]) really doesn't matter - it's you allowing the user input to be used as anything else but a value by definition means you allow SQL injection.

Related

Handling SQL request with parameters and avoiding SQL injection

This question is quite open ended. Maybe it doesn't belong here, so sorry in advance if that's the case.
I'm using SQL in a real project for the first time, and I'm having some issues. I'm also using php and javascript.
In the web app I'm currently writing, i do a lot of SQL query to my MySQL database. Each one of these query do a different thing, on different tables, etc.
At the moment, I'm doing the following : each time i do a query in the client side code, I'm passing a parameter I defined myself to the server.
On the server, I wrote a switch on this parameter. So it looks like this :
if (parameter == 1)
/*Query 1*/
else if (parameter == 2)
/*Query 2*/
etc.
It's not very convenient. However, if i use a function writing a SQL query by taking parameters from the client, it would be subject to SQL injection.
So to sum it up : how do i create a SQL query in the most "modular" way possible and still avoid SQL injection ?
I already know about prepared statement, but if i get it right, i can't write a full SQL query with only prepared statement.

Query Mysql to find is a statement is valid (NOEXEC perhaps)

Is there any way in mysql to determine of a sql statement is valid before executing it? (In other word rather than execute the stamens and deal with errors I simply want to know if it is a valid statement)
I notice in Mysql workbench that then I type a query it checks it for validity, so I assume there is a way to do that?
In essence I am trying to "precheck" the sql at runtime to see if it is even valid with actually executing it.
Perhaps using the NOEXEC statement?
You can use something called 'SQL Fiddle', you have to build a schema first and then start running your sql queries, see link below:
http://sqlfiddle.com/

Parameterized OLEDB source query

I am creating an ETL in SSIS in which I which I want my data source to be a restricted query, like select * from table_name where id='Variable'. This variable is what I defined as User created variable.
I do not understand how I can have my source query interact with the SSIS scoped Variable.
The only present options are
Table
Table from variable
SQL Command
SQL command from a variable
What I want is to have a SQL statement having a variable as parameter
Simple. Choose SQL command as the Data Access Mode. Enter your query with a question mark as a parameter placeholder. Then click the Parameters button and map your variable to Parameter0 in the Set Query Parameters dialog:
More information is available on MSDN.
An inferior alternative to #Edmund's approach is to use an Expression on another Variable to build your string. Assuming you have #[User::FirstName] already defined, you would then create another variable, #[User::SourceQuery].
In the properties for this variable, set EvaluateAsExpression to True and then set an Expression like "SELECT FirstName, LastName, FROM Person.Person WHERE FirstName = '" + #[User::FirstName] +"'" The double quotes are required because we are building an SSIS String.
There are two big reasons this approach should not be implored.
Caching
This approach is going to bloat your plan cache in SQL Server with N copies of essentially the same query. The first time it runs and the value is "Edmund" SQL Server will create an execution plan and save it (because it can be expensive to build them). You then run the package and the value is "Bill". SQL Server checks to see if it has a plan for this. It doesn't, it only has one for Edmund and so it creates another copy of the plan, this time hard coded to Bill. Lather-rinse-repeat and watch your available memory dwindle until it unloads some plans.
By using the parameter approach, when the plan is submitted to SQL Server, it should be creating a parameterized version of the plan internally and assumes that all parameters supplied will result in equal costing executions. Generally speaking, this is the desired behaviour.
If your database is optimized for ad-hoc workload (it's a setting turned off by default), that should be mitigated as every plan is going to get parameterized.
SQL Injection
The other big nasty you will run into with building your own string is that you open yourself up to SQL Injection attacks or at the least, you can get runtime errors. It's as simple as having a value of "d'Artagnan." That single quote will cause your query to fail resulting in package failure. Changing the value to "';DROP TABLE Person.Person;--" will result in great pain.
You might think it's trivial to safe quote everything but the effort of implementing it consistently everywhere you query is beyond what your employer is paying you. All the more so since there is native functionality provided to do the same thing.
When using OLEDB Connection manager (with SQL Server Native Client 11.0 provider in my case) you can catch an error like this:
Parameters cannot be extracted from the SQL command. The provider
might not help to parse parameter information from the command. In
that case, use the "SQL command from variable" access mode, in which
the entire SQL command is stored in a variable.
So you need to explicitly specify database name in OLEDB Connection manager properties. Otherwise SQL Server Native Client can use different database name then you mean (e.g. master in MSSQL Server).
For some cases you can explicitly specify database name for each database object used in query, e.g.:
select Name
from MyDatabase.MySchema.MyTable
where id = ?

MySQL Injection - Use SELECT query to UPDATE/DELETE

I've got one easy question: say there is a site with a query like:
SELECT id, name, message FROM messages WHERE id = $_GET['q'].
Is there any way to get something updated/deleted in the database (MySQL)? Until now I've never seen an injection that was able to delete/update using a SELECT query, so, is it even possible?
Before directly answering the question, it's worth noting that even if all an attacker can do is read data that he shouldn't be able to, that's usually still really bad. Consider that by using JOINs and SELECTing from system tables (like mysql.innodb_table_stats), an attacker who starts with a SELECT injection and no other knowledge of your database can map your schema and then exfiltrate the entirety of the data that you have in MySQL. For the vast majority of databases and applications, that already represents a catastrophic security hole.
But to answer the question directly: there are a few ways that I know of by which injection into a MySQL SELECT can be used to modify data. Fortunately, they all require reasonably unusual circumstances to be possible. All example injections below are given relative to the example injectable query from the question:
SELECT id, name, message FROM messages WHERE id = $_GET['q']
1. "Stacked" or "batched" queries.
The classic injection technique of just putting an entire other statement after the one being injected into. As suggested in another answer here, you could set $_GET['q'] to 1; DELETE FROM users; -- so that the query forms two statements which get executed consecutively, the second of which deletes everything in the users table.
In mitigation
Most MySQL connectors - notably including PHP's (deprecated) mysql_* and (non-deprecated) mysqli_* functions - don't support stacked or batched queries at all, so this kind of attack just plain doesn't work. However, some do - notably including PHP's PDO connector (although the support can be disabled to increase security).
2. Exploiting user-defined functions
Functions can be called from a SELECT, and can alter data. If a data-altering function has been created in the database, you could make the SELECT call it, for instance by passing 0 OR SOME_FUNCTION_NAME() as the value of $_GET['q'].
In mitigation
Most databases don't contain any user-defined functions - let alone data-altering ones - and so offer no opportunity at all to perform this sort of exploit.
3. Writing to files
As described in Muhaimin Dzulfakar's (somewhat presumptuously named) paper Advanced MySQL Exploitation, you can use INTO OUTFILE or INTO DUMPFILE clauses on a MySQL select to dump the result into a file. Since, by using a UNION, any arbitrary result can be SELECTed, this allows writing new files with arbitrary content at any location that the user running mysqld can access. Conceivably this can be exploited not merely to modify data in the MySQL database, but to get shell access to the server on which it is running - for instance, by writing a PHP script to the webroot and then making a request to it, if the MySQL server is co-hosted with a PHP server.
In mitigation
Lots of factors reduce the practical exploitability of this otherwise impressive-sounding attack:
MySQL will never let you use INTO OUTFILE or INTO DUMPFILE to overwrite an existing file, nor write to a folder that doesn't exist. This prevents attacks like creating a .ssh folder with a private key in the mysql user's home directory and then SSHing in, or overwriting the mysqld binary itself with a malicious version and waiting for a server restart.
Any halfway decent installation package will set up a special user (typically named mysql) to run mysqld, and give that user only very limited permissions. As such, it shouldn't be able to write to most locations on the file system - and certainly shouldn't ordinarily be able to do things like write to a web application's webroot.
Modern installations of MySQL come with --secure-file-priv set by default, preventing MySQL from writing to anywhere other than a designated data import/export directory and thereby rendering this attack almost completely impotent... unless the owner of the server has deliberately disabled it. Fortunately, nobody would ever just completely disable a security feature like that since that would obviously be - oh wait never mind.
4. Calling the sys_exec() function from lib_mysqludf_sys to run arbitrary shell commands
There's a MySQL extension called lib_mysqludf_sys that - judging from its stars on GitHub and a quick Stack Overflow search - has at least a few hundred users. It adds a function called sys_exec that runs shell commands. As noted in #2, functions can be called from within a SELECT; the implications are hopefully obvious. To quote from the source, this function "can be a security hazard".
In mitigation
Most systems don't have this extension installed.
If you say you use mysql_query that doesn't support multiple queries, you cannot directly add DELETE/UPDATE/INSERT, but it's possible to modify data under some circumstances. For example, let's say you have the following function
DELIMITER //
CREATE DEFINER=`root`#`localhost` FUNCTION `testP`()
RETURNS int(11)
LANGUAGE SQL
NOT DETERMINISTIC
MODIFIES SQL DATA
SQL SECURITY DEFINER
COMMENT ''
BEGIN
DELETE FROM test2;
return 1;
END //
Now you can call this function in SELECT :
SELECT id, name, message FROM messages WHERE id = NULL OR testP()
(id = NULL - always NULL(FALSE), so testP() always gets executed.
It depends on the DBMS connector you are using. Most of the time your scenario should not be possible, but under certain circumstances it could work. For further details you should take a look at chapter 4 and 5 from the Blackhat-Paper Advanced MySQL Exploitation.
Yes it's possible.
$_GET['q'] would hold 1; DELETE FROM users; --
SELECT id, name, message FROM messages WHERE id = 1; DELETE FROM users; -- whatever here');

SQL Server vs MySQL - SQL Injection Vulnerabilities in Classic ASP

Recently one of our client's websites fell prey to a SQL Injection attack due to a failure to sanitize query string parameters provided to the page. The vulnerable code has since been identified and is being corrected, but it got me wondering about some of the differences between how MySQL and SQL Server process multi-query strings.
The vulnerable code is used on several dozen websites, two of which are are running on SQL server while the rest are on MySQL. With this code we have never before suffered an injection attack (by the grace of God), but once we released the two websites that are running on SQL server (with the same code base) the website was quickly exploited. The method of injection was quite simple:
page.asp?param=1;delete from [some_table];
Like I said, the vulnerable code is shared across many websites, but if I try to execute the same type of injection on our MySQL sites ASP throws up a nice Server Error letting us know that there was an error in the query:
SELECT * FROM Table1 WHERE ID = 1;DELETE FROM TABLE1;
Testing this further I was able to verify that the MySQL ODBC 3.51 Driver will not allow two SQL queries to be executed in the same statement when an ADODB.Connection object calls Execute(""), while SQL Server Native Client (10.1) doesn't have any problem running two side-by-side queries. Is this in fact just a configuration of the provider that makes SQL server vulnerable in this fashion while MySQL is not, or does this stem from somewhere else?
The MySQL client API does not permit multi-queries by default. You have to enable this explicitly, or else you'll get errors when trying to execute a query like you saw. This is a good thing for reducing risk of SQL injection attacks.
The MySQL ODBC driver 3.51.18 (August 2007) added support for a connect option FLAG_MULTI_STATEMENTS to enable multi-statements. See http://dev.mysql.com/doc/refman/5.1/en/connector-odbc-configuration-connection-parameters.html.
See also http://bugs.mysql.com/bug.php?id=7445 for the history of this option.
Also see my answer to "Mysql change delimiter for better SQL INJECTION handling?" Note that multi-statements is only one way to get an SQL injection vulnerability. Disabling multi-statements is not a 100% proof against these flaws.
It's a feature of SQL server that it supports multiple statements on a line. The solution is not so much to sanitize the input, as to use parameterized queries or stored procedures. If the query had been
SELECT * FROM Table1 WHERE ID = #id
Then passing "1;DELETE FROM TABLE1;" would have produced an error, since that's not a valid integer value.
I think this happened because SQL Server supports MARS. As far as I understand MySQL does not support this. Mars is a good feature to speed up database queires so there are fewer round trips. you can put more then one query in a sql statement.
It is possible to exploit SQL injection without stacking queries. A very common method is to use a "Union Select"
Here is a mysql injection exploit that I have written which uses a union select:
http://milw0rm.com/exploits/3002
A union select allows you make a select statement within other statement:
select 1 union select Password from mysql.user
You can also do a sub-select:
insert into sometable (some,col,id) values ((select Password from mysql.user),1,1)-- )
Blind sql injection works on all platforms, however depending on the database the exploit will be different. This is a blind SQL Injection exploit for mysql:"
milw0rm.com/exploits/4547
This is a very good paper on the topic of SQL Injection for MySQL:
www.ngssoftware.com/papers/HackproofingMySQL.pdf