├── assets ├── magic.png ├── 7UHqiwX.png ├── R7goaLF.png ├── TjWkzGc.png ├── gtQuIsL.png ├── kRMXPZz.png ├── xhTc8Gv.png └── checkheap.png ├── gdbinit.py ├── .gdbinit ├── .gitignore ├── pwngdb ├── __init__.py ├── utils.py ├── command_wrapper.py ├── gdbpwnpwnpwn.py ├── commands.py └── angelheap.py ├── README.md └── LICENSE /assets/magic.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/0xKira/pwngdb/HEAD/assets/magic.png -------------------------------------------------------------------------------- /assets/7UHqiwX.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/0xKira/pwngdb/HEAD/assets/7UHqiwX.png -------------------------------------------------------------------------------- /assets/R7goaLF.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/0xKira/pwngdb/HEAD/assets/R7goaLF.png -------------------------------------------------------------------------------- /assets/TjWkzGc.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/0xKira/pwngdb/HEAD/assets/TjWkzGc.png -------------------------------------------------------------------------------- /assets/gtQuIsL.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/0xKira/pwngdb/HEAD/assets/gtQuIsL.png -------------------------------------------------------------------------------- /assets/kRMXPZz.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/0xKira/pwngdb/HEAD/assets/kRMXPZz.png -------------------------------------------------------------------------------- /assets/xhTc8Gv.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/0xKira/pwngdb/HEAD/assets/xhTc8Gv.png -------------------------------------------------------------------------------- /assets/checkheap.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/0xKira/pwngdb/HEAD/assets/checkheap.png -------------------------------------------------------------------------------- /gdbinit.py: -------------------------------------------------------------------------------- 1 | # !/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | import sys 4 | from os import path 5 | 6 | directory, _file = path.split(__file__) 7 | directory = path.expanduser(directory) 8 | directory = path.abspath(directory) 9 | 10 | sys.path.append(directory) 11 | 12 | import pwngdb 13 | from pwngdb import angelheap, gdbpwnpwnpwn -------------------------------------------------------------------------------- /.gdbinit: -------------------------------------------------------------------------------- 1 | source ~/peda/peda.py 2 | source ~/pwngdb/gdbinit.py 3 | 4 | define init 5 | set $print_addr = $arg0 6 | python 7 | angelheap.init_angelheap() 8 | output = gdb.parse_and_eval('$print_addr') == 1 9 | gdbpwnpwnpwn.init(output) 10 | end 11 | end 12 | 13 | define hookpost-start 14 | init 0 15 | end 16 | 17 | define hookpost-run 18 | init 0 19 | end 20 | 21 | define hookpost-attach 22 | init 1 23 | end 24 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | 55 | # Sphinx documentation 56 | docs/_build/ 57 | 58 | # PyBuilder 59 | target/ 60 | 61 | #Ipython Notebook 62 | .ipynb_checkpoints 63 | 64 | .idea/ 65 | -------------------------------------------------------------------------------- /pwngdb/__init__.py: -------------------------------------------------------------------------------- 1 | # !/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | import gdb 4 | from . import angelheap 5 | from . import gdbpwnpwnpwn 6 | from .commands import PwnCmd 7 | from .command_wrapper import AngelHeapCmd, CmdWrapper, Alias 8 | 9 | angelheap_cmd = AngelHeapCmd() 10 | CmdWrapper('angelheap', angelheap_cmd) 11 | for cmd in angelheap_cmd.commands: 12 | Alias(cmd, 'angelheap {}'.format(cmd)) 13 | 14 | pwn_cmd = PwnCmd() 15 | CmdWrapper('pwngdb', pwn_cmd) 16 | for cmd in pwn_cmd.commands: 17 | Alias(cmd, 'pwngdb {}'.format(cmd)) 18 | 19 | gdb.execute('set print asm-demangle on') 20 | 21 | # for debug usage 22 | # import traceback 23 | # def _execute(cmd, to_string=False): 24 | # try: 25 | # out = gdb._never_guess(cmd, to_string=to_string) 26 | # if to_string: 27 | # return out 28 | # else: 29 | # return True 30 | # except Exception as e: 31 | # print('=' * 40) 32 | # print(cmd, to_string) 33 | # traceback.print_exc() 34 | # print('=' * 40) 35 | # return False 36 | 37 | # gdb._never_guess = gdb.execute 38 | # gdb.execute = _execute -------------------------------------------------------------------------------- /pwngdb/utils.py: -------------------------------------------------------------------------------- 1 | # !/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | import gdb 4 | import re 5 | import os 6 | 7 | 8 | def get_libc_version(): 9 | try: 10 | return float(gdb.execute("x/s __libc_version", to_string=True).split()[2].strip("\"")) 11 | except: 12 | print("Can not get libc version") 13 | return 0 14 | 15 | 16 | def reveal_ptr(addr_of_entry, entry): 17 | return (addr_of_entry >> 12) ^ entry 18 | 19 | 20 | def get_arch(): 21 | data = gdb.execute('show arch', to_string=True) 22 | tmp = re.search("currently.*", data) 23 | if tmp: 24 | info = tmp.group() 25 | if "x86-64" in info: 26 | return "x86-64", "gx ", 8 27 | elif "aarch64" in info: 28 | return "aarch64", "gx ", 8 29 | elif "arm" in info: 30 | return "arm", "wx ", 4 31 | else: 32 | return "i386", "wx ", 4 33 | else: 34 | return None, None, None 35 | 36 | 37 | def get_gdb_map(): 38 | """ 39 | Use gdb command 'info proc mappings' to get the memory mapping 40 | Notice: No permission info 41 | """ 42 | resp = gdb.execute("info proc mappings", to_string=True).split("\n") 43 | resp = '\n'.join(resp[i] for i in range(4, len(resp))).strip().split("\n") 44 | gdb_map = "" 45 | for l in resp: 46 | line = "" 47 | first = True 48 | for sep in l.split(" "): 49 | if len(sep) != 0: 50 | if first: # start address 51 | line += sep + "-" 52 | first = False 53 | else: 54 | line += sep + " " 55 | line = line.strip() + "\n" 56 | gdb_map += line 57 | return gdb_map 58 | 59 | 60 | def get_proc_map(): 61 | data = gdb.execute('info proc exe', to_string=True) 62 | pid = re.search('process.*', data) 63 | if pid: 64 | pid = pid.group() 65 | pid = pid.split()[1] 66 | fpath = "/proc/" + pid + "/maps" 67 | if os.path.isfile(fpath): # if file exist, read memory mapping directly from file 68 | maps = open(fpath) 69 | proc_map = maps.read() 70 | maps.close() 71 | return proc_map 72 | else: # if file doesn't exist, use 'info proc mappings' to get the memory mapping 73 | return get_gdb_map() 74 | else: 75 | return "error" 76 | 77 | 78 | def to_int(val): 79 | """ 80 | Convert a string to int number 81 | from https://github.com/longld/peda 82 | """ 83 | try: 84 | return int(str(val), 0) 85 | except: 86 | return None 87 | 88 | 89 | def normalize_argv(args, size=0): 90 | """ 91 | Normalize argv to list with predefined length 92 | from https://github.com/longld/peda 93 | """ 94 | args = list(args) 95 | for (idx, val) in enumerate(args): 96 | if to_int(val) is not None: 97 | args[idx] = to_int(val) 98 | if size and idx == size: 99 | return args[:idx] 100 | 101 | if size == 0: 102 | return args 103 | for i in range(len(args), size): 104 | args += [None] 105 | return args 106 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # pwngdb 2 | 3 | GDB for pwn. 4 | 5 | ## Install 6 | 7 | ### Basic 8 | cd ~ 9 | git clone https://github.com/0xKira/pwngdb.git 10 | cp ~/pwngdb/.gdbinit ~ 11 | 12 | If you dont want to use gdb-peda , you can modify the gdbinit to remove it. 13 | 14 | ### Heapinfo 15 | 16 | If you want to use the feature of heapinfo and tracemalloc , you need to install libc debug file (libc6-dbg & libc6-dbg:i386 for debian package) 17 | 18 | ## Features 19 | 20 | + `libc` : Print the base address of libc 21 | + `ld` : Print the base address of ld 22 | + `codebase` : Print the base of code segment 23 | + `getheap` : Print the base of heap 24 | + `tls` : Print the thread local storage address 25 | + `ra`: Reattach to the process which specify by GDB file 26 | + `bb`: Break according to the offset to the elf base address 27 | + `xx`: Examine memory according to the offset to the elf base address 28 | + `got` : Print the Global Offset Table infomation 29 | + `dyn` : Print the Dynamic section infomation 30 | + `findcall` : Find some function call 31 | + `bcall` : Set the breakpoint at some function call 32 | + `findsyscall` : Find the syscall (0x050f) 33 | + `fmtarg` : Calculate the index of format string 34 | + You need to stop on printf(the call instruction) which has vulnerability. 35 | + `force` : Calculate the nb in the house of force. 36 | + `heapinfo` : Print some infomation of heap 37 | + heapinfo (Address of arena) 38 | + default is the arena of current thread 39 | + If tcache is enable, it would show infomation of tcache entry 40 | + `heapinfoall` : Print some infomation of heap (all threads) 41 | + `arenainfo` : Print some infomation of all arena 42 | + `chunkinfo`: Print the infomation of chunk 43 | + chunkinfo (Address of victim) 44 | + `chunkptr` : Print the infomation of chunk 45 | + chunkptr (Address of user ptr) 46 | + `mergeinfo` : Print the infomation of merge 47 | + mergeinfo (Address of victim) 48 | + `fastbins` : Print some infomation of fastbin 49 | + `unsorted` : Print some infomation of unsorted bin 50 | + `tracemalloc on` : Trace the malloc and free and detect some error 51 | + You need to run the process first than `tracemalloc on`, it will record all of the malloc and free. 52 | + You can set the `DEBUG` in pwngdb.py , than it will print all of the malloc and free infomation such as the screeshot. 53 | + `parseheap` : Parse heap layout 54 | + `checkheap`: Show the histroy of one address in heap 55 | + You need `tracemalloc on` first. 56 | + `magic` : Print useful variables, functions and one gadget in glibc 57 | + magic [anything] add any arg to show one gadget 58 | + `fp` : show FILE structure 59 | + fp (Address of FILE) 60 | + `fpchain`: show linked list of FILE 61 | + `orange` : Test `house of orange` condition in the `_IO_flush_lockp` 62 | + orange (Address of FILE) 63 | + glibc version <= 2.23 64 | 65 | 66 | ## Screenshot 67 | 68 | + Chunkinfo 69 | 70 | ![chunkinfo](assets/gtQuIsL.png) 71 | + Mergeinfo 72 | 73 | ![chunkinfo](assets/TjWkzGc.png) 74 | + Heapinfo 75 | 76 | ![xhTc8Gv](assets/xhTc8Gv.png) 77 | + Heapinfoall 78 | 79 | ![heapinfoall](assets/kRMXPZz.png) 80 | 81 | + parseheap 82 | 83 | ![R7goaLF](assets/R7goaLF.png) 84 | 85 | + tracemalloc 86 | 87 | ![trace](assets/7UHqiwX.png) 88 | 89 | + magic 90 | 91 | ![magic](assets/magic.png) 92 | 93 | - checkheap 94 | 95 | ![checkheap](assets/checkheap.png) 96 | 97 | ## Credit 98 | 99 | - https://github.com/scwuaptx/Pwngdb 100 | - https://github.com/pwndbg/pwndbg -------------------------------------------------------------------------------- /pwngdb/command_wrapper.py: -------------------------------------------------------------------------------- 1 | # !/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | import gdb 4 | from . import angelheap 5 | from .utils import normalize_argv 6 | 7 | 8 | class AngelHeapCmd(object): 9 | commands = [] 10 | 11 | def __init__(self): 12 | # list all commands 13 | self.commands = set([cmd for cmd in dir(self) if callable(getattr(self, cmd)) and not cmd.startswith("_")]) 14 | self.no_eval_cmds = set() 15 | self.normal_cmds = self.commands 16 | 17 | def tracemalloc(self, *arg): 18 | """ Trace the malloc and free and detect some error """ 19 | (option, ) = normalize_argv(arg, 1) 20 | if option == "on": 21 | try: 22 | angelheap.trace_malloc() 23 | except: 24 | print("Can't create Breakpoint") 25 | elif option == "off": 26 | angelheap.dis_trace_malloc() 27 | 28 | def heapinfo(self, *arg): 29 | """ Print some information of heap """ 30 | (arena, ) = normalize_argv(arg, 1) 31 | angelheap.putheapinfo(arena) 32 | 33 | def heapinfoall(self): 34 | """ Print some information of multiheap """ 35 | angelheap.putheapinfoall() 36 | 37 | def arenainfo(self): 38 | """ Print all arena info """ 39 | angelheap.putarenainfo() 40 | 41 | def chunkinfo(self, *arg): 42 | """ Print chunk information of victim""" 43 | (victim, ) = normalize_argv(arg, 1) 44 | angelheap.chunkinfo(victim) 45 | 46 | def free(self, *arg): 47 | """ Print chunk is freeable """ 48 | (victim, ) = normalize_argv(arg, 1) 49 | angelheap.freeptr(victim) 50 | 51 | def chunkptr(self, *arg): 52 | """ Print chunk information of user ptr""" 53 | (ptr, ) = normalize_argv(arg, 1) 54 | angelheap.chunkptr(ptr) 55 | 56 | def mergeinfo(self, *arg): 57 | """ Print merge information of victim""" 58 | (victim, ) = normalize_argv(arg, 1) 59 | angelheap.mergeinfo(victim) 60 | 61 | def force(self, *arg): 62 | """ Calculate the nb in the house of force """ 63 | (target, ) = normalize_argv(arg, 1) 64 | angelheap.force(target) 65 | 66 | def fastbins(self): 67 | """ Print the fastbin """ 68 | angelheap.putfastbin() 69 | 70 | def unsorted(self): 71 | """ Print the unsorted bin """ 72 | angelheap.put_unsorted() 73 | 74 | def inused(self): 75 | """ Print the inuse chunk """ 76 | angelheap.putinused() 77 | 78 | def parseheap(self): 79 | """ Parse heap """ 80 | angelheap.parse_heap() 81 | 82 | def fakefast(self, *arg): 83 | (addr, size) = normalize_argv(arg, 2) 84 | angelheap.get_fake_fast(addr, size) 85 | 86 | def checkheap(self, *arg): 87 | """ Given an address and return the information of its heap """ 88 | if len(arg) > 1: 89 | angelheap.check_heap(arg[0], arg[1]) 90 | else: 91 | angelheap.check_heap(arg[0]) 92 | 93 | 94 | class CmdWrapper(gdb.Command): 95 | """ command wrapper """ 96 | 97 | def __init__(self, cmd_name, cmd_obj): 98 | super(CmdWrapper, self).__init__(cmd_name, gdb.COMMAND_USER) 99 | self.cmd_obj = cmd_obj 100 | 101 | def try_eval(self, expr): 102 | try: 103 | return gdb.parse_and_eval(expr) 104 | except: 105 | # print("Unable to parse expression: {}".format(expr)) 106 | return expr 107 | 108 | def eval_argv(self, expressions): 109 | """ Leave command alone, let GDB parse and evaluate arguments """ 110 | return [expressions[0]] + [self.try_eval(expr) for expr in expressions[1:]] 111 | 112 | def invoke(self, args, from_tty): 113 | self.dont_repeat() 114 | expressions = gdb.string_to_argv(args) 115 | cmd = expressions[0] 116 | 117 | if cmd in self.cmd_obj.normal_cmds: 118 | func = getattr(self.cmd_obj, cmd) 119 | arg = self.eval_argv(expressions) 120 | func(*arg[1:]) 121 | elif cmd in self.cmd_obj.no_eval_cmds: 122 | func = getattr(self.cmd_obj, cmd) 123 | func(*expressions[1:]) 124 | else: 125 | print("Unknow command") 126 | 127 | 128 | class Alias(gdb.Command): 129 | def __init__(self, alias, command): 130 | self.command = command 131 | super(Alias, self).__init__(alias, gdb.COMMAND_NONE) 132 | 133 | def invoke(self, args, from_tty): 134 | self.dont_repeat() 135 | gdb.execute("%s %s" % (self.command, args)) 136 | -------------------------------------------------------------------------------- /pwngdb/gdbpwnpwnpwn.py: -------------------------------------------------------------------------------- 1 | # !/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | __author__ = "Kira" 4 | import gdb 5 | import re 6 | from subprocess import check_output, CalledProcessError 7 | 8 | elf_base = 0 9 | elf_base_old = 0 10 | pid = 0 11 | is_pie_on = False 12 | proc_name = None 13 | 14 | 15 | def set_current_pid(): 16 | i = gdb.selected_inferior() 17 | if (i is not None) and (i.pid > 0): 18 | global pid 19 | pid = i.pid 20 | return True 21 | return False 22 | 23 | 24 | def set_elf_base(proc_name, output): 25 | global elf_base, elf_base_old 26 | elf_base_old = elf_base 27 | patt = re.compile(r'.*?([0-9a-f]+)\-[0-9a-f]+\s+...p.*?%s' % proc_name) 28 | with open('/proc/{}/maps'.format(pid), 'rb') as f: 29 | vmmap = f.read().decode() 30 | elf_base = int(patt.findall(vmmap)[0], 16) 31 | if output: 32 | print("\033[32m" + 'text:' + "\033[37m", hex(elf_base)) 33 | 34 | 35 | def get_proc_name(): 36 | global proc_name 37 | proc_name = None 38 | try: 39 | data = gdb.execute("info proc exe", to_string=True) 40 | proc_name = re.search("exe.*", data).group().split("=")[1][2:-1] 41 | except: 42 | data = gdb.execute("info files", to_string=True) 43 | if data: 44 | proc_name = re.search("`(.*)', file type", data).group(1) 45 | return proc_name 46 | 47 | 48 | def pie_on(proc_name): 49 | result = check_output("readelf -h -wN " + "\"" + proc_name + "\"", shell=True).decode('utf8') 50 | return 'Type:' in result and 'DYN (' in result 51 | 52 | 53 | def init(output=True): 54 | global proc_name, is_pie_on 55 | if not set_current_pid(): 56 | return 57 | proc_name = get_proc_name() 58 | is_pie_on = pie_on(proc_name) 59 | if is_pie_on: 60 | set_elf_base(proc_name, output) 61 | gdb.execute('getheap', to_string=(not output)) 62 | gdb.execute('libc', to_string=(not output)) 63 | if is_pie_on: 64 | # if existing some breakpoints, delete them and set new breakpoints 65 | if gdb.breakpoints(): 66 | breakpoints = [] 67 | for br in gdb.breakpoints(): 68 | if not br.location: # watchpoint will be None 69 | br.delete() 70 | continue 71 | # won't delete symbol breakpoint 72 | find = re.findall(r'^\*((?:0x)?[0-9a-fA-F]+)$', br.location) 73 | # TODO: convert number to symbol if possible 74 | if find: 75 | location = int(find[0], 0) # let python figure out the base 76 | breakpoints.append(location - elf_base_old) 77 | br.delete() 78 | for i in breakpoints: 79 | gdb.execute('b *%d' % (i + elf_base)) 80 | 81 | 82 | class ReattachCommand(gdb.Command): 83 | """ 84 | Reattaches the new instance of the previous process. 85 | First argument is the name of executable (enough to specify the first time) 86 | """ 87 | 88 | def __init__(self): 89 | super(ReattachCommand, self).__init__("ra", gdb.COMMAND_SUPPORT, gdb.COMPLETE_FILENAME) 90 | 91 | def invoke(self, arg, from_tty): 92 | global proc_name, pid, is_pie_on 93 | 94 | fn = arg.split(' ')[0].strip() 95 | if len(fn) > 0: 96 | proc_name = fn 97 | else: 98 | proc_name = get_proc_name() 99 | if not proc_name: 100 | print('Please specify program name first!') 101 | return 102 | try: 103 | pid = check_output(["pidof", proc_name]).strip() 104 | except CalledProcessError as e: 105 | if e.returncode == 1: 106 | print('Process not found :(') 107 | return 108 | else: 109 | raise e 110 | 111 | pid = pid.decode().split(' ')[0] 112 | try: 113 | gdb.execute('attach ' + pid) 114 | except gdb.error as e: 115 | raise gdb.GdbError(e) 116 | 117 | 118 | class PieBreak(gdb.Command): 119 | """ Break according to the offset to the elf base address """ 120 | 121 | def __init__(self): 122 | super(PieBreak, self).__init__("bb", gdb.COMMAND_SUPPORT, gdb.COMPLETE_EXPRESSION) 123 | 124 | def invoke(self, arg, from_tty): 125 | offset = arg.split(' ')[0].strip() 126 | if len(offset) == 0: 127 | print('I need an offset:(') 128 | return 129 | if pid == 0: 130 | print('Please run your program first, ' 131 | 'use \033[32mstart\033[0m/\033[32mstarti\033[0m to stop at the beginning.') 132 | return 133 | if is_pie_on: 134 | bp_addr = int(gdb.parse_and_eval(offset).cast(gdb.lookup_type('long'))) + elf_base 135 | else: 136 | bp_addr = gdb.parse_and_eval(offset) 137 | out = gdb.execute('info symbol {}'.format(bp_addr), to_string=True) 138 | if 'No symbol matches' in out: 139 | gdb.execute('b *{}'.format(bp_addr)) 140 | else: 141 | sym = re.search('(.*?) in section', out).group(1) 142 | gdb.execute('b *{}'.format(sym)) 143 | 144 | 145 | class PieExamineMem(gdb.Command): 146 | """ Examine memory according to the offset to the elf base address """ 147 | 148 | def __init__(self): 149 | super(PieExamineMem, self).__init__("xx", gdb.COMMAND_SUPPORT, gdb.COMPLETE_EXPRESSION) 150 | 151 | def invoke(self, arg, from_tty): 152 | if is_pie_on: 153 | gdb.execute('x {}+0x{:x}'.format(arg.rstrip(), elf_base)) 154 | else: 155 | gdb.execute('x' + arg) 156 | 157 | 158 | ReattachCommand() 159 | PieBreak() 160 | PieExamineMem() 161 | -------------------------------------------------------------------------------- /pwngdb/commands.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | import gdb 3 | import subprocess 4 | import re 5 | from os import path, system 6 | from .utils import normalize_argv, get_proc_map 7 | 8 | # arch info 9 | capsize = 0 10 | word = "" 11 | arch = "" 12 | magic_variable = [ 13 | "__malloc_hook", "__free_hook", "__realloc_hook", "stdin", "stdout", "_IO_list_all", "__after_morecore_hook" 14 | ] 15 | magic_function = ["system", "execve", "open", "read", "write", "gets", "mprotect", "setcontext+0x35"] 16 | 17 | 18 | class PwnCmd(object): 19 | commands = [] 20 | prevbp = [] 21 | bpoff = [] 22 | 23 | def __init__(self): 24 | # list all commands 25 | self.commands = set([cmd for cmd in dir(self) if callable(getattr(self, cmd)) and not cmd.startswith("_")]) 26 | self.no_eval_cmds = set(['off', 'bcall', 'findcall', 'rop']) 27 | self.normal_cmds = self.commands - self.no_eval_cmds 28 | 29 | def libc(self): 30 | """ Get libc base """ 31 | libc_base = get_libc_base() 32 | if libc_base: 33 | print("\033[34m" + "libc: " + "\033[37m" + hex(libc_base)) 34 | else: 35 | print('libc not found') 36 | 37 | def getheap(self): 38 | """ Get heap base """ 39 | heap_base = get_heap_base() 40 | if heap_base: 41 | print("\033[35m" + "heap: " + "\033[37m" + hex(heap_base)) 42 | else: 43 | print("heap not found") 44 | 45 | def ld(self): 46 | """ Get ld.so base """ 47 | ld_base = get_ld_base() 48 | if ld_base: 49 | print("\033[34m" + "ld: " + "\033[37m" + hex(ld_base)) 50 | else: 51 | print('ld not found') 52 | 53 | def codebase(self): 54 | """ Get code base """ 55 | code_base, _ = get_code_base() 56 | if code_base: 57 | print("\033[34m" + "code: " + "\033[37m" + hex(code_base)) 58 | else: 59 | print('code not found') 60 | 61 | def tls(self): 62 | """ Get tls base """ 63 | tls_base = get_tls_base() 64 | if tls_base: 65 | print("\033[34m" + "tls: " + "\033[37m" + hex(tls_base)) 66 | else: 67 | print('tls not found') 68 | 69 | def canary(self): 70 | """ Get canary value """ 71 | print("\033[34m" + "canary: " + "\033[37m" + hex(get_canary())) 72 | 73 | def fmtarg(self, *arg): 74 | """ Calculate format argument offset """ 75 | (addr, ) = normalize_argv(arg, 1) 76 | get_fmt_arg(addr) 77 | 78 | def off(self, *arg): 79 | """ Calculate offset to libc """ 80 | (sym, ) = normalize_argv(arg, 1) 81 | sym_off = get_off(sym) 82 | if sym_off == 0xffffffffffffffff: 83 | print("Not found the symbol") 84 | else: 85 | if type(sym) is int: 86 | print("\033[34m" + hex(sym) + ": " + "\033[37m" + hex(sym_off)) 87 | else: 88 | print("\033[34m" + sym + ": " + "\033[37m" + hex(sym_off)) 89 | 90 | def fp(self, *arg): 91 | """ show FILE structure """ 92 | (addr, ) = normalize_argv(arg, 1) 93 | show_fp(addr) 94 | 95 | def fpchain(self): 96 | """ show FILE chain """ 97 | show_fp_chain() 98 | 99 | def orange(self, *arg): 100 | """ test house of orange """ 101 | (addr, ) = normalize_argv(arg, 1) 102 | if addr: 103 | test_orange(addr) 104 | else: 105 | print("You need to specifiy an address") 106 | 107 | def fsop(self, *arg): 108 | """ test fsop """ 109 | (addr, ) = normalize_argv(arg, 1) 110 | test_fsop(addr) 111 | 112 | def magic(self, *arg): 113 | """ Print usefual variables or function in glibc """ 114 | (show_one, ) = normalize_argv(arg, 1) 115 | show_magic(show_one) 116 | 117 | def findsyscall(self): 118 | """ find the syscall gadget """ 119 | start, end = get_code_base() 120 | if arch == "x86-64": 121 | gdb.execute("searchmem 0x050f " + hex(start) + " " + hex(end)) 122 | elif arch == "i386": 123 | gdb.execute("searchmem 0x80cd " + hex(start) + " " + hex(end)) 124 | elif arch == "arm": 125 | gdb.execute("searchmem 0xbc80df00 " + hex(start) + " " + hex(end)) 126 | elif arch == "aarch64": 127 | gdb.execute("searchmem 0xd4000001 " + hex(start) + " " + hex(end)) 128 | else: 129 | print("error") 130 | 131 | def got(self): 132 | """ Print the got table """ 133 | proc_name = get_proc_name() 134 | if proc_name: 135 | cmd = "objdump -R " 136 | if is_cpp(): 137 | cmd += "--demangle " 138 | cmd += '"{}"'.format(proc_name) 139 | got = subprocess.check_output(cmd, shell=True)[:-2].decode('utf8') 140 | print(got) 141 | else: 142 | print("No current process or executable file specified.") 143 | 144 | def dyn(self): 145 | """ Print dynamic section """ 146 | proc_name = get_proc_name() 147 | if proc_name: 148 | dyn = subprocess.check_output('readelf -d "{}"'.format(proc_name), shell=True).decode('utf8') 149 | print(dyn) 150 | else: 151 | print("No current process or executable file specified.") 152 | 153 | def rop(self, *arg): 154 | """ ROPgadget """ 155 | proc_name = get_proc_name() 156 | cmd = 'ROPgadget --binary "{}"'.format(proc_name) 157 | if proc_name: 158 | for s in arg: 159 | cmd += ' | grep "{}"'.format(s) 160 | subprocess.call(cmd, shell=True) 161 | else: 162 | print("No current process or executable file specified.") 163 | 164 | def findcall(self, *arg): 165 | """ Find some function call """ 166 | (sym, ) = normalize_argv(arg, 1) 167 | output = search_call(sym) 168 | print(output) 169 | 170 | def bcall(self, *arg): 171 | """ Set the breakpoint at some function call """ 172 | (sym, ) = normalize_argv(arg, 1) 173 | call = search_call(sym) 174 | if not call: 175 | print("symbol not found") 176 | else: 177 | if is_pie(): 178 | code_start, code_end = get_code_base() 179 | for callbase in call.split('\n')[:-1]: 180 | addr = int(callbase.split(':')[0], 16) + code_start 181 | cmd = "b*" + hex(addr) 182 | gdb.execute(cmd) 183 | else: 184 | for callbase in call.split('\n')[:-1]: 185 | addr = int(callbase.split(':')[0], 16) 186 | cmd = "b*" + hex(addr) 187 | gdb.execute(cmd) 188 | 189 | 190 | def is_cpp(): 191 | proc_name = get_proc_name() 192 | data = subprocess.check_output("readelf -s " + proc_name, shell=True).decode('utf8') 193 | if "CXX" in data: 194 | return True 195 | else: 196 | return False 197 | 198 | 199 | def get_proc_name(relative=False): 200 | proc_name = None 201 | try: 202 | data = gdb.execute("info proc exe", to_string=True) 203 | proc_name = re.search("exe.*", data).group().split("=")[1][2:-1] 204 | except: 205 | data = gdb.execute("info files", to_string=True) 206 | if data: 207 | proc_name = re.search('Symbols from "(.*)"', data).group(1) 208 | if proc_name and relative: 209 | return proc_name.split("/")[-1] 210 | return proc_name 211 | 212 | 213 | def get_libc_base(): 214 | proc_map = get_proc_map() 215 | data = re.search(r".+/libc\.so\.6", proc_map) 216 | if not data: 217 | # we accpet libc-2.27.so, not libcx.so 218 | data = re.search(r".+/libc(?!\w).*\.so", proc_map) 219 | if data: 220 | libc_base = int(data.group().split("-")[0], 16) 221 | gdb.execute("set $libc=%s" % hex(libc_base)) 222 | return libc_base 223 | else: 224 | return 0 225 | 226 | 227 | def get_ld_base(): 228 | proc_map = get_proc_map() 229 | data = re.search(r".*ld.*\.so", proc_map) 230 | if data: 231 | ldaddr = data.group().split("-")[0] 232 | gdb.execute("set $ld=%s" % hex(int(ldaddr, 16))) 233 | return int(ldaddr, 16) 234 | else: 235 | return 0 236 | 237 | 238 | def get_heap_base(): 239 | proc_map = get_proc_map() 240 | data = re.search(r".*heap\]", proc_map) 241 | if data: 242 | heap_base = data.group().split("-")[0] 243 | gdb.execute("set $heap=%s" % hex(int(heap_base, 16))) 244 | return int(heap_base, 16) 245 | else: 246 | return 0 247 | 248 | 249 | def get_code_base(): # ret (start,end) 250 | proc_map = get_proc_map() 251 | proc_name = get_proc_name() 252 | pat = ".*" + proc_name 253 | data = re.findall(pat, proc_map) 254 | if data: 255 | code_start = data[0].split("-")[0] 256 | code_end = data[0].split("-")[1].split()[0] 257 | gdb.execute("set $code=%s" % hex(int(code_start, 16))) 258 | return (int(code_start, 16), int(code_end, 16)) 259 | else: 260 | return (0, 0) 261 | 262 | 263 | def get_tls_base(): 264 | if arch == "i386": 265 | vsysaddr = gdb.execute("info functions __kernel_vsyscall", to_string=True).split("\n")[-2].split()[0].strip() 266 | sysinfo = gdb.execute("searchmem " + vsysaddr, to_string=True) 267 | match = re.search(r"mapped : .*(0x[0-9a-z]{8})", sysinfo) 268 | if match: 269 | tls_base = int(match.groups()[0], 16) - 0x10 270 | else: 271 | return 0 272 | return tls_base 273 | elif arch == "x86-64": 274 | gdb.execute("call (int)arch_prctl(0x1003, $rsp-8)", to_string=True) 275 | data = gdb.execute("x/xg $rsp-8", to_string=True) 276 | return int(data.split(":")[1].strip(), 16) 277 | else: 278 | return 0 279 | 280 | 281 | def get_canary(): 282 | tls_base = get_tls_base() 283 | if not tls_base: 284 | return 'error' 285 | if arch == "i386": 286 | offset = 0x14 287 | result = gdb.execute("x/xw " + hex(tls_base + offset), to_string=True).split(":")[1].strip() 288 | return int(result, 16) 289 | elif arch == "x86-64": 290 | offset = 0x28 291 | result = gdb.execute("x/xg " + hex(tls_base + offset), to_string=True).split(":")[1].strip() 292 | return int(result, 16) 293 | else: 294 | return "error" 295 | 296 | 297 | def get_off(sym): 298 | libc = get_libc_base() 299 | if type(sym) is int: 300 | return sym - libc 301 | else: 302 | try: 303 | data = gdb.execute("x/x " + sym, to_string=True) 304 | if "No symbol" in data: 305 | return 0xffffffffffffffff 306 | else: 307 | data = re.search("0x.*[0-9a-f] ", data).group() 308 | sym_addr = int(data[:-1], 16) 309 | return sym_addr - libc 310 | except: 311 | return 0xffffffffffffffff 312 | 313 | 314 | def search_call(sym): 315 | proc_name = get_proc_name() 316 | cmd = "objdump -d -M intel " 317 | if is_cpp(): 318 | cmd += "--demangle " 319 | cmd += '"{}"'.format(proc_name) 320 | try: 321 | call = subprocess.check_output(cmd + "| grep \"call.*" + sym + "@plt>\"", shell=True).decode('utf8') 322 | return call 323 | except: 324 | return '' 325 | 326 | 327 | def is_pie(): 328 | proc_name = get_proc_name() 329 | result = subprocess.check_output('readelf -h -wN "{}"'.format(proc_name), shell=True).decode('utf8') 330 | return 'Type:' in result and 'DYN (' in result 331 | 332 | 333 | def get_reg(reg): 334 | cmd = "info register " + reg 335 | result = int(gdb.execute(cmd, to_string=True).split()[1].strip(), 16) 336 | return result 337 | 338 | 339 | def show_fp(addr): 340 | if addr: 341 | cmd = "p *(struct _IO_FILE_plus *)" + hex(addr) 342 | try: 343 | gdb.execute(cmd) 344 | except gdb.error: 345 | print("Can't not access 0x%x" % addr) 346 | else: 347 | print("You need to specify an address") 348 | 349 | 350 | def show_fp_chain(): 351 | cmd = "x/" + word + "&_IO_list_all" 352 | head = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 353 | print("\033[32mfpchain:\033[1;37m ", end="") 354 | chain = head 355 | print("0x%x" % chain, end="") 356 | try: 357 | while chain != 0: 358 | print(" --> ", end="") 359 | cmd = "x/" + word + "&((struct _IO_FILE_plus *)" + hex(chain) + ").file._chain" 360 | chain = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 361 | print("0x%x" % chain, end="") 362 | print("") 363 | except: 364 | print("Chain is corrupted") 365 | 366 | 367 | def test_orange(addr): 368 | result = True 369 | cmd = "x/" + word + "&((struct _IO_FILE_plus *)" + hex(addr) + ").file._mode" 370 | mode = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) & 0xffffffff 371 | cmd = "x/" + word + "&((struct _IO_FILE_plus *)" + hex(addr) + ").file._IO_write_ptr" 372 | write_ptr = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 373 | cmd = "x/" + word + "&((struct _IO_FILE_plus *)" + hex(addr) + ").file._IO_write_base" 374 | write_base = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 375 | if mode < 0x80000000 and mode != 0: 376 | try: 377 | cmd = "x/" + word + "&((struct _IO_FILE_plus *)" + hex(addr) + ").file._wide_data" 378 | wide_data = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 379 | cmd = "x/" + word + "&((struct _IO_wide_data *)" + hex(wide_data) + ")._IO_write_ptr" 380 | w_write_ptr = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 381 | cmd = "x/" + word + "&((struct _IO_wide_data *)" + hex(wide_data) + ")._IO_write_base" 382 | w_write_base = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 383 | if w_write_ptr <= w_write_base: 384 | print("\033[;1;31m_wide_data->_IO_write_ptr(0x%x) < _wide_data->_IO_write_base(0x%x)\033[1;37m" % 385 | (w_write_ptr, w_write_base)) 386 | result = False 387 | except: 388 | print("\033;1;31mCan't access wide_data\033[1;37m") 389 | result = False 390 | else: 391 | if write_ptr <= write_base: 392 | print("\033[;1;31m_IO_write_ptr(0x%x) < _IO_write_base(0x%x)\033[1;37m" % (write_ptr, write_base)) 393 | result = False 394 | if result: 395 | print("Result : \033[34mTrue\033[37m") 396 | cmd = "x/" + word + "&((struct _IO_FILE_plus *)" + hex(addr) + ").vtable.__overflow" 397 | overflow = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 398 | print("Func : \033[33m 0x%x\033[1;37m" % overflow) 399 | else: 400 | print("Result : \033[31mFalse\033[1;37m") 401 | 402 | 403 | def test_fsop(addr=None): 404 | if addr: 405 | cmd = "x/" + word + hex(addr) 406 | else: 407 | cmd = "x/" + word + "&_IO_list_all" 408 | head = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 409 | chain = head 410 | print("---------- fp : 0x%x ----------" % chain) 411 | test_orange(chain) 412 | try: 413 | while chain != 0: 414 | cmd = "x/" + word + "&((struct _IO_FILE_plus *)" + hex(chain) + ").file._chain" 415 | chain = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 416 | if chain != 0: 417 | print("---------- fp : 0x%x ----------" % chain) 418 | test_orange(chain) 419 | except: 420 | print("Chain is corrupted") 421 | 422 | 423 | def get_fmt_arg(addr): 424 | if not addr: 425 | print("You need to specify a stack address") 426 | return 427 | if arch == "i386": 428 | start = get_reg("esp") 429 | idx = (addr - start) / 4 + 1 430 | print('The index of format argument : %d ("%%%d$p")' % (idx, idx - 1)) 431 | elif arch == "x86-64": 432 | start = get_reg("rsp") 433 | idx = (addr - start) / 8 + 7 434 | print('The index of format argument : %d ("%%%d$p")' % (idx, idx - 1)) 435 | else: 436 | print("Not support the arch") 437 | 438 | 439 | def show_magic(show_one): 440 | try: 441 | proc_map = get_proc_map() 442 | data = re.findall(r'\S+/libc(?!\w).*\.so.*', proc_map) 443 | libc_path = data[0].split()[-1] if data else '' 444 | libc_base = get_libc_base() 445 | print("========== function ==========") 446 | for f in magic_function: 447 | cmd = "x/" + word + "&" + f 448 | func_addr = gdb.execute(cmd, to_string=True).split()[0].strip() 449 | to_print = "\033[34m%s\033[33m(%s)\033[37m" % (f, hex(get_off(f))) 450 | to_print = to_print.ljust(36 + 15, ' ') + func_addr 451 | print(to_print) 452 | print("\033[00m========== variables ==========") 453 | for v in magic_variable: 454 | cmd = "x/" + word + "&" + v 455 | output = gdb.execute(cmd, to_string=True) 456 | var_addr = output.split()[0].strip() 457 | var_content = output.split(':')[1].strip() 458 | offset = hex(get_off("&" + v)) 459 | to_print = '\033[34m%s\033[33m(%s)\033[37m' % (v, offset) 460 | to_print = to_print.ljust(36 + 15, ' ') 461 | to_print += '%s: \033[37m%s' % (var_addr, var_content) 462 | print(to_print) 463 | if libc_path: 464 | cmd = 'strings -t x {} | grep "/bin/sh"'.format(libc_path) 465 | binsh_off = subprocess.check_output(cmd, shell=True).decode('utf8').split()[0] 466 | binsh_addr = libc_base + int(binsh_off, 16) 467 | cmd = "x/" + word + hex(binsh_addr) 468 | binsh_content = gdb.execute(cmd, to_string=True).split(':')[1].strip() 469 | to_print = '\033[34m"/bin/sh"\033[33m(0x%s)\033[37m' % binsh_off 470 | to_print = to_print.ljust(36 + 15, ' ') 471 | to_print += '0x%x: \033[37m%s' % (binsh_addr, binsh_content) 472 | print(to_print) 473 | # print one gadget 474 | if show_one and path.isfile('/usr/local/bin/one_gadget'): 475 | print("========== one gadget ==========") 476 | system("one_gadget {}".format(libc_path)) 477 | except: 478 | print("Error occured, you may need run the program first") 479 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /pwngdb/angelheap.py: -------------------------------------------------------------------------------- 1 | # !/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | import gdb 5 | import re 6 | import copy 7 | import struct 8 | import os 9 | from .utils import get_arch, get_libc_version, reveal_ptr 10 | from .commands import get_libc_base 11 | from . import commands 12 | 13 | # main_arena 14 | main_arena = 0 15 | main_arena_off = 0 16 | 17 | # thread 18 | thread_arena = 0 19 | enable_thread = False 20 | tcache_enable = False 21 | tcache = None 22 | tcache_max_bin = 0 23 | tcache_counts_size = 1 24 | 25 | # chunks 26 | top = {} 27 | fastbin_size = 13 28 | fastbin = [] 29 | fastchunk = [] # save fastchunk address for chunkinfo check 30 | tcache_entry = [] 31 | tcache_count = [] 32 | all_tcache_entry = [] # save tcache address for chunkinfo check 33 | last_remainder = {} 34 | unsortbin = [] 35 | smallbin = {} # {size:bin} 36 | largebin = {} 37 | system_mem = 0x21000 38 | 39 | # chunk recording 40 | free_mem_area = {} # using in parse 41 | alloc_mem_area = {} 42 | free_record = {} # using in trace 43 | # all malloc free record trace 44 | # struct: malloc/free, start_addr, end_addr 45 | all_record = [] 46 | 47 | # setting for tracing memory allocation 48 | enable_reveal_ptr = False 49 | trace_largebin = True 50 | in_memalign = False 51 | in_realloc = False 52 | print_overlap = True 53 | DEBUG = True # debug msg (free and malloc) if you want 54 | 55 | # breakpoints for tracing 56 | malloc_bp = None 57 | free_bp = None 58 | memalign_bp = None 59 | realloc_bp = None 60 | 61 | # arch info 62 | arch = "" 63 | word = "" 64 | capsize = 0 65 | 66 | # condition 67 | bin_corrupt = False 68 | 69 | 70 | def u32(data, fmt="--------------------------------------------------------------------------------------<\033[37m" 117 | ) 118 | msg = "\033[33mmalloc(0x%x)\033[37m" % self.arg 119 | print("%-40s = 0x%x \033[31m overlap detected !! (0x%x)\033[37m" % 120 | (msg, chunk["addr"] + capsize * 2, overlap["addr"])) 121 | print( 122 | "\033[34m>--------------------------------------------------------------------------------------<\033[37m" 123 | ) 124 | else: 125 | print("\033[31moverlap detected !! (0x%x)\033[37m" % overlap["addr"]) 126 | del alloc_mem_area[hex(overlap["addr"])] 127 | else: 128 | if DEBUG: 129 | msg = "\033[33mmalloc(0x%x)\033[37m" % self.arg 130 | print("%-40s = 0x%x" % (msg, chunk["addr"] + capsize * 2)) 131 | alloc_mem_area[hex(chunk["addr"])] = copy.deepcopy((chunk["addr"], chunk["addr"] + chunk["size"], chunk)) 132 | backtrace = gdb.execute('bt', to_string=True) 133 | all_record.append( 134 | ['malloc', chunk["addr"], chunk["addr"] + chunk["size"], '\n'.join(backtrace.split('\n')[:-3])]) 135 | if hex(chunk["addr"]) in free_record: 136 | free_chunk_tuple = free_record[hex(chunk["addr"])] 137 | free_chunk = free_chunk_tuple[2] 138 | split_chunk = {} 139 | del free_record[hex(chunk["addr"])] 140 | if chunk["size"] != free_chunk["size"]: 141 | split_chunk["addr"] = chunk["addr"] + chunk["size"] 142 | split_chunk["size"] = free_chunk["size"] - chunk["size"] 143 | free_record[hex(split_chunk["addr"])] = copy.deepcopy( 144 | (split_chunk["addr"], split_chunk["addr"] + split_chunk["size"], split_chunk)) 145 | if self.arg >= 128 * capsize: 146 | Malloc_consolidate() 147 | 148 | 149 | class Malloc_Bp_handler(gdb.Breakpoint): 150 | def stop(self): 151 | if arch == "x86-64": 152 | reg = "$rdi" 153 | else: 154 | # for _int_malloc in x86's glibc (unbuntu 14.04 & 16.04), size is stored in edx 155 | # fbi warning! 156 | # to be changed here! 157 | reg = "$edx" 158 | arg = int(gdb.execute("info register " + reg, to_string=True).split()[1].strip(), 16) 159 | Malloc_bp_ret(arg) 160 | return False 161 | 162 | 163 | class Free_bp_ret(gdb.FinishBreakpoint): 164 | def __init__(self): 165 | gdb.FinishBreakpoint.__init__(self, gdb.newest_frame(), internal=True) 166 | self.silent = True 167 | 168 | def stop(self): 169 | Malloc_consolidate() 170 | return False 171 | 172 | 173 | class Free_Bp_handler(gdb.Breakpoint): 174 | def stop(self): 175 | global alloc_mem_area, free_record, in_memalign, in_realloc, all_record 176 | get_top_lastremainder() 177 | 178 | if arch == "x86-64": 179 | reg = "$rdi" 180 | result = int(gdb.execute("info register " + reg, to_string=True).split()[1].strip(), 16) 181 | else: 182 | # for _int_free in x86's glibc (unbuntu 14.04 & 16.04), chunk address is stored in edx 183 | # fbi warning! 184 | # to be changed here! 185 | reg = "$edx" 186 | result = int(gdb.execute("info register " + reg, to_string=True).split()[1].strip(), 16) 187 | chunk = {} 188 | if in_memalign or in_realloc: 189 | Update_alloca() 190 | in_memalign = False 191 | in_realloc = False 192 | prev_freed = False 193 | chunk["addr"] = result - capsize * 2 194 | 195 | cmd = "x/" + word + hex(chunk["addr"] + capsize) 196 | size = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 197 | chunk["size"] = size & 0xfffffffffffffff8 198 | if (size & 1) == 0: 199 | prev_freed = True 200 | 201 | backtrace = gdb.execute('bt', to_string=True) 202 | all_record.append(['free', chunk["addr"], chunk["addr"] + chunk["size"], '\n'.join(backtrace.split('\n')[:-3])]) 203 | 204 | overlap, status = check_overlap(chunk["addr"], chunk["size"], free_record) 205 | if overlap and status == "error": 206 | if DEBUG: 207 | msg = "\033[32mfree(0x%x)\033[37m (size = 0x%x)" % (result, chunk["size"]) 208 | print( 209 | "\033[34m>--------------------------------------------------------------------------------------<\033[37m" 210 | ) 211 | print("%-25s \033[31m double free detected !! (0x%x(size:0x%x))\033[37m" % 212 | (msg, overlap["addr"], overlap["size"])) 213 | print( 214 | "\033[34m>--------------------------------------------------------------------------------------<\033[37m", 215 | end="") 216 | else: 217 | print("\033[31mdouble free detected !! (0x%x)\033[37m" % overlap["addr"]) 218 | del free_record[hex(overlap["addr"])] 219 | else: 220 | if DEBUG: 221 | msg = "\033[32mfree(0x%x)\033[37m" % result 222 | print("%-40s (size = 0x%x)" % (msg, chunk["size"]), end="") 223 | 224 | if chunk["size"] <= 0x80: 225 | free_record[hex(chunk["addr"])] = copy.deepcopy((chunk["addr"], chunk["addr"] + chunk["size"], chunk)) 226 | if DEBUG: 227 | print("") 228 | if hex(chunk["addr"]) in alloc_mem_area: 229 | del alloc_mem_area[hex(chunk["addr"])] 230 | return False 231 | 232 | prev_chunk = {} 233 | if prev_freed: 234 | cmd = "x/" + word + hex(chunk["addr"]) 235 | prev_chunk["size"] = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) & 0xfffffffffffffff8 236 | prev_chunk["addr"] = chunk["addr"] - prev_chunk["size"] 237 | if hex(prev_chunk["addr"]) not in free_record: 238 | print("\033[31m confuse in prev_chunk 0x%x" % prev_chunk["addr"]) 239 | else: 240 | prev_chunk["size"] += chunk["size"] 241 | del free_record[hex(prev_chunk["addr"])] 242 | 243 | next_chunk = {"addr": chunk["addr"] + chunk["size"]} 244 | 245 | if next_chunk["addr"] == top["addr"]: 246 | if hex(chunk["addr"]) in alloc_mem_area: 247 | del alloc_mem_area[hex(chunk["addr"])] 248 | Free_bp_ret() 249 | if DEBUG: 250 | print("") 251 | return False 252 | 253 | cmd = "x/" + word + hex(next_chunk["addr"] + capsize) 254 | next_chunk["size"] = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) & 0xfffffffffffffff8 255 | cmd = "x/" + word + hex(next_chunk["addr"] + next_chunk["size"] + capsize) 256 | next_inuse = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) & 1 257 | 258 | if next_inuse == 0 and prev_freed: # next chunk is freed 259 | if hex(next_chunk["addr"]) not in free_record: 260 | print("\033[31m confuse in next_chunk 0x%x" % next_chunk["addr"]) 261 | else: 262 | prev_chunk["size"] += next_chunk["size"] 263 | del free_record[hex(next_chunk["addr"])] 264 | if next_inuse == 0 and not prev_freed: 265 | if hex(next_chunk["addr"]) not in free_record: 266 | print("\033[31m confuse in next_chunk 0x%x" % next_chunk["addr"]) 267 | else: 268 | chunk["size"] += next_chunk["size"] 269 | del free_record[hex(next_chunk["addr"])] 270 | if prev_freed: 271 | if hex(chunk["addr"]) in alloc_mem_area: 272 | del alloc_mem_area[hex(chunk["addr"])] 273 | chunk = prev_chunk 274 | 275 | if DEBUG: 276 | print("") 277 | free_record[hex(chunk["addr"])] = copy.deepcopy((chunk["addr"], chunk["addr"] + chunk["size"], chunk)) 278 | if hex(chunk["addr"]) in alloc_mem_area: 279 | del alloc_mem_area[hex(chunk["addr"])] 280 | if chunk["size"] > 65536: 281 | Malloc_consolidate() 282 | return False 283 | 284 | 285 | class Memalign_Bp_handler(gdb.Breakpoint): 286 | def stop(self): 287 | global in_memalign 288 | in_memalign = True 289 | return False 290 | 291 | 292 | class Realloc_Bp_handler(gdb.Breakpoint): 293 | def stop(self): 294 | global in_realloc 295 | in_realloc = True 296 | return False 297 | 298 | 299 | def Update_alloca(): 300 | global alloc_mem_area 301 | for addr, (start, end, chunk) in alloc_mem_area.items(): 302 | cmd = "x/" + word + hex(chunk["addr"] + capsize * 1) 303 | cur_size = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) & 0xfffffffffffffff8 304 | 305 | if cur_size != chunk["size"]: 306 | chunk["size"] = cur_size 307 | alloc_mem_area[hex(chunk["addr"])] = copy.deepcopy((start, start + cur_size, chunk)) 308 | 309 | 310 | def Malloc_consolidate(): 311 | """ merge fastbin when malloc a large chunk or free a very large chunk """ 312 | global fastbin, free_record 313 | 314 | free_record = {} 315 | if not get_heap_info(): 316 | print("Can't find heap info") 317 | return 318 | free_record = copy.deepcopy(free_mem_area) 319 | 320 | 321 | def getoff(sym): 322 | libc = get_libc_base() 323 | if type(sym) is int: 324 | return sym - libc 325 | else: 326 | try: 327 | data = gdb.execute("x/x " + sym, to_string=True) 328 | if "No symbol" in data: 329 | return 0 330 | else: 331 | data = re.search("0x.*[0-9a-f] ", data) 332 | data = data.group() 333 | symaddr = int(data[:-1], 16) 334 | return symaddr - libc 335 | except: 336 | return 0 337 | 338 | 339 | def set_thread_arena(): 340 | global thread_arena, main_arena, enable_thread 341 | try: 342 | data = gdb.execute("x/" + word + "&thread_arena", to_string=True) 343 | except: 344 | return 345 | enable_thread = True 346 | if "main_arena" in data: 347 | thread_arena = main_arena 348 | return 349 | thread_arena = int(data.split(":")[1].strip(), 16) 350 | 351 | 352 | def set_main_arena(): 353 | global main_arena, main_arena_off 354 | 355 | offset = getoff("&main_arena") 356 | if offset == 0: # no main_arena symbol 357 | print( 358 | "Cannot get main_arena's symbol address. Make sure you install libc debug file (libc6-dbg & libc6-dbg:i386 for debian package)." 359 | ) 360 | return 361 | main_arena_off = offset 362 | main_arena = get_libc_base() + main_arena_off 363 | 364 | 365 | def check_overlap(addr, size, data=None): 366 | if data: 367 | for key, (start, end, chunk) in data.items(): 368 | if (addr >= start and addr < end) or ((addr + size) > start and 369 | (addr + size) < end) or ((addr < start) and ((addr + size) >= end)): 370 | return chunk, "error" 371 | else: 372 | for key, (start, end, chunk) in free_mem_area.items(): 373 | if (addr >= start and addr < end) or ((addr + size) > start and 374 | (addr + size) < end) or ((addr < start) and ((addr + size) >= end)): 375 | return chunk, "freed" 376 | for key, (start, end, chunk) in alloc_mem_area.items(): 377 | if (addr >= start and addr < end) or ((addr + size) > start and 378 | (addr + size) < end) or ((addr < start) and ((addr + size) >= end)): 379 | return chunk, "inused" 380 | return None, None 381 | 382 | 383 | def get_top_lastremainder(arena=None): 384 | global fastbin_size, top, last_remainder 385 | if not arena: 386 | arena = main_arena 387 | chunk = {} 388 | # get top 389 | cmd = "x/" + word + "&((struct malloc_state *)" + hex(arena) + ").top" 390 | chunk["addr"] = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 391 | chunk["size"] = 0 392 | if chunk["addr"]: 393 | cmd = "x/" + word + hex(chunk["addr"] + capsize * 1) 394 | try: 395 | chunk["size"] = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) & 0xfffffffffffffff8 396 | if chunk["size"] > system_mem: 397 | chunk["memerror"] = "top is broken ?" 398 | except: 399 | chunk["memerror"] = "invaild memory" 400 | top = copy.deepcopy(chunk) 401 | # get last_remainder 402 | chunk = {} 403 | cmd = "x/" + word + "&((struct malloc_state *)" + hex(arena) + ").last_remainder" 404 | chunk["addr"] = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 405 | chunk["size"] = 0 406 | if chunk["addr"]: 407 | cmd = "x/" + word + hex(chunk["addr"] + capsize * 1) 408 | try: 409 | chunk["size"] = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) & 0xfffffffffffffff8 410 | except: 411 | chunk["memerror"] = "invaild memory" 412 | last_remainder = copy.deepcopy(chunk) 413 | 414 | 415 | def get_fast_bin(arena=None): 416 | global fastbin, fastchunk, fastbin_size, free_mem_area 417 | 418 | if not arena: 419 | arena = main_arena 420 | fastbin = [] 421 | fastchunk = [] 422 | # freememoryarea = [] 423 | cmd = "x/" + word + "&((struct malloc_state *)" + hex(arena) + ").fastbinsY" 424 | fastbinsY = int(gdb.execute(cmd, to_string=True).split(":")[0].split()[0].strip(), 16) 425 | for i in range(fastbin_size - 3): 426 | fastbin.append([]) 427 | chunk = {} 428 | is_overlap = (None, None) 429 | cmd = "x/" + word + hex(fastbinsY + i * capsize) 430 | chunk["addr"] = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 431 | 432 | while chunk["addr"] and not is_overlap[0]: 433 | cmd = "x/" + word + hex(chunk["addr"] + capsize * 1) 434 | try: 435 | chunk["size"] = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) & 0xfffffffffffffff8 436 | except: 437 | chunk["memerror"] = "invaild memory" 438 | break 439 | is_overlap = check_overlap(chunk["addr"], (capsize * 2) * (i + 2)) 440 | chunk["overlap"] = is_overlap 441 | free_mem_area[hex(chunk["addr"])] = copy.deepcopy( 442 | (chunk["addr"], chunk["addr"] + (capsize * 2) * (i + 2), chunk)) 443 | fastbin[i].append(copy.deepcopy(chunk)) 444 | fastchunk.append(chunk["addr"]) 445 | cmd = "x/" + word + hex(chunk["addr"] + capsize * 2) 446 | ref_chunk_addr = chunk["addr"] + capsize * 2 447 | chunk = {} 448 | chunk["addr"] = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 449 | if chunk["addr"] and enable_reveal_ptr: 450 | chunk["addr"] = reveal_ptr(ref_chunk_addr, chunk["addr"]) 451 | if not is_overlap[0]: 452 | chunk["size"] = 0 453 | chunk["overlap"] = None 454 | fastbin[i].append(copy.deepcopy(chunk)) 455 | 456 | 457 | def get_curthread(): 458 | cmd = "thread" 459 | thread_id = int(gdb.execute(cmd, to_string=True).split("thread is")[1].split()[0].strip()) 460 | return thread_id 461 | 462 | 463 | def get_all_threads(): 464 | cmd = "info threads" 465 | all_threads = [ 466 | int(line.split()[0].strip()) for line in gdb.execute(cmd, to_string=True).replace("*", "").split("\n")[1:-1] 467 | ] 468 | return all_threads 469 | 470 | 471 | def thread_cmd_execute(thread_id, thread_cmd): 472 | cmd = "thread apply %d %s" % (thread_id, thread_cmd) 473 | result = gdb.execute(cmd, to_string=True) 474 | return result 475 | 476 | 477 | def get_tcache(): 478 | global tcache, tcache_enable, tcache_max_bin, tcache_counts_size 479 | 480 | try: 481 | tcache_max_bin = int(gdb.execute("x/" + word + " &mp_.tcache_bins", to_string=True).split(":")[1].strip(), 16) 482 | try: 483 | tcache_enable = True 484 | tcache = int(gdb.execute("x/" + word + "&tcache", to_string=True).split(":")[1].strip(), 16) 485 | tps_size = int(gdb.execute("p/x sizeof(*tcache)", to_string=True).split("=")[1].strip(), 16) 486 | if capsize == 4: 487 | if tps_size > 0x140: 488 | tcache_counts_size = 2 489 | else: 490 | if tps_size > 0x240: 491 | tcache_counts_size = 2 492 | except gdb.error: 493 | heapbase = get_heapbase() 494 | if heapbase != 0: 495 | cmd = "x/" + word + hex(heapbase + capsize * 1) 496 | f_size = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 497 | while (f_size == 0): 498 | heapbase += capsize * 2 499 | cmd = "x/" + word + hex(heapbase + capsize * 1) 500 | f_size = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 501 | tcache = heapbase + capsize * 2 502 | if capsize == 4: 503 | if (f_size & ~7) - 0x10 > 0x140: 504 | tcache_counts_size = 2 505 | else: 506 | if (f_size & ~7) - 0x10 > 0x240: 507 | tcache_counts_size = 2 508 | else: 509 | tcache = 0 510 | except gdb.error: 511 | tcache_enable = False 512 | tcache = 0 513 | 514 | 515 | def get_tcache_count(): 516 | global tcache_count 517 | tcache_count = [] 518 | if not tcache_enable: 519 | return 520 | count_size = int(tcache_max_bin * tcache_counts_size / capsize) 521 | for i in range(count_size): 522 | cmd = "x/" + word + hex(tcache + i * capsize) 523 | c = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 524 | for j in range(int(capsize / tcache_counts_size)): 525 | tcache_count.append((c >> j * 8 * tcache_counts_size) & 0xff) 526 | 527 | 528 | def get_tcache_entry(): 529 | global tcache_entry 530 | 531 | get_tcache() 532 | if not tcache_enable: 533 | return 534 | tcache_entry = [] 535 | get_tcache_count() 536 | if tcache and tcache_max_bin: 537 | entry_start = tcache + tcache_max_bin * tcache_counts_size 538 | for i in range(tcache_max_bin): 539 | tcache_entry.append([]) 540 | chunk = {} 541 | is_overlap = (None, None) 542 | cmd = "x/" + word + hex(entry_start + i * capsize) 543 | entry = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 544 | while entry and not is_overlap[0]: 545 | chunk["addr"] = entry - capsize * 2 546 | if ((entry & -capsize) != entry) and enable_reveal_ptr: 547 | chunk["memerror"] = "unaligned tcache chunk" 548 | tcache_entry[i].append(copy.deepcopy(chunk)) 549 | break 550 | 551 | cmd = "x/" + word + hex(chunk["addr"] + capsize) 552 | try: 553 | chunk["size"] = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) & 0xfffffffffffffff8 554 | except: 555 | chunk["memerror"] = "invaild memory" 556 | tcache_entry[i].append(copy.deepcopy(chunk)) 557 | break 558 | is_overlap = check_overlap(chunk["addr"], chunk["size"]) 559 | 560 | chunk["overlap"] = is_overlap 561 | free_mem_area[hex(chunk["addr"])] = copy.deepcopy((chunk["addr"], chunk["addr"] + chunk["size"], chunk)) 562 | tcache_entry[i].append(copy.deepcopy(chunk)) 563 | all_tcache_entry.append(chunk["addr"]) 564 | cmd = "x/" + word + hex(chunk["addr"] + capsize * 2) 565 | entry = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 566 | if entry and enable_reveal_ptr: 567 | entry = reveal_ptr(chunk["addr"] + capsize * 2, entry) 568 | 569 | chunk = {} 570 | 571 | 572 | def trace_normal_bin(chunkhead, arena=None): 573 | global free_mem_area 574 | if not arena: 575 | arena = main_arena 576 | bins = [] 577 | if chunkhead["addr"] == 0: # main_arena not initial 578 | return None 579 | chunk = {} 580 | cmd = "x/" + word + hex(chunkhead["addr"] + capsize * 2) # fd 581 | chunk["addr"] = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) # get fd chunk 582 | if (chunk["addr"] == chunkhead["addr"]): # no chunk in the bin 583 | if (chunkhead["addr"] > arena): 584 | return bins 585 | else: 586 | try: 587 | cmd = "x/" + word + hex(chunk["addr"] + capsize * 1) 588 | chunk["size"] = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) & 0xfffffffffffffff8 589 | is_overlap = check_overlap(chunk["addr"], chunk["size"]) 590 | chunk["overlap"] = is_overlap 591 | chunk["memerror"] = "\033[31mbad fd (" + hex(chunk["addr"]) + ")\033[37m" 592 | except: 593 | chunk["memerror"] = "invaild memory" 594 | bins.append(copy.deepcopy(chunk)) 595 | return bins 596 | else: 597 | try: 598 | cmd = "x/" + word + hex(chunkhead["addr"] + capsize * 3) 599 | bk = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 600 | cmd = "x/" + word + hex(bk + capsize * 2) 601 | bk_fd = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 602 | if bk_fd != chunkhead["addr"]: 603 | chunkhead[ 604 | "memerror"] = "\033[31mdoubly linked list corruption {0} != {1} and \033[36m{2}\033[31m is broken".format( 605 | hex(chunkhead["addr"]), hex(bk_fd), hex(chunkhead["addr"])) 606 | bins.append(copy.deepcopy(chunkhead)) 607 | return bins 608 | fd = chunkhead["addr"] 609 | chunkhead = {} 610 | chunkhead["addr"] = bk # bins addr 611 | chunk["addr"] = fd # first chunk 612 | except: 613 | chunkhead["memerror"] = "invaild memory" 614 | bins.append(copy.deepcopy(chunkhead)) 615 | return bins 616 | while chunk["addr"] != chunkhead["addr"]: 617 | try: 618 | cmd = "x/" + word + hex(chunk["addr"]) 619 | chunk["prev_size"] = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 620 | 16) & 0xfffffffffffffff8 621 | cmd = "x/" + word + hex(chunk["addr"] + capsize * 1) 622 | chunk["size"] = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) & 0xfffffffffffffff8 623 | except: 624 | chunk["memerror"] = "invaild memory" 625 | break 626 | try: 627 | cmd = "x/" + word + hex(chunk["addr"] + capsize * 2) 628 | fd = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 629 | if fd == chunk["addr"]: 630 | chunk["memerror"] = "\033[31mbad fd (" + hex(fd) + ")\033[37m" 631 | bins.append(copy.deepcopy(chunk)) 632 | break 633 | cmd = "x/" + word + hex(fd + capsize * 3) 634 | fd_bk = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 635 | if chunk["addr"] != fd_bk: 636 | chunk[ 637 | "memerror"] = "\033[31mdoubly linked list corruption {0} != {1} and \033[36m{2}\033[31m or \033[36m{3}\033[31m is broken".format( 638 | hex(chunk["addr"]), hex(fd_bk), hex(fd), hex(chunk["addr"])) 639 | bins.append(copy.deepcopy(chunk)) 640 | break 641 | except: 642 | chunk["memerror"] = "invaild memory" 643 | bins.append(copy.deepcopy(chunk)) 644 | break 645 | is_overlap = check_overlap(chunk["addr"], chunk["size"]) 646 | chunk["overlap"] = is_overlap 647 | free_mem_area[hex(chunk["addr"])] = copy.deepcopy((chunk["addr"], chunk["addr"] + chunk["size"], chunk)) 648 | bins.append(copy.deepcopy(chunk)) 649 | cmd = "x/" + word + hex(chunk["addr"] + capsize * 2) # find next 650 | chunk = {} 651 | chunk["addr"] = fd 652 | return bins 653 | 654 | 655 | def get_unsortbin(arena=None): 656 | global unsortbin 657 | if not arena: 658 | arena = main_arena 659 | unsortbin = [] 660 | chunkhead = {} 661 | cmd = "x/" + word + "&((struct malloc_state *)" + hex(arena) + ").bins" 662 | chunkhead["addr"] = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 663 | unsortbin = trace_normal_bin(chunkhead, arena) 664 | 665 | 666 | def get_smallbin(arena=None): 667 | global smallbin, tcache_enable, bin_corrupt 668 | if not arena: 669 | arena = main_arena 670 | smallbin = {} 671 | max_smallbin_size = 512 * int(capsize / 4) 672 | cmd = "x/" + word + "&((struct malloc_state *)" + hex(arena) + ").bins" 673 | bins_addr = int(gdb.execute(cmd, to_string=True).split(":")[0].split()[0].strip(), 16) 674 | cur_size = 8 if tcache_enable else capsize 675 | for size in range(capsize * 4, max_smallbin_size, cur_size * 2): 676 | chunkhead = {} 677 | idx = int((size / (capsize * 2))) - 1 678 | if tcache_enable and capsize == 4: 679 | idx = int(size / (cur_size * 2)) 680 | else: 681 | idx = int(size / (cur_size * 2)) - 1 682 | cmd = "x/" + word + hex(bins_addr + idx * capsize * 2) # calc the smallbin index 683 | chunkhead["addr"] = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 684 | try: 685 | bins = trace_normal_bin(chunkhead, arena) 686 | except: 687 | bin_corrupt = True 688 | bins = None 689 | if bins and len(bins) > 0: 690 | smallbin[hex(size)] = copy.deepcopy(bins) 691 | 692 | 693 | def largbin_index(size): 694 | if capsize == 8: 695 | if (size >> 6) <= 48: 696 | idx = 48 + (size >> 6) 697 | elif (size >> 9) <= 20: 698 | idx = 91 + (size >> 9) 699 | elif (size >> 12) <= 10: 700 | idx = 110 + (size >> 12) 701 | elif (size >> 15) <= 4: 702 | idx = 119 + (size >> 15) 703 | elif (size >> 18) <= 2: 704 | idx = 124 + (size >> 18) 705 | else: 706 | idx = 126 707 | else: 708 | if (size >> 6) <= 38: 709 | idx = 56 + (size >> 6) 710 | elif (size >> 9) <= 20: 711 | idx = 91 + (size >> 9) 712 | elif (size >> 12) <= 10: 713 | idx = 110 + (size >> 12) 714 | elif (size >> 15) <= 4: 715 | idx = 119 + (size >> 15) 716 | elif (size >> 18) <= 2: 717 | idx = 124 + (size >> 18) 718 | else: 719 | idx = 126 720 | return idx 721 | 722 | 723 | def get_largebin(arena=None): 724 | global largebin, bin_corrupt 725 | if not arena: 726 | arena = main_arena 727 | largebin = {} 728 | cmd = "x/" + word + "&((struct malloc_state *)" + hex(arena) + ").bins" 729 | bins_addr = int(gdb.execute(cmd, to_string=True).split(":")[0].split()[0].strip(), 16) 730 | for idx in range(64, 128): 731 | chunkhead = {} 732 | cmd = "x/" + word + hex(bins_addr + idx * capsize * 2 - 2 * capsize) # calc the largbin index 733 | chunkhead["addr"] = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 734 | try: 735 | bins = trace_normal_bin(chunkhead, arena) 736 | except: 737 | bin_corrupt = True 738 | bins = None 739 | if bins and len(bins) > 0: 740 | largebin[idx] = copy.deepcopy(bins) 741 | 742 | 743 | def get_system_mem(arena=None): 744 | global system_mem 745 | if not arena: 746 | arena = main_arena 747 | cmd = "x/" + word + "&((struct malloc_state *)" + hex(arena) + ").system_mem" 748 | system_mem = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 749 | 750 | 751 | def get_heap_info(arena=None): 752 | global main_arena, thread_arena, free_mem_area, top, bin_corrupt 753 | global enable_reveal_ptr, tcache_enable, tcache 754 | 755 | top = {} 756 | free_mem_area = {} 757 | bin_corrupt = False 758 | 759 | if get_libc_version() > 2.31: 760 | enable_reveal_ptr = True 761 | if arena: 762 | get_tcache_entry() 763 | get_system_mem(arena) 764 | get_unsortbin(arena) 765 | get_smallbin(arena) 766 | if trace_largebin: 767 | get_largebin(arena) 768 | get_fast_bin(arena) 769 | get_top_lastremainder(arena) 770 | return True 771 | 772 | set_main_arena() 773 | set_thread_arena() 774 | if thread_arena and enable_thread: 775 | get_tcache_entry() 776 | get_system_mem(thread_arena) 777 | get_unsortbin(thread_arena) 778 | get_smallbin(thread_arena) 779 | if trace_largebin: 780 | get_largebin(thread_arena) 781 | get_fast_bin(thread_arena) 782 | get_top_lastremainder(thread_arena) 783 | return True 784 | 785 | elif main_arena and not enable_thread: 786 | get_tcache_entry() 787 | get_system_mem() 788 | get_unsortbin() 789 | get_smallbin() 790 | if trace_largebin: 791 | get_largebin() 792 | get_fast_bin() 793 | get_top_lastremainder() 794 | return True 795 | return False 796 | 797 | 798 | def get_reg(reg): 799 | cmd = "info register " + reg 800 | result = int(gdb.execute(cmd, to_string=True).split()[1].strip(), 16) 801 | return result 802 | 803 | 804 | def trace_malloc(): 805 | global malloc_bp, free_bp, memalign_bp, realloc_bp 806 | 807 | malloc_bp = Malloc_Bp_handler("*" + "__libc_malloc") 808 | free_bp = Free_Bp_handler("*" + "__libc_free") 809 | memalign_bp = Memalign_Bp_handler("*" + "__libc_memalign") 810 | realloc_bp = Realloc_Bp_handler("*" + "__libc_realloc") 811 | if not get_heap_info(): 812 | print("Can't find heap info") 813 | return 814 | 815 | 816 | def dis_trace_malloc(): 817 | global malloc_bp, free_bp, memalign_bp, realloc_bp 818 | 819 | if malloc_bp: 820 | malloc_bp.delete() 821 | malloc_bp = None 822 | if free_bp: 823 | free_bp.delete() 824 | free_bp = None 825 | if memalign_bp: 826 | memalign_bp.delete() 827 | memalign_bp = None 828 | if realloc_bp: 829 | realloc_bp.delete() 830 | realloc_bp = None 831 | 832 | 833 | def find_overlap(chunk, bins): 834 | is_overlap = False 835 | count = 0 836 | for current in bins: 837 | if chunk["addr"] == current["addr"]: 838 | count += 1 839 | if count > 1: 840 | is_overlap = True 841 | return is_overlap 842 | 843 | 844 | def unlinkable(chunkaddr, fd=None, bk=None): 845 | try: 846 | cmd = "x/" + word + hex(chunkaddr + capsize) 847 | chunk_size = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) & 0xfffffffffffffff8 848 | cmd = "x/" + word + hex(chunkaddr + chunk_size) 849 | next_prev_size = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 850 | if not fd: 851 | cmd = "x/" + word + hex(chunkaddr + capsize * 2) 852 | fd = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 853 | if not bk: 854 | cmd = "x/" + word + hex(chunkaddr + capsize * 3) 855 | bk = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 856 | cmd = "x/" + word + hex(fd + capsize * 3) 857 | fd_bk = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 858 | cmd = "x/" + word + hex(bk + capsize * 2) 859 | bk_fd = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 860 | if chunk_size != next_prev_size: 861 | print( 862 | "\033[32mUnlinkable :\033[1;31m False (corrupted size chunksize(0x%x) != prev_size(0x%x)) ) \033[37m " % 863 | (chunk_size, next_prev_size)) 864 | elif (chunkaddr == fd_bk) and (chunkaddr == bk_fd): 865 | print("\033[32mUnlinkable :\033[1;33m True\033[37m") 866 | print("\033[32mResult of unlink :\033[37m") 867 | print( 868 | "\033[32m \033[1;34m FD->bk (\033[1;33m*0x%x\033[1;34m) = BK (\033[1;37m0x%x ->\033[1;33m 0x%x\033[1;34m)\033[37m " 869 | % (fd + capsize * 3, fd_bk, bk)) 870 | print( 871 | "\033[32m \033[1;34m BK->fd (\033[1;33m*0x%x\033[1;34m) = FD (\033[1;37m0x%x ->\033[1;33m 0x%x\033[1;34m)\033[37m " 872 | % (bk + capsize * 2, bk_fd, fd)) 873 | else: 874 | if chunkaddr != fd_bk: 875 | print("\033[32mUnlinkable :\033[1;31m False (FD->bk(0x%x) != (0x%x)) \033[37m " % (fd_bk, chunkaddr)) 876 | else: 877 | print("\033[32mUnlinkable :\033[1;31m False (BK->fd(0x%x) != (0x%x)) \033[37m " % (bk_fd, chunkaddr)) 878 | except: 879 | print("\033[32mUnlinkable :\033[1;31m False (FD or BK is corruption) \033[37m ") 880 | 881 | 882 | def freeable(victim): 883 | global fastchunk, system_mem 884 | chunkaddr = victim 885 | try: 886 | if not get_heap_info(): 887 | print("Can't find heap info") 888 | return 889 | cmd = "x/" + word + hex(chunkaddr) 890 | prev_size = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 891 | cmd = "x/" + word + hex(chunkaddr + capsize * 1) 892 | size = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 893 | cmd = "x/" + word + hex(chunkaddr + capsize * 2) 894 | fd = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 895 | cmd = "x/" + word + hex(chunkaddr + capsize * 3) 896 | bk = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 897 | prev_inuse = size & 1 898 | is_mmapd = (size >> 1) & 1 899 | non_main_arena = (size >> 2) & 1 900 | size = size & 0xfffffffffffffff8 901 | if is_mmapd: 902 | block = chunkaddr - prev_size 903 | total_size = prev_size + size 904 | if ((block | total_size) & (0xfff)) != 0: 905 | print( 906 | "\033[32mFreeable :\033[1;31m False -> Invalid pointer (((chunkaddr(0x%x) - prev_size(0x%x))|(prev_size(0x%x) + size(0x%x)))) & 0xfff != 0 \033[37m" 907 | % (chunkaddr, prev_size, prev_size, size)) 908 | return 909 | else: 910 | if chunkaddr > (2**(capsize * 8) - (size & 0xfffffffffffffff8)): 911 | print("\033[32mFreeable :\033[1;31m False -> Invalid pointer chunkaddr (0x%x) > -size (0x%x)\033[37m" % 912 | (chunkaddr, (2**(capsize * 8) - (size & 0xfffffffffffffff8)))) 913 | return 914 | if (chunkaddr & (capsize * 2 - 1)) != 0: 915 | print( 916 | "\033[32mFreeable :\033[1;31m False -> Invalid pointer misaligned chunkaddr (0x%x) & (0x%x) != 0\033[37m" 917 | % (chunkaddr, (capsize * 2 - 1))) 918 | return 919 | if (size < capsize * 4): 920 | print( 921 | "\033[32mFreeable :\033[1;31m False -> Chunkaddr (0x%x) invalid size (size(0x%x) < 0x%x )\033[37m" % 922 | (chunkaddr, size, capsize * 4)) 923 | return 924 | if (size & (capsize)) != 0: 925 | print( 926 | "\033[32mFreeable :\033[1;31m False -> Chunkaddr (0x%x) invalid size (size(0x%x) & 0x%x != 0 )\033[37m" 927 | % (chunkaddr, size, capsize)) 928 | return 929 | cmd = "x/" + word + hex(chunkaddr + size + capsize) 930 | nextsize = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 931 | nextchunk = chunkaddr + size 932 | status = nextsize & 1 933 | if size <= capsize * 0x10: # fastbin 934 | if nextsize < capsize * 4: 935 | print( 936 | "\033[32mFreeable :\033[1;31m False -> Chunkaddr (0x%x) invalid next size (size(0x%x) < 0x%x )\033[37m" 937 | % (chunkaddr, size, capsize * 4)) 938 | return 939 | if nextsize >= system_mem: 940 | print( 941 | "\033[32mFreeable :\033[1;31m False -> Chunkaddr (0x%x) invalid next size (size(0x%x) > system_mem(0x%x) )\033[37m" 942 | % (chunkaddr, size, system_mem)) 943 | return 944 | old = fastbin[int(size / 0x10) - 2][0]["addr"] 945 | if chunkaddr == old: 946 | print("\033[32mFreeable :\033[1;31m false -> Double free chunkaddr(0x%x) == 0x%x )\033[37m" % 947 | (chunkaddr, old)) 948 | return 949 | else: 950 | if chunkaddr == top["addr"]: 951 | print("\033[32mFreeable :\033[1;31m False -> Free top chunkaddr(0x%x) == 0x%x )\033[37m" % 952 | (chunkaddr, top["addr"])) 953 | return 954 | cmd = "x/" + word + hex(top["addr"] + capsize) 955 | topsize = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 956 | if nextchunk >= top["addr"] + topsize: 957 | print("\033[32mFreeable :\033[1;31m False -> Out of top chunkaddr(0x%x) > 0x%x )\033[37m" % 958 | (chunkaddr, top["addr"] + topsize)) 959 | return 960 | if status == 0: 961 | print( 962 | "\033[32mFreeable :\033[1;31m false -> Double free chunkaddr(0x%x) inused bit is not seted )\033[37m" 963 | % (chunkaddr)) 964 | return 965 | if nextsize < capsize * 4: 966 | print( 967 | "\033[32mFreeable :\033[1;31m False -> Chunkaddr (0x%x) invalid next size (size(0x%x) < 0x%x )\033[37m" 968 | % (chunkaddr, size, capsize * 4)) 969 | return 970 | if nextsize >= system_mem: 971 | print( 972 | "\033[32mFreeable :\033[1;31m False -> Chunkaddr (0x%x) invalid next size (size(0x%x) > system_mem(0x%x) )\033[37m" 973 | % (chunkaddr, size, system_mem)) 974 | return 975 | if not prev_inuse: 976 | cmd = "x/" + word + hex(chunkaddr - prev_size + capsize) 977 | prev_chunk_size = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 978 | 16) & 0xfffffffffffffff8 979 | if prev_size != prev_chunk_size: 980 | print("\033[32mFreeable :\033[1;31m False -> p->size(0x%x) != next->prevsize(0x%x) \033[37m" % 981 | (prev_chunk_size, prev_size)) 982 | return 983 | 984 | if len(unsortbin) > 0: 985 | bck = unsortbin[0]["addr"] 986 | cmd = "x/" + word + hex(bck + capsize * 2) 987 | fwd = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 988 | cmd = "x/" + word + hex(fwd + capsize * 3) 989 | bk = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 990 | if bk != bck: 991 | print( 992 | "\033[32mFreeable :\033[1;31m False -> Corrupted unsorted chunkaddr fwd->bk(0x%x) != bck(0x%x) )\033[37m" 993 | % (bk, bck)) 994 | return 995 | print("\033[32mFreeable :\033[1;33m True\033[37m") 996 | except: 997 | print("Can't access memory") 998 | 999 | 1000 | def get_heapbase(): 1001 | if (main_arena and not enable_thread) or thread_arena == main_arena: 1002 | heapbase = int(gdb.execute("x/" + word + " &mp_.sbrk_base", to_string=True).split(":")[1].strip(), 16) 1003 | elif thread_arena: 1004 | arena_size = int(gdb.execute("p sizeof(main_arena)", to_string=True).split("=")[1].strip(), 16) 1005 | heapbase = (thread_arena + arena_size + 0xf) & ~0xf 1006 | else: 1007 | return None 1008 | return heapbase 1009 | 1010 | 1011 | def chunkinfo(victim): 1012 | global fastchunk 1013 | 1014 | chunkaddr = victim 1015 | try: 1016 | if not get_heap_info(): 1017 | print("Can't find heap info") 1018 | return 1019 | cmd = "x/" + word + hex(chunkaddr) 1020 | prev_size = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 1021 | cmd = "x/" + word + hex(chunkaddr + capsize * 1) 1022 | size = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 1023 | cmd = "x/" + word + hex(chunkaddr + capsize * 2) 1024 | fd = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 1025 | cmd = "x/" + word + hex(chunkaddr + capsize * 3) 1026 | bk = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 1027 | cmd = "x/" + word + hex(chunkaddr + (size & 0xfffffffffffffff8) + capsize) 1028 | nextsize = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 1029 | status = nextsize & 1 1030 | print("==================================") 1031 | print(" Chunk info ") 1032 | print("==================================") 1033 | if status: 1034 | if chunkaddr in fastchunk: 1035 | print("\033[1;32mStatus : \033[1;34m Freed (fast) \033[37m") 1036 | elif chunkaddr in all_tcache_entry: 1037 | print("\033[1;32mStatus : \033[1;34m Freed (tcache) \033[37m") 1038 | else: 1039 | print("\033[1;32mStatus : \033[31m Used \033[37m") 1040 | else: 1041 | print("\033[1;32mStatus : \033[1;34m Freed \033[37m") 1042 | unlinkable(chunkaddr, fd, bk) 1043 | freeable(chunkaddr) 1044 | print("\033[32mprev_size :\033[37m 0x%x " % prev_size) 1045 | print("\033[32msize :\033[37m 0x%x " % (size & 0xfffffffffffffff8)) 1046 | print("\033[32mprev_inused :\033[37m %x " % (size & 1)) 1047 | print("\033[32mis_mmap :\033[37m %x " % (size & 2)) 1048 | print("\033[32mnon_mainarea :\033[37m %x " % (size & 4)) 1049 | if not status: 1050 | print("\033[32mfd :\033[37m 0x%x " % fd) 1051 | print("\033[32mbk :\033[37m 0x%x " % bk) 1052 | if size >= 512 * (capsize / 4): 1053 | cmd = "x/" + word + hex(chunkaddr + capsize * 4) 1054 | fd_nextsize = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 1055 | cmd = "x/" + word + hex(chunkaddr + capsize * 5) 1056 | bk_nextsize = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 1057 | print("\033[32mfd_nextsize :\033[37m 0x%x " % fd_nextsize) 1058 | print("\033[32mbk_nextsize :\033[37m 0x%x " % bk_nextsize) 1059 | except: 1060 | print("Can't access memory") 1061 | 1062 | 1063 | def freeptr(ptr): 1064 | freeable(ptr - capsize * 2) 1065 | 1066 | 1067 | def chunkptr(ptr): 1068 | chunkinfo(ptr - capsize * 2) 1069 | 1070 | 1071 | def mergeinfo(victim): 1072 | global fastchunk 1073 | 1074 | chunkaddr = victim 1075 | try: 1076 | if not get_heap_info(): 1077 | print("Can't find heap info") 1078 | return 1079 | print("==================================") 1080 | print(" Merge info ") 1081 | print("==================================") 1082 | cmd = "x/" + word + hex(chunkaddr) 1083 | prev_size = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 1084 | cmd = "x/" + word + hex(chunkaddr + capsize * 1) 1085 | size = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 1086 | cmd = "x/" + word + hex(chunkaddr + (size & 0xfffffffffffffff8) + capsize) 1087 | nextsize = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 1088 | status = nextsize & 1 1089 | if status: 1090 | if chunkaddr in fastchunk: 1091 | print("The chunk is freed") 1092 | else: 1093 | if (size & 0xfffffffffffffff8) <= 0x80: 1094 | print("The chunk will be a\033[32m fastchunk\033[37m") 1095 | else: 1096 | prev_status = size & 1 1097 | next_chunk = chunkaddr + (size & 0xfffffffffffffff8) 1098 | cmd = "x/" + word + hex(next_chunk + (nextsize & 0xfffffffffffffff8) + capsize) 1099 | if next_chunk != top["addr"]: 1100 | next_nextsize = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 1101 | next_status = next_nextsize & 1 1102 | if not prev_status: # if prev chunk is freed 1103 | prev_chunk = chunkaddr - prev_size 1104 | if next_chunk == top["addr"]: # if next chunk is top 1105 | print("The chunk will merge into top , top will be \033[1;33m0x%x\033[37m " % prev_chunk) 1106 | print("\033[32mUnlink info : \033[1;33m0x%x\033[37m" % prev_chunk) 1107 | unlinkable(prev_chunk) 1108 | elif not next_status: # if next chunk is freed 1109 | print("The chunk and \033[1;33m0x%x\033[0m will merge into \033[1;33m0x%x\033[37m" % 1110 | (next_chunk, prev_chunk)) 1111 | print("\033[32mUnlink info : \033[1;33m0x%x\033[37m" % prev_chunk) 1112 | unlinkable(prev_chunk) 1113 | print("\033[32mUnlink info : \033[1;33m0x%x\033[37m" % next_chunk) 1114 | unlinkable(next_chunk) 1115 | else: 1116 | print("The chunk will merge into \033[1;33m0x%x\033[37m" % prev_chunk) 1117 | print("\033[32mUnlink info : \033[1;33m0x%x\033[37m" % prev_chunk) 1118 | unlinkable(prev_chunk) 1119 | else: 1120 | if next_chunk == top["addr"]: # if next chunk is top 1121 | print("The chunk will merge into top , top will be \033[1;34m0x%x\033[37m" % chunkaddr) 1122 | elif not next_status: # if next chunk is freed 1123 | print("The chunk will merge with \033[1;33m0x%x\033[37m" % next_chunk) 1124 | print("\033[32mUnlink info : \033[1;33m0x%x\033[37m" % next_chunk) 1125 | unlinkable(next_chunk) 1126 | else: 1127 | print("The chunk will not merge with other") 1128 | else: 1129 | print("The chunk is freed") 1130 | except: 1131 | print("Can't access memory") 1132 | 1133 | 1134 | def force(target): 1135 | if not get_heap_info(): 1136 | print("Can't find heap info") 1137 | return 1138 | if target % capsize != 0: 1139 | print("Not alignment") 1140 | else: 1141 | nb = target - top["addr"] - capsize * 2 1142 | print("nb = %d" % nb) 1143 | 1144 | 1145 | def putfastbin(arena=None): 1146 | if not get_heap_info(arena): 1147 | print("Can't find heap info") 1148 | return False 1149 | for i, bins in enumerate(fastbin): 1150 | cur_size = (capsize * 2) * (i + 2) 1151 | print("\033[32m(0x%02x) fastbin[%d]:\033[37m " % (cur_size, i), end="") 1152 | for chunk in bins: 1153 | if "memerror" in chunk: 1154 | print("\033[31m0x%x (%s)\033[37m" % (chunk["addr"], chunk["memerror"]), end="") 1155 | elif chunk["size"] != cur_size and chunk["addr"] != 0: 1156 | print("\033[36m0x%x (size error (0x%x))\033[37m" % (chunk["addr"], chunk["size"]), end="") 1157 | elif chunk["overlap"] and chunk["overlap"][0]: 1158 | print("\033[31m0x%x (overlap chunk with \033[36m0x%x(%s)\033[31m )\033[37m" % 1159 | (chunk["addr"], chunk["overlap"][0]["addr"], chunk["overlap"][1]), 1160 | end="") 1161 | elif chunk == bins[0]: 1162 | print("\033[34m0x%x\033[37m" % chunk["addr"], end="") 1163 | else: 1164 | if print_overlap: 1165 | if find_overlap(chunk, bins): 1166 | print("\033[31m0x%x\033[37m" % chunk["addr"], end="") 1167 | else: 1168 | print("0x%x" % chunk["addr"], end="") 1169 | else: 1170 | print("0x%x" % chunk["addr"], end="") 1171 | if chunk != bins[-1]: 1172 | print(" --> ", end="") 1173 | print("") 1174 | return True 1175 | 1176 | 1177 | def put_tcache(): 1178 | if not tcache_enable: 1179 | return 1180 | for i, entry in enumerate(tcache_entry): 1181 | if capsize == 4: 1182 | cur_size = 16 * (i + 1) 1183 | else: 1184 | cur_size = 16 * (i + 2) 1185 | if len(tcache_entry[i]) > 0: 1186 | print("\033[33;1m(0x%02x) tcache_entry[%d]\033[32m(%d)\033[33;1m:\033[37m " % 1187 | (cur_size, i, tcache_count[i]), 1188 | end="") 1189 | elif tcache_count[i] > 0: 1190 | print("\033[33;1m(0x%02x) tcache_entry[%d]\033[31;1m(%d)\033[33;1m:\033[37m 0\n" % 1191 | (cur_size, i, tcache_count[i]), 1192 | end="") 1193 | for chunk in entry: 1194 | if "memerror" in chunk: 1195 | print("\033[31m0x%x (%s)\033[37m" % (chunk["addr"] + capsize * 2, chunk["memerror"]), end="") 1196 | elif chunk["overlap"] and chunk["overlap"][0]: 1197 | print("\033[31m0x%x (overlap chunk with \033[36m0x%x(%s)\033[31m )\033[37m" % 1198 | (chunk["addr"] + capsize * 2, chunk["overlap"][0]["addr"], chunk["overlap"][1]), 1199 | end="") 1200 | elif chunk == entry[0]: 1201 | print("\033[34m0x%x\033[37m" % (chunk["addr"] + capsize * 2), end="") 1202 | else: 1203 | if print_overlap: 1204 | if find_overlap(chunk, entry): 1205 | print("\033[31m0x%x\033[37m" % chunk["addr"], end="") 1206 | else: 1207 | print("0x%x" % (chunk["addr"] + capsize * 2), end="") 1208 | else: 1209 | print("0x%x" % (chunk["addr"] + capsize * 2), end="") 1210 | if chunk != entry[-1]: 1211 | print(" --> ", end="") 1212 | if len(tcache_entry[i]) > 0: 1213 | print("") 1214 | return True 1215 | 1216 | 1217 | def put_unsorted(pad=False): 1218 | if pad: 1219 | s = 'unsortbin'.rjust(21, ' ') 1220 | else: 1221 | s = 'unsortbin' 1222 | print("\033[35m%s:\033[37m " % s, end="") 1223 | if unsortbin and len(unsortbin) > 0: 1224 | for chunk in unsortbin: 1225 | if "memerror" in chunk: 1226 | print("\033[31m0x%x (%s)\033[37m" % (chunk["addr"], chunk["memerror"]), end="") 1227 | elif chunk["overlap"] and chunk["overlap"][0]: 1228 | print("\033[31m0x%x (overlap chunk with \033[36m0x%x(%s)\033[31m )\033[37m" % 1229 | (chunk["addr"], chunk["overlap"][0]["addr"], chunk["overlap"][1]), 1230 | end="") 1231 | elif chunk == unsortbin[-1]: 1232 | print("\033[34m0x%x\033[37m \33[33m(size : 0x%x)\033[37m" % (chunk["addr"], chunk["size"]), end="") 1233 | else: 1234 | print("0x%x \33[33m(size : 0x%x)\033[37m" % (chunk["addr"], chunk["size"]), end="") 1235 | if chunk != unsortbin[-1]: 1236 | print(" <--> ", end="") 1237 | print("") 1238 | else: 1239 | print(0) # no chunk in unsortbin 1240 | 1241 | 1242 | def putheapinfo(arena=None): 1243 | if not putfastbin(arena): 1244 | return 1245 | if "memerror" in top: 1246 | print("\033[35m %20s:\033[31m 0x%x \033[33m(size : 0x%x)\033[31m (%s)\033[37m " % 1247 | ("top", top["addr"], top["size"], top["memerror"])) 1248 | else: 1249 | print("\033[35m %20s:\033[34m 0x%x \033[33m(size : 0x%x)\033[37m " % ("top", top["addr"], top["size"])) 1250 | 1251 | print("\033[35m %20s:\033[34m 0x%x \033[33m(size : 0x%x)\033[37m " % 1252 | ("last_remainder", last_remainder["addr"], last_remainder["size"])) 1253 | put_unsorted(True) 1254 | 1255 | for size, bins in smallbin.items(): 1256 | cur_size = 8 if tcache_enable else capsize 1257 | idx = int(int(size, 16) / (cur_size * 2)) - 2 1258 | print("\033[33m(0x%03x) %s[%2d]:\033[37m " % (int(size, 16), "smallbin", idx), end="") 1259 | for chunk in bins: 1260 | if "memerror" in chunk: 1261 | print("\033[31m0x%x (%s)\033[37m" % (chunk["addr"], chunk["memerror"]), end="") 1262 | elif chunk["size"] != int(size, 16): 1263 | print("\033[36m0x%x (size error (0x%x))\033[37m" % (chunk["addr"], chunk["size"]), end="") 1264 | elif chunk["overlap"] and chunk["overlap"][0]: 1265 | print("\033[31m0x%x (overlap chunk with \033[36m0x%x(%s)\033[31m )\033[37m" % 1266 | (chunk["addr"], chunk["overlap"][0]["addr"], chunk["overlap"][1]), 1267 | end="") 1268 | elif chunk == bins[-1]: 1269 | print("\033[34m0x%x\033[37m" % chunk["addr"], end="") 1270 | else: 1271 | print("0x%x " % chunk["addr"], end="") 1272 | if chunk != bins[-1]: 1273 | print(" <--> ", end="") 1274 | print("") 1275 | for idx, bins in largebin.items(): 1276 | print("\033[33m %15s[%2d]:\033[37m " % ("largebin", idx - 64), end="") 1277 | for chunk in bins: 1278 | if "memerror" in chunk: 1279 | print("\033[31m0x%x (%s)\033[37m" % (chunk["addr"], chunk["memerror"]), end="") 1280 | elif chunk["overlap"] and chunk["overlap"][0]: 1281 | print("\033[31m0x%x (overlap chunk with \033[36m0x%x(%s)\033[31m )\033[37m" % 1282 | (chunk["addr"], chunk["overlap"][0]["addr"], chunk["overlap"][1]), 1283 | end="") 1284 | elif largbin_index(chunk["size"]) != idx: 1285 | print("\033[31m0x%x (incorrect bin size :\033[36m 0x%x\033[31m)\033[37m" % 1286 | (chunk["addr"], chunk["size"]), 1287 | end="") 1288 | elif chunk == bins[-1]: 1289 | print("\033[34m0x%x\033[37m \33[33m(size : 0x%x)\033[37m" % (chunk["addr"], chunk["size"]), end="") 1290 | else: 1291 | print("0x%x \33[33m(size : 0x%x)\033[37m" % (chunk["addr"], chunk["size"]), end="") 1292 | if chunk != bins[-1]: 1293 | print(" <--> ", end="") 1294 | print("") 1295 | if not arena: 1296 | put_tcache() 1297 | if bin_corrupt: 1298 | print("\033[31m Some bins is corrupted !\033[37m") 1299 | 1300 | 1301 | def putarenainfo(): 1302 | set_main_arena() 1303 | cur_arena = 0 1304 | if main_arena: 1305 | try: 1306 | if capsize == 4: 1307 | nextoff = 0x10d * capsize + 0xc 1308 | else: 1309 | nextoff = 0x10d * capsize 1310 | count = 0 1311 | print(" Main Arena ".center(50, "=")) 1312 | putheapinfo(main_arena) 1313 | cmd = "x/" + word + "&main_arena.next" 1314 | cur_arena = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 1315 | while cur_arena != main_arena: 1316 | count += 1 1317 | print((" Arena " + str(count) + " ").center(50, "=")) 1318 | putheapinfo(cur_arena) 1319 | cur_arena = int( 1320 | gdb.execute("x/" + word + hex(cur_arena + nextoff), to_string=True).split(":")[1].strip(), 16) 1321 | except: 1322 | print("Memory Error (heap)") 1323 | else: 1324 | print("Can't find heap info ") 1325 | 1326 | 1327 | def putheapinfoall(): 1328 | cur_thread_id = get_curthread() 1329 | all_threads = get_all_threads() 1330 | for thread_id in all_threads: 1331 | if thread_id == cur_thread_id: 1332 | print("\033[33;1m" + (" Thread " + str(thread_id) + " ").center(50, "=") + "\033[0m", end="") 1333 | else: 1334 | print((" Thread " + str(thread_id) + " ").center(50, "="), end="") 1335 | result = thread_cmd_execute(thread_id, "heapinfo") 1336 | print(result.split("):")[1], end="") 1337 | 1338 | 1339 | def putinused(): 1340 | print("\033[33m %s:\033[37m " % "inused ", end="") 1341 | for addr, (start, end, chunk) in alloc_mem_area.items(): 1342 | print("0x%x," % (chunk["addr"]), end="") 1343 | print("") 1344 | 1345 | 1346 | def parse_heap(arena=None): 1347 | if not get_heap_info(arena): 1348 | print("can't find heap info") 1349 | return 1350 | 1351 | hb = get_heapbase() 1352 | chunkaddr = hb 1353 | if not chunkaddr: 1354 | print("Can't find heap") 1355 | return 1356 | print('\033[1;33m{:<20}{:<20}{:<21}{:<20}{:<18}{:<18}\033[0m'.format('addr', 'prev', 'size', 'status', 'fd', 'bk')) 1357 | while chunkaddr != top["addr"]: 1358 | try: 1359 | cmd = "x/" + word + hex(chunkaddr) 1360 | prev_size = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 1361 | cmd = "x/" + word + hex(chunkaddr + capsize * 1) 1362 | size = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 1363 | cmd = "x/" + word + hex(chunkaddr + capsize * 2) 1364 | if size == 0 and chunkaddr == hb: 1365 | chunkaddr += capsize * 2 1366 | continue 1367 | fd = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 1368 | cmd = "x/" + word + hex(chunkaddr + capsize * 3) 1369 | bk = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 1370 | cmd = "x/" + word + hex(chunkaddr + (size & 0xfffffffffffffff8) + capsize) 1371 | nextsize = int(gdb.execute(cmd, to_string=True).split(":")[1].strip(), 16) 1372 | status = nextsize & 1 1373 | size = size & 0xfffffffffffffff8 1374 | if size == 0: 1375 | print("\033[31mCorrupt ?! \033[0m(size == 0) (0x%x)" % chunkaddr) 1376 | break 1377 | if status: 1378 | if chunkaddr in fastchunk or chunkaddr in all_tcache_entry: 1379 | msg = "\033[1;34m Freed \033[0m" 1380 | print('0x{:<18x}0x{:<18x}0x{:<18x}{:<16}{:>18}{:>18}'.format(chunkaddr, prev_size, size, msg, 1381 | hex(fd), "None")) 1382 | else: 1383 | msg = "\033[31m Used \033[0m" 1384 | print('0x{:<18x}0x{:<18x}0x{:<18x}{:<16}{:>18}{:>18}'.format(chunkaddr, prev_size, size, msg, 1385 | "None", "None")) 1386 | else: 1387 | msg = "\033[1;34m Freed \033[0m" 1388 | print('0x{:<18x}0x{:<18x}0x{:<18x}{:<16}{:>18}{:>18}'.format(chunkaddr, prev_size, size, msg, hex(fd), 1389 | hex(bk))) 1390 | chunkaddr = chunkaddr + (size & 0xfffffffffffffff8) 1391 | 1392 | if chunkaddr > top["addr"]: 1393 | print("\033[31mCorrupt ?!\033[0m") 1394 | break 1395 | except: 1396 | print("Corrupt ?!") 1397 | break 1398 | 1399 | 1400 | def fastbin_idx(size): 1401 | if capsize == 8: 1402 | return (size >> 4) - 2 1403 | else: 1404 | return (size >> 3) - 2 1405 | 1406 | 1407 | def fake_fast(addr, size): 1408 | if not get_heap_info(): 1409 | print("Can't find heap info") 1410 | return 1411 | result = [] 1412 | idx = fastbin_idx(size) 1413 | chunk_size = size & 0xfffffffffffffff8 1414 | start = addr - chunk_size 1415 | chunk_data = gdb.selected_inferior().read_memory(start, chunk_size) 1416 | for offset in range(chunk_size - 4): 1417 | fake_size = u32(chunk_data[offset:offset + 4]) 1418 | if fastbin_idx(fake_size) == idx: 1419 | if ((fake_size & 2 == 2) and (fake_size & 4 == 4)) or (fake_size & 4 == 0): 1420 | padding = addr - (start + offset - capsize) - capsize * 2 1421 | result.append((start + offset - capsize, padding)) 1422 | return result 1423 | 1424 | 1425 | def get_fake_fast(addr, size=None): 1426 | fast_max = int(gdb.execute("x/" + word + "&global_max_fast", to_string=True).split(":")[1].strip(), 16) 1427 | if not fast_max: 1428 | fast_max = capsize * 0x10 1429 | if size: 1430 | chunk_list = fake_fast(addr, size) 1431 | for fakechunk in chunk_list: 1432 | if len(chunk_list) > 0: 1433 | print("\033[1;33mfake chunk : \033[1;0m0x{:<12x}\033[1;33m padding :\033[1;0m {:<8d}".format( 1434 | fakechunk[0], fakechunk[1])) 1435 | else: 1436 | for i in range(int(fast_max / (capsize * 2) - 1)): 1437 | size = capsize * 2 * 2 + i * capsize * 2 1438 | chunk_list = fake_fast(addr, size) 1439 | if len(chunk_list) > 0: 1440 | print("-- size : %s --" % hex(size)) 1441 | for fakechunk in chunk_list: 1442 | print("\033[1;33mfake chunk :\033[1;0m 0x{:<12x}\033[1;33m padding :\033[1;0m {:<8d}".format( 1443 | fakechunk[0], fakechunk[1])) 1444 | 1445 | 1446 | def check_heap(addr, print_num=4): 1447 | addr = int(addr.cast(gdb.lookup_type('long'))) 1448 | if print_num == 'all': 1449 | print_num = 0xffff 1450 | print_num = int(print_num) 1451 | count = 0 1452 | found = False 1453 | for record in reversed(all_record): 1454 | if record[1] <= addr <= record[2]: 1455 | found = True 1456 | count += 1 1457 | if count > print_num: 1458 | break 1459 | if record[0] == "malloc": 1460 | print('================================== \033[1;32m', end='') # green 1461 | else: 1462 | print('================================== \033[1;31m', end='') # red 1463 | print('{}\033[0;37m =================================='.format(record[0])) 1464 | print("\033[32m" + 'start:' + "\033[37m", hex(record[1])) 1465 | print("\033[32m" + 'end: ' + "\033[37m", hex(record[2])) 1466 | print('\033[34mbacktrace:\033[37m') 1467 | print(record[3]) 1468 | if not found: 1469 | print('\033[1;31mNot found!\033[0;37m') # red 1470 | --------------------------------------------------------------------------------