├── .gitignore ├── LICENSE ├── README.md ├── __init__.py ├── generate_plugininfo.py ├── img └── DeGObfuscate.gif └── plugin.json /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__ 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2020 Kryptos Logic LLC 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DeGObfuscate (v1.0.2) 2 | Author: **Jamie Hankins** 3 | 4 | _De-obfuscates strings inside of obfuscated Go binaries_ 5 | 6 | ## Description: 7 | 8 | This plugin implements a simple LLIL emulator to statically de-obfuscate simple string obfuscation such as the obfuscations done by [gobfuscate](https://github.com/unixpickle/gobfuscate). 9 | 10 | To activate it, use either the `Tools` menu or the command palette. It offers two modes, the first will attempt to analyze the current function while the other will attempt to find all functions that are merely obfuscated strings and rename them. If the function name cannot be cleanly replaced, a comment will be added at all call locations with the detailed deobfuscated string in addition to the truncated rename. 11 | 12 | ![](https://github.com/jamie-34254/binja_degobfuscate/blob/master/img/DeGObfuscate.gif?raw=true) 13 | 14 | 15 | ## Installation Instructions 16 | 17 | ### Darwin 18 | 19 | no special instructions, package manager is recommended 20 | 21 | ### Windows 22 | 23 | no special instructions, package manager is recommended 24 | 25 | ### Linux 26 | 27 | no special instructions, package manager is recommended 28 | 29 | ## Minimum Version 30 | 31 | This plugin requires the following minimum version of Binary Ninja: 32 | 33 | * 1528 34 | 35 | 36 | ## License 37 | 38 | This plugin is released under a MIT license. 39 | ## Metadata Version 40 | 41 | 2 42 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding: utf-8 3 | 4 | import os.path 5 | import struct 6 | import re 7 | from binaryninja import * 8 | 9 | function_name_regex = re.compile(r'[\W_]+') 10 | Settings().register_group("degobfuscate", "DeGObfuscate") 11 | Settings().register_setting("degobfuscate.prefix", """ 12 | { 13 | "title" : "Default function prefix", 14 | "type" : "string", 15 | "default" : "str_", 16 | "description" : "The string prefix that will be put in front of a shortened string name for deobfuscated functions." 17 | } 18 | """) 19 | Settings().register_setting("degobfuscate.maxlength", """ 20 | { 21 | "title" : "Maximum Length", 22 | "type" : "number", 23 | "default" : 32, 24 | "description" : "The maimum string length before the de-obfuscated string will be truncated when used in renaming the function. String comments will be added if the string is truncated." 25 | } 26 | """) 27 | Settings().register_setting("degobfuscate.highlight", """ 28 | { 29 | "title" : "Debug Highlights", 30 | "type" : "boolean", 31 | "default" : false, 32 | "description" : "Whether or not to add highlights to emulated code, useful for debugging the emulation." 33 | } 34 | """) 35 | 36 | def handle_deref(bv, deref_size, deref_addr): 37 | br = BinaryReader(bv) 38 | br.seek(deref_addr) 39 | data = br.read(deref_size) 40 | return data 41 | 42 | class EmuMagic(object): 43 | def _get_struct_fmt(self, size, signed): 44 | structfmt = {1: 'B', 2: 'H', 4: 'L', 8: 'Q', 16: 'QQ'} 45 | fmt = structfmt[size] 46 | if signed: 47 | fmt = fmt.lower() 48 | return ( 49 | '<' if self.arch.endianness == Endianness.LittleEndian 50 | else '' 51 | ) + fmt 52 | 53 | def read_memory(self, location, size): 54 | def get_data(addr, size): 55 | for segment in self.bv.segments: 56 | if addr >= segment.start and addr <= segment.end: 57 | return self.bv.read(addr, size) 58 | return self.memory[addr:addr+size] 59 | 60 | if location < 0: 61 | raise Exception("Negative memory reading, something is broken") 62 | 63 | if size <= 8: 64 | return struct.unpack(self._get_struct_fmt(size, False), get_data(location, size))[0] 65 | else: 66 | if size != 16: 67 | raise Exception("TODO: Fix reads of size 16 bytes+") 68 | 69 | a = struct.unpack(self._get_struct_fmt(8, False), get_data(location, 8))[0] 70 | b = struct.unpack(self._get_struct_fmt(8, False), get_data(location + 8, 8))[0] 71 | return (b << 64) + a 72 | 73 | def write_memory(self, addr, size, value): 74 | signed = value < 0 75 | if size <= 8: 76 | d = struct.pack(self._get_struct_fmt(size, signed), value) 77 | self.memory[addr:addr+size] = d 78 | else: 79 | if size != 16: 80 | raise Exception("TODO: Fix reads of size 16 bytes+") 81 | self.write_memory(addr, 8, (value >> 0) % 2**64) 82 | self.write_memory(addr + 8, 8, (value >> 64) % 2**64) 83 | 84 | def set_register(self, inst, value): 85 | register_name = inst.dest.name 86 | register_info = self.arch.regs[register_name] 87 | # Are we setting a partial register or the full width one? 88 | if register_name == register_info.full_width_reg: 89 | self.registers[register_name] = value 90 | return value 91 | 92 | # from https://github.com/joshwatson/emilator/blob/master/emilator.py#L139-L148on/emilator/blob/master/emilator.py#L139-L148 93 | # mask off the value that will be replaced 94 | full_width_reg_info = self.arch.regs[register_info.full_width_reg] 95 | full_width_reg_value = self.registers[full_width_reg_info.full_width_reg] 96 | 97 | # https://reverseengineering.stackexchange.com/a/14610 98 | # 32 bit ops will clear the top 32 bits 99 | if register_info.extend == ImplicitRegisterExtend.ZeroExtendToFullWidth: 100 | full_width_reg_value = value 101 | elif register_info.extend == ImplicitRegisterExtend.NoExtend: 102 | # mask off the value that will be replaced 103 | mask = (1 << register_info.size * 8) - 1 104 | full_mask = (1 << full_width_reg_info.size * 8) - 1 105 | reg_bits = mask << (register_info.offset * 8) 106 | 107 | full_width_reg_value &= full_mask ^ reg_bits 108 | full_width_reg_value |= value << register_info.offset * 8 109 | 110 | self.registers[register_info.full_width_reg] = full_width_reg_value 111 | return value 112 | 113 | def print_registers(self, prefix): 114 | log_debug(f"{prefix} | {self.registers}") 115 | 116 | # Pop a value from the stack 117 | def stack_pop(self, size): 118 | sp = self.arch.stack_pointer 119 | self.registers[sp] += size 120 | return self.read_memory(self.registers[sp], size) 121 | 122 | # Push a value onto the stack 123 | def stack_push(self, value, size): 124 | sp = self.arch.stack_pointer 125 | self.write_memory(self.registers[sp], size, value) 126 | self.registers[sp] -= size 127 | return self.registers[sp] 128 | 129 | def handle_LLIL_TAILCALL(self, expr): 130 | callee = self.handle(expr.dest) 131 | callee_func = self.bv.get_function_at(callee) 132 | log_debug(f"LLIL_TAILCALL: We're jumping to {callee_func.name}") 133 | self.instructions = callee_func.llil 134 | self.ip = 0 135 | 136 | def handle_LLIL_CALL(self, expr): 137 | callee = self.handle(expr.dest) 138 | callee_func = self.bv.get_function_at(callee) 139 | 140 | slicebytetostring_sym = self.bv.get_symbols_by_name("go.runtime.slicebytetostring") or self.bv.get_symbols_by_name("runtime.slicebytetostring") or self.bv.get_symbols_by_name("_runtime.slicebytetostring") or self.bv.get_symbols_by_name("runtime_slicebytetostring") or self.bv.get_symbols_by_name("_runtime_slicebytetostring") 141 | slicebytetostring = self.bv.get_function_at(slicebytetostring_sym[0].address) 142 | if callee_func == slicebytetostring: 143 | log_debug("LLIL_CALL: Avoiding call to runtime function, we are out of here!") 144 | # Setting the IP to overflow the available instructions to halt execution 145 | self.ip = len(self.instructions) + 1 146 | return 147 | ret_address = self.instructions[self.ip + 1].address 148 | log_debug(f"LLIL_CALL: We're jumping to {callee_func.name} and we'll come back to {hex(ret_address)}") 149 | self.stack_push(ret_address, self.arch.address_size) 150 | self.instructions = callee_func.llil 151 | self.ip = 0 152 | 153 | def handle_LLIL_RET(self, expr): 154 | ret_addr = self.stack_pop(self.arch.address_size) 155 | ret_func = self.bv.get_functions_containing(ret_addr)[0] 156 | self.instructions = ret_func.llil 157 | ret_il = ret_func.get_low_level_il_at(ret_addr) 158 | self.ip = ret_il.instr_index 159 | log_debug(f"LLIL_RET: Returning to {ret_func.name} @ {hex(ret_addr)} and IP is becoming: {self.ip}") 160 | 161 | def handle_LLIL_PUSH(self, expr): 162 | return self.stack_push(self.handle(expr.src), expr.size) 163 | 164 | def handle_LLIL_POP(self, expr): 165 | return self.stack_pop(expr.size) 166 | 167 | def handle_LLIL_SET_FLAG(self, inst): 168 | flag = inst.dest.index 169 | value = self.handle(inst.src) 170 | self.flags[flag] = value 171 | return 172 | 173 | def handle_LLIL_FLAG(self, inst): 174 | flag = inst.src.index 175 | return self.flags.get(flag, False) 176 | 177 | def handle_LLIL_XOR(self, inst): 178 | left = self.handle(inst.left) 179 | right = self.handle(inst.right) 180 | log_debug("DeGObfuscate: XOR " + chr(left ^ right)) 181 | self.output += chr(left ^ right) 182 | return left ^ right 183 | 184 | def handle_LLIL_ZX(self, expr): 185 | return self.handle(expr.src) 186 | 187 | def handle_LLIL_GOTO(self, expr): 188 | self.ip = expr.dest 189 | 190 | def handle_LLIL_STORE(self, inst): 191 | addr = self.handle(inst.dest) 192 | value = self.handle(inst.src) 193 | self.write_memory(addr, inst.size, value) 194 | 195 | def handle_LLIL_CMP_NE(self, inst): 196 | return self.handle(inst.left) != self.handle(inst.right) 197 | 198 | def handle_LLIL_CMP_E(self, inst): 199 | return self.handle(inst.left) == self.handle(inst.right) 200 | 201 | def handle_LLIL_AND(self, inst): 202 | return self.handle(inst.left) & self.handle(inst.right) 203 | 204 | # Signed less than or equal 205 | def handle_LLIL_CMP_SLE(self, inst): 206 | left = self.handle(inst.left) 207 | right = self.handle(inst.right) 208 | return left <= right 209 | 210 | # Signed less than 211 | def handle_LLIL_CMP_SLT(self, inst): 212 | left = self.handle(inst.left) 213 | right = self.handle(inst.right) 214 | return left < right 215 | 216 | # Signed greater than 217 | def handle_LLIL_CMP_SGT(self, inst): 218 | left = self.handle(inst.left) 219 | right = self.handle(inst.right) 220 | return left > right 221 | 222 | # Signed greater than or equal 223 | def handle_LLIL_CMP_SGE(self, inst): 224 | left = self.handle(inst.left) 225 | right = self.handle(inst.right) 226 | return left >= right 227 | 228 | # Unsigned less than or equal 229 | def handle_LLIL_CMP_ULE(self, inst): 230 | left = int(self.handle(inst.left)) 231 | right = int(self.handle(inst.right)) 232 | return left <= right 233 | 234 | # Unsigned greater than or equal 235 | def handle_LLIL_CMP_UGE(self, inst): 236 | left = int(self.handle(inst.left)) 237 | right = int(self.handle(inst.right)) 238 | return left >= right 239 | 240 | # Unsigned greater than 241 | def handle_LLIL_CMP_UGT(self, inst): 242 | left = int(self.handle(inst.left)) 243 | right = int(self.handle(inst.right)) 244 | return left > right 245 | 246 | # Unsigned less than 247 | def handle_LLIL_CMP_ULT(self, inst): 248 | left = int(self.handle(inst.left)) 249 | right = int(self.handle(inst.right)) 250 | return left < right 251 | 252 | def handle_LLIL_IF(self, expr): 253 | res = self.handle(expr.condition) 254 | if res: 255 | self.ip = expr.true 256 | else: 257 | self.ip = expr.false 258 | 259 | def handle_LLIL_LOAD(self, inst): 260 | value = self.handle(inst.src) 261 | return self.read_memory(value, inst.size) 262 | 263 | def handle_LLIL_SET_REG(self, inst): 264 | src = self.handle(inst.src) 265 | self.set_register(inst, src) 266 | return True 267 | 268 | def handle_LLIL_CONST(self, inst): 269 | return inst.constant 270 | 271 | def handle_LLIL_CONST_PTR(self, inst): 272 | return inst.constant 273 | 274 | def handle_LLIL_REG(self, inst): 275 | register_name = inst.src.name 276 | register_info = self.arch.regs[register_name] 277 | full_width_reg_info = self.arch.regs[register_info.full_width_reg] 278 | full_reg_value = self.registers[register_info.full_width_reg] 279 | 280 | mask = (1 << register_info.size * 8) - 1 281 | 282 | if inst.src == register_info.full_width_reg: 283 | return full_reg_value & mask 284 | 285 | mask = (1 << register_info.size * 8) - 1 286 | reg_bits = mask << (register_info.offset * 8) 287 | reg_value = (full_reg_value & reg_bits) >> (register_info.offset * 8) 288 | return reg_value 289 | 290 | def handle_LLIL_SUB(self, inst): 291 | return self.handle(inst.left) - self.handle(inst.right) 292 | 293 | def handle_LLIL_ADD(self, inst): 294 | return self.handle(inst.left) + self.handle(inst.right) 295 | 296 | def handle(self, inst): 297 | log_debug(f"DeGObfuscate executing: {inst.operation.name}") 298 | for field in LowLevelILInstruction.ILOperations[inst.operation]: 299 | handler = f"handle_{inst.operation.name}" 300 | has_handler = hasattr(self, handler) 301 | if has_handler is False: 302 | log_warn(f"DeGObfuscate needs to implement: {inst.operation.name}") 303 | return None 304 | else: 305 | res = getattr(self, handler)(inst) 306 | return res 307 | 308 | def execute(self): 309 | if self.ip >= len(self.instructions): 310 | return False 311 | log_debug(f"DeGObfuscate IP: {self.ip}") 312 | instr = self.instructions[self.ip] 313 | if self.highlight: 314 | self.candidate.set_auto_instr_highlight(instr.address, enums.HighlightStandardColor.GreenHighlightColor) 315 | self.ip += 1 316 | self.handle(instr) 317 | return True 318 | 319 | def run(self): 320 | while True: 321 | if not self.execute(): 322 | break 323 | return self.output 324 | 325 | def __init__(self, bv, candidate): 326 | self.bv = bv 327 | self.candidate = candidate 328 | self.arch = candidate.arch 329 | self.instructions = candidate.llil 330 | self.ip = 0 331 | self.output = "" 332 | 333 | self.flags = {} 334 | self.registers = {} 335 | for r in self.arch.regs: 336 | reg = self.arch.regs[r] 337 | if reg.full_width_reg == r: 338 | self.registers[r] = 0 339 | 340 | self.memory = bytearray('\x00', encoding='ascii')*10000000 341 | self.stack = [] 342 | 343 | # TODO: Test on non-x86/x64 344 | # https://www.reddit.com/r/golang/comments/gq4pfh/what_is_the_purpose_of_fs_and_gs_registers_in/ 345 | # rcx = [fsbase - 8].q 346 | # if (rsp u<= [rcx + 0x10].q) then 2 @ 0x6aec49 else 4 @ 0x6aebb3 347 | self.memory[92] = 0 348 | if bv.arch in [Architecture['x86'], Architecture['x86_64']]: 349 | self.registers["fsbase"] = 100 350 | self.registers["gsbase"] = 100 351 | self.registers[bv.arch.stack_pointer] = 0x10000 352 | self.write_memory(self.registers["gsbase"], 4, 0x2000) 353 | 354 | self.highlight = Settings().get_bool("degobfuscate.highlight") 355 | 356 | def get_runtime_funcs(bv): 357 | morestack_noctxt_sym = bv.get_symbols_by_name("go.runtime.morestack_noctxt") or bv.get_symbols_by_name("runtime.morestack_noctxt") or bv.get_symbols_by_name("_runtime.morestack_noctxt") or bv.get_symbols_by_name("runtime_morestack_noctxt") or bv.get_symbols_by_name("_runtime_morestack_noctxt") 358 | slicebytetostring_sym = bv.get_symbols_by_name("go.runtime.slicebytetostring") or bv.get_symbols_by_name("runtime.slicebytetostring") or bv.get_symbols_by_name("_runtime.slicebytetostring") or bv.get_symbols_by_name("runtime_slicebytetostring") or bv.get_symbols_by_name("_runtime_slicebytetostring") 359 | return (morestack_noctxt_sym, slicebytetostring_sym) 360 | 361 | def validfunc(bv, func): 362 | morestack_noctxt_sym, slicebytetostring_sym = get_runtime_funcs(bv) 363 | morestack_noctxt = bv.get_function_at(morestack_noctxt_sym[0].address) 364 | slicebytetostring = bv.get_function_at(slicebytetostring_sym[0].address) 365 | # TODO: Replace this with a much more robust heuristic for detecting obfuscated functions 366 | if not slicebytetostring in func.callees or not morestack_noctxt in func.callees: 367 | return False 368 | 369 | # Find functions which make use of an XOR primitive 370 | # Because we're using IL here we don't need to worry about xor eax, eax because that gets optimized into: 371 | # LLIL_SET_REG eax/LLIL_CONST 0 372 | def findxor(expr): 373 | if expr.operation == LowLevelILOperation.LLIL_XOR: 374 | return True 375 | for field in LowLevelILInstruction.ILOperations[expr.operation]: 376 | if field[1] == "expr": 377 | if findxor(getattr(expr, field[0])): 378 | return True 379 | return False 380 | 381 | foundxor = False 382 | for il in func.llil.instructions: 383 | if findxor(il): 384 | foundxor = True 385 | 386 | if not foundxor: 387 | log_debug(f"{func.name} is not valid due to no usage of LLIL_XOR") 388 | return foundxor 389 | 390 | def nextname(bv, newname): 391 | for x in range(1,10000): 392 | candidate = f"{newname}_{x}" 393 | if candidate in bv.symbols.keys(): 394 | continue 395 | return candidate 396 | 397 | def deobfunc(bv, func): 398 | emu = EmuMagic(bv, func) 399 | result = emu.run() 400 | if result != "": 401 | log_debug(f"DeGObfuscate result: {repr(result)}") 402 | maxlength = Settings().get_integer("degobfuscate.maxlength") 403 | shortname = function_name_regex.sub("", result)[0:maxlength] 404 | if shortname != result[0:maxlength]: 405 | for xref in bv.get_code_refs(func.start): 406 | xref.function.set_comment_at(xref.address, repr(result)[1:-1]) 407 | shortname = Settings().get_string("degobfuscate.prefix") + shortname 408 | if shortname in bv.symbols.keys() and func.start != bv.symbols[shortname].address: 409 | shortname = nextname(bv, shortname) 410 | func.name = shortname 411 | 412 | class Deob(BackgroundTaskThread): 413 | def __init__(self, bv): 414 | self.total = len(bv.functions) 415 | BackgroundTaskThread.__init__(self, f"DeGObfuscate: scanning {self.total} total functions...", True) 416 | self.bv = bv 417 | self.match = 0 418 | self.index = 0 419 | 420 | def run(self): 421 | morestack_noctxt_sym, slicebytetostring_sym = get_runtime_funcs(self.bv) 422 | if len(morestack_noctxt_sym) == 0 or len(slicebytetostring_sym) == 0: 423 | log_alert("Unable to find Go runtime slicebytetostring and/or morestack_noctxt functions. Make sure you recover symbols before running degobfuscate.") 424 | self.progress = f"DeGObfuscate failed, aborting" 425 | return 426 | 427 | for func in self.bv.functions: 428 | if self.cancelled: 429 | self.progress = f"DeGObfuscate cancelled, aborting" 430 | return 431 | 432 | self.index += 1 433 | if validfunc(self.bv, func): 434 | self.match += 1 435 | self.progress = f"DeGObfuscate analyzing ({self.index}/{self.total}) : {func.name}" 436 | try: 437 | deobfunc(self.bv, func) 438 | except Exception as e: 439 | log_warn(f"DeGObfuscate: error while emulating {func.name}: {e}") 440 | 441 | self.progress = f"DeGObfuscate emulated {self.match} functions" 442 | 443 | def deob(bv): 444 | d = Deob(bv) 445 | d.start() 446 | 447 | def deobsingle(bv, func): 448 | try: 449 | deobfunc(bv, func) 450 | except Exception as e: 451 | log_warn(f"DeGObfuscate: error while emulating {func.name}: {e}") 452 | 453 | PluginCommand.register_for_function("DeGObfuscate single function", "Tries to just deobfuscate this function as a gobfuscated string", deobsingle) 454 | PluginCommand.register("DeGObfuscate all functions", "Searches all functions for obfuscated xor strings and attempts light IL emulation to recover them.", deob) 455 | -------------------------------------------------------------------------------- /generate_plugininfo.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | This script helps in the process of creating required metadata to add a plugin to the Binary Ninja plugin repository 4 | """ 5 | import json 6 | import argparse 7 | import os 8 | import sys 9 | import io 10 | import datetime 11 | import pprint 12 | import tempfile 13 | from builtins import input 14 | import sys, tempfile, os 15 | from subprocess import call 16 | 17 | currentpluginmetadataversion = 2 18 | 19 | # def getEditorData(message): 20 | # EDITOR = os.environ.get('EDITOR','vim') 21 | 22 | # initial_message = message 23 | # edited_message = "" 24 | # with tempfile.NamedTemporaryFile(suffix=".tmp") as tf: 25 | # tf.write(initial_message.encode("utf-8")) 26 | # tf.flush() 27 | # call([EDITOR, tf.name]) 28 | 29 | # tf.seek(0) 30 | # edited_message = tf.read().decode("utf-8") 31 | # return edited_message 32 | 33 | validPluginTypes = ["core", "ui", "binaryview", "architecture", "helper"] 34 | validApis = ["python2", "python3"] 35 | validPlatforms = ["Darwin", "Windows", "Linux"] 36 | requiredLicenseKeys = ["name", "text"] 37 | 38 | def validateList(data, name, validList): 39 | if name not in data: 40 | print("Warning: '{}' field doesn't exist".format(name)) 41 | return False 42 | elif not isinstance(data[name], list): 43 | print("Error: '{}' field isn't a list".format(name)) 44 | return False 45 | 46 | success = True 47 | for item in data[name]: 48 | if item not in validList: 49 | print("Error: plugin {}: {} not one of {}".format(name, item, validList)) 50 | success = False 51 | return success 52 | 53 | def validateString(data, name): 54 | if name not in data: 55 | print("Error: '{}' field doesn't exist".format(name)) 56 | return False 57 | elif type(data[name]).__name__ not in ("unicode", "str"): # a python 2/3 compliant check for string type 58 | print("Error: '{}' field is {} not a string".format(name, type(data[name]))) 59 | return False 60 | return True 61 | 62 | def validateInteger(data, name): 63 | if name not in data: 64 | print("Error: '{}' field doesn't exist.".format(name)) 65 | return False 66 | elif not isinstance(data[name], int): 67 | print("Error: '{}' is {} not an integer value".format(name, type(data[name]))) 68 | return False 69 | return True 70 | 71 | def validateStringMap(data, name, validKeys, requiredKeys=None): 72 | if name not in data: 73 | print("Error: '{}' field doesn't exist.".format(name)) 74 | return False 75 | elif not isinstance(data[name], dict): 76 | print("Error: '{}' is {} not a dict type".format(name, type(data[name]))) 77 | return False 78 | 79 | success = True 80 | if requiredKeys is not None: 81 | for key in requiredKeys: 82 | if key not in data[name]: 83 | print("Error: required subkey '{}' not in {}".format(key, name)) 84 | success = False 85 | 86 | for key in data[name].keys(): 87 | if key not in validKeys: 88 | print("Error: key '{}' not is not in the set of valid keys {}".format(key, validKeys)) 89 | success = False 90 | 91 | return success 92 | 93 | def validateRequiredFields(data): 94 | success = validateInteger(data, "pluginmetadataversion") 95 | if success: 96 | if data["pluginmetadataversion"] != currentpluginmetadataversion: 97 | print("Error: 'pluginmetadataversion' is not the correct version") 98 | success = False 99 | else: 100 | print("Current version is {}".format(currentpluginmetadataversion)) 101 | 102 | success &= validateString(data, "name") 103 | success &= validateList(data, "type", validPluginTypes) 104 | success &= validateList(data, "api", validApis) 105 | success &= validateString(data, "description") 106 | success &= validateString(data, "longdescription") 107 | success &= validateStringMap(data, "license", requiredLicenseKeys, requiredLicenseKeys) 108 | validPlatformList = validateList(data, "platforms", validPlatforms) 109 | success &= validPlatformList 110 | success &= validateStringMap(data, "installinstructions", validPlatforms, list(data["platforms"]) if validPlatformList else None) 111 | success &= validateString(data, "version") 112 | success &= validateString(data, "author") 113 | success &= validateInteger(data, "minimumbinaryninjaversion") 114 | return success 115 | 116 | def getCombinationSelection(validList, prompt, maxItems=None): 117 | if maxItems == None: 118 | maxItems = len(validList) 119 | 120 | prompt2 = "Enter comma separated list of items> " 121 | if maxItems == 1: 122 | prompt2 = "> " 123 | while True: 124 | print(prompt) 125 | for i, item in enumerate(validList): 126 | print("\t{:>3}: {}".format(i, item)) 127 | items = filter(None, input(prompt2).split(",")) 128 | result = [] 129 | success = True 130 | for item in items: 131 | try: 132 | value = int(item.strip()) 133 | except ValueError: 134 | print("Couldn't convert {} to integer".format(item)) 135 | success = False 136 | break 137 | if value < 0 or value >= len(validList): 138 | print("{} is not a valid selection".format(value)) 139 | success = False 140 | break 141 | else: 142 | result.append(validList[value]) 143 | if success: 144 | return result 145 | 146 | licenseTypes = { 147 | "MIT" : """Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.""", 148 | "2-Clause BSD" : """Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.""", 149 | "Apache-2.0" : """Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at\n\n\thttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.""", 150 | "LGPL-2.0" : """This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA""", 151 | "LGPL-2.1" : """This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA""", 152 | "LGPL-3.0" : """This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA""", 153 | "GPL-2.0" : """This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License along with this program; if not, see .""", 154 | "GPL-3.0" : """This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License along with this program. If not, see .""" 155 | } 156 | 157 | def generatepluginmetadata(): 158 | data = {} 159 | data["pluginmetadataversion"] = 2 160 | data["name"] = input("Enter plugin name: ") 161 | data["author"] = input("Enter your name or the name you want this plugin listed under: ") 162 | data["type"] = getCombinationSelection(validPluginTypes, "Which types of plugin is this? ") 163 | data["api"] = getCombinationSelection(validApis, "Which api's are supported? ") 164 | data["description"] = input("Enter a short description of this plugin (50 characters max): ") 165 | data["longdescription"] = input("Enter a full description of this plugin (Markdown formatted): ") 166 | data["license"] = {} 167 | 168 | licenseTypeNames = ["Other"] 169 | licenseTypeNames.extend(licenseTypes.keys()) 170 | data["license"]["name"] = getCombinationSelection(licenseTypeNames, "Enter the license type of this plugin:", 1)[0] 171 | if data["license"]["name"] == "Other": 172 | data["license"]["name"] = input("Enter License Type: ") 173 | data["license"]["text"] = input("Enter License Text: ") 174 | else: 175 | data["license"]["text"] = licenseTypes[data["license"]["name"]] 176 | 177 | year = datetime.datetime.now().year 178 | holder = data["author"] 179 | 180 | answer = input("Is this the correct copyrigtht information?\n\tCopyright {year} {holder}\n[Y/n]: ".format(year=year, holder=holder)) 181 | if answer not in ("Y", "y", ""): 182 | year = input("Enter copyright year: ") 183 | holder = input("Enter copyright holder: ") 184 | 185 | data["license"]["text"] = "Copyright {year} {holder}\n\n".format(year=year, holder=holder) + data["license"]["text"] 186 | data["platforms"] = getCombinationSelection(validPlatforms, "Which platforms are supported? ") 187 | 188 | data["installinstructions"] = {} 189 | for platform in data["platforms"]: 190 | print("Enter Markdown formatted installation directions for the following platform: ") 191 | data["installinstructions"][platform] = input("{}: ".format(platform)) 192 | data["version"] = input("Enter the version string for this plugin. ") 193 | data["minimumbinaryninjaversion"] = int(input("Enter the minimum build number that you've successfully tested this plugin with: ")) 194 | return data 195 | 196 | 197 | readmeTemplate = u"""# {name} (v{version}) 198 | Author: **{author}** 199 | 200 | _{description}_ 201 | 202 | ## Description: 203 | 204 | {longdescription} 205 | {install} 206 | 207 | ## Minimum Version 208 | 209 | This plugin requires the following minimum version of Binary Ninja: 210 | 211 | * {minimum} 212 | 213 | {dependencies} 214 | ## License 215 | 216 | This plugin is released under a {license} license. 217 | ## Metadata Version 218 | 219 | {metadataVersion} 220 | """ 221 | 222 | def generateReadme(plugin): 223 | install = None 224 | if "installinstructions" in plugin: 225 | install = "\n\n## Installation Instructions" 226 | for platform in plugin["installinstructions"]: 227 | install += "\n\n### {}\n\n{}".format(platform, plugin["installinstructions"][platform]) 228 | 229 | if "dependencies" in plugin: 230 | dependencies = u"\n\n## Required Dependencies\n\nThe following dependencies are required for this plugin:\n\n" 231 | for dependency in plugin["dependencies"]: 232 | dependencylist = u", ".join(plugin["dependencies"][dependency]) 233 | dependencies += u" * {dependency} - {dependencylist}\n".format(dependency = dependency, dependencylist = dependencylist) 234 | dependencies += "\n" 235 | else: 236 | dependencies = "" 237 | 238 | return readmeTemplate.format(name=plugin["name"], version=plugin["version"], 239 | author=plugin["author"], description=plugin["description"], 240 | longdescription=plugin["longdescription"], install=install, 241 | minimum=plugin["minimumbinaryninjaversion"], dependencies=dependencies, 242 | license=plugin["license"]["name"], metadataVersion=plugin["pluginmetadataversion"]) 243 | 244 | 245 | def main(): 246 | parser = argparse.ArgumentParser(description="Generate README.md (and optional LICENSE) from plugin.json metadata") 247 | parser.add_argument("-a", "--all", help="Generate all supporting information needed (plugin.json, README.md, LICENSE)", action="store_true") 248 | parser.add_argument("-p", "--plugin", help="Interactively generate plugin.json file", action="store_true") 249 | parser.add_argument("-r", "--readme", help="Automatically generate README.md", action="store_true") 250 | parser.add_argument("-l", "--license", help="Automatically generate LICENSE file", action="store_true") 251 | parser.add_argument("-f", "--force", help="Force overwrite of existing files", action="store_true") 252 | parser.add_argument("-v", "--validate", help="Validate existing plugin.json only", metavar="JSON") 253 | args = parser.parse_args() 254 | 255 | 256 | # Just validate an existing plugin.json 257 | if args.validate is not None: 258 | if validateRequiredFields(json.load(io.open(args.validate, "r", encoding="utf8"))): 259 | print("Successfully validated json file") 260 | else: 261 | print("Error: json validation failed") 262 | return 263 | 264 | pluginjson = "plugin.json" 265 | 266 | # Enable all the options if --all is selected 267 | if args.all: 268 | args.plugin = True 269 | args.readme = True 270 | args.license = True 271 | 272 | if args.plugin: 273 | plugin = generatepluginmetadata() 274 | else: 275 | try: 276 | plugin = json.load(io.open(pluginjson, "r", encoding="utf8")) 277 | except json.JSONDecodeError: 278 | print("File {} doesn't contain valid json".format(pluginjson)) 279 | return 280 | except Exception: 281 | print("File {} doesn't exist".format(pluginjson)) 282 | return 283 | 284 | print("-----------------------------------------------------------------") 285 | if validateRequiredFields(plugin): 286 | print("Successfully validated json file") 287 | else: 288 | print("Error: json validation failed") 289 | return 290 | 291 | if "python2" in plugin["api"] and "python3" not in plugin["api"]: 292 | print("Warning: This python plugin doesn't support python3, python2 support will soon be deprecated.") 293 | print(" Please consider upgrading you plugin to support python3") 294 | 295 | if args.plugin: 296 | skip = False 297 | print("-----------------------------------------------------------------") 298 | if os.path.isfile(pluginjson) and not args.force and args.plugin: 299 | print("{} already exists.".format(pluginjson)) 300 | response = input("Overwrite it? (N,y) ") 301 | if response != "y": 302 | print("Not overwriting plugin.json") 303 | skip = True 304 | if not skip: 305 | print("Creating plugin.json.") 306 | with io.open(pluginjson, "w", encoding="utf8") as pluginfile: 307 | pluginfile.write(json.dumps(plugin, indent=" ")) 308 | 309 | if args.readme: 310 | print("-----------------------------------------------------------------") 311 | readme = os.path.join(os.path.dirname(pluginjson), "README.md") 312 | skip = False 313 | if os.path.isfile(readme) and not args.force: 314 | print("{} already exists.".format(readme)) 315 | response = input("Overwrite it? (N,y) ") 316 | if response != "y": 317 | print("Not overwriting README.md") 318 | skip = True 319 | if not skip: 320 | print("Creating README.md") 321 | with io.open(readme, "w", encoding="utf8") as readmeFile: 322 | readmeFile.write(generateReadme(plugin)) 323 | 324 | if args.license: 325 | print("-----------------------------------------------------------------") 326 | licenseFile = os.path.join(os.path.dirname(pluginjson), "LICENSE") 327 | skip = False 328 | if os.path.isfile(licenseFile) and not args.force: 329 | print("{} already exists.".format(licenseFile)) 330 | response = input("Overwrite it? (N,y) ") 331 | if response != "y": 332 | print("Not overwriting LICENSE") 333 | skip = True 334 | if not skip: 335 | print("Creating LICENSE") 336 | with io.open(licenseFile, "w", encoding="utf8") as lic: 337 | lic.write(plugin["license"]["text"]) 338 | 339 | 340 | if __name__ == "__main__": 341 | main() 342 | -------------------------------------------------------------------------------- /img/DeGObfuscate.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kryptoslogic/binja_degobfuscate/e61b884ba60981458ae076e890c3915876e94d94/img/DeGObfuscate.gif -------------------------------------------------------------------------------- /plugin.json: -------------------------------------------------------------------------------- 1 | {"pluginmetadataversion": 2, "name": "DeGObfuscate", "author": "Jamie Hankins", "type": ["helper"], "api": ["python3"], "description": "De-obfuscates strings inside of obfuscated Go binaries", "longdescription": "This plugin implements a simple LLIL emulator to statically de-obfuscate simple string obfuscation such as the obfuscations done by [gobfuscate](https://github.com/unixpickle/gobfuscate).\n\nTo activate it, use either the `Tools` menu or the command palette. It offers two modes, the first will attempt to analyze the current function while the other will attempt to find all functions that are merely obfuscated strings and rename them. If the function name cannot be cleanly replaced, a comment will be added at all call locations with the detailed deobfuscated string in addition to the truncated rename.\n\n![](https://github.com/jamie-34254/binja_degobfuscate/blob/master/img/DeGObfuscate.gif?raw=true)", "license": {"name": "MIT", "text": "Copyright 2020 Kryptos Logic\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE."}, "platforms": ["Darwin", "Windows", "Linux"], "installinstructions": {"Darwin": "no special instructions, package manager is recommended", "Windows": "no special instructions, package manager is recommended", "Linux": "no special instructions, package manager is recommended"}, "version": "1.0.2", "minimumbinaryninjaversion": 1528} 2 | --------------------------------------------------------------------------------