def __init__(self, context: GameContext, frame: Rect, width: int) -> None: super().__init__(context, frame) self.width = width self.ceiling = Solid( context, Rect.make(0, -frame.size.height / 2 + width / 2, frame.size.width, width)) self.wallLeft = Solid( context, Rect.make(-frame.size.width / 2 + width / 2, 0, width, frame.size.height - width * 2)) self.wallRight = Solid( context, Rect.make(frame.size.width / 2 - width / 2, 0, width, frame.size.height - width * 2)) self.floor = Solid( context, Rect.make(0, frame.size.height / 2 - width / 2, frame.size.width, width)) self.ceiling.renderObject = RenderObject.render_object_from_color( context.renderer, Color(0, 0, 0, 0xFF)) self.wallLeft.renderObject = RenderObject.render_object_from_color( context.renderer, Color(0, 0, 0, 0xFF)) self.wallRight.renderObject = RenderObject.render_object_from_color( context.renderer, Color(0, 0, 0, 0xFF)) self.floor.renderObject = RenderObject.render_object_from_color( context.renderer, Color(0, 0, 0, 0xFF)) self.add_child(self.ceiling) self.add_child(self.wallLeft) self.add_child(self.wallRight) self.add_child(self.floor)
def deobfuscation(self): """ Deobfuscation of the push_reg function """ print Color.step("Emulating each call to {}".format(self.pattern.name)) # for each call to the function for match_func in self.pattern.matches.matches: for args in match_func.args: push_arg1 = int(args["push1"][0].info.arg1, 16) push_arg2 = int(args["push2"][0].info.arg1, 16) push_addr2 = args["push2"][0].info.address func_end = match_func.match["last_inst"][0].info.address ret_addr = args["call"][0].info.address + len( args["call"][0].info.opcode) + 1 # init registers and call the targeted function self.sb.call_callback(match_func.func_addr, push_arg1, push_arg2, cb=self.end, ret_addr=ret_addr, bp=func_end) # save the deobfuscated instruction if self.tmp: # calculate call address addr = (self.tmp - push_addr2) & 0xFFFFFFFF match_func.deobf_inst.append({ "args": args, "inst": "JMP {}".format(addr) }) self.tmp = 0
def patch(self, start, end, str_inst): mn = self.sb.machine.mn loc_db = LocationDB() opcode = mn.asm(mn.fromstring(str_inst, loc_db, 32))[0] if len(opcode) <= (end - start): self.pe.virt.set(start, opcode) else: print Color.error("Can't patch not enough space")
def __init__(self, points=None, bgColor=Color("bg", ("blue", 0.45)), textColor=Color("bg", ("white", 0.95))): if not points: points = [] self.points = [] for point in points: self.points.append((point, False)) self.bgColor = bgColor self.textColor = textColor self.menu = False self.menuInstance = None
def get_rgb(self, index): page = self._get_page(index) content = page.find('div', class_='colormap-col colormap_detailinfo span6') rgb = content.find_all('p')[0].text[14:-9].strip().split(',') rgb = [int(col) for col in rgb] return Color(*rgb, index)
def get_xrefs(self): """Try to get the xrefs of the matched function""" # generate our pattern for xrefs xrefs_pattern = XREFS_PATTERN.replace("FILL_ADDR", str(hex(self.func_addr))) #print Color.step("Searching for the XREFS to the function 0x{:X}".format(self.func_addr)) # match the pattern call_matches = pygrap.match_graph(xrefs_pattern, self.test_graph) # creation of the list of xrefs if len(call_matches) == 0: print Color.error("No XREFS to the function 0x{:X} was found".format(self.func_addr)) else: for match in call_matches["xrefs"]: self.xrefs.append(int(match["call"][0].info.address))
def patch(self): patch = Patch(self.sb) print Color.step("Patching each call to {} (can take a while)".format( self.pattern.name)) for match_func in self.pattern.matches.matches: for elem in match_func.deobf_inst: args = elem["args"] inst = elem["inst"] start = args["push"][0].info.address end = args["call"][0].info.address + len( args["call"][0].info.opcode) + 1 # patch the range with NOPs patch.nop_range(start, end) # write the deobfuscated instruction patch.patch(start, end, inst)
def get_func_ep_grap(self): """Try to get the entrypoint of the matched function""" first_inst = self.match["first_inst"][0] first_addr = first_inst.info.address # Find the beginning of the function: # It is a node with at least 2 fathers which address a fulfills: address - 0x7 <= a <= address address_cond = "address >= " + str(hex(int(first_addr - 0x7))) + " and address <= " + str(hex(int(first_addr))) ep_pattern = EP_PATTERN.replace("FILL_ADDR_COND", address_cond) #print Color.step("Searching for the function entrypoint near 0x{:X}".format(first_addr)) # search for the EP ep_matches = pygrap.match_graph(ep_pattern, self.test_graph) if len(ep_matches) != 1 or len(ep_matches["ep_func"]) != 1: print Color.error("Entrypoint not found or the function was not call for the address 0x{:X}".format(first_addr)) else: self.func_addr = int(ep_matches["ep_func"][0]["ep"][0].info.address)
def main(): """Main""" # Init options = usage() emu = Emu(options) # Deobfuscation emu.deobf_push_reg() emu.deobf_detour_call() emu.deobf_detour_jmp() # Generation of IDA script if options.ida: ida = Ida(emu) ida.dump(options.input + "_ida.py") # Create the deobfuscated version clean = options.input + ".clean" print Color.step("Patched nymaim available: {}".format(clean)) open(clean, 'wb').write(str(emu.sb.pe))
def deobfuscation(self): """ Deobfuscation of the push_reg function """ print Color.step("Emulating each call to {}".format(self.pattern.name)) # for each call to the function for match_func in self.pattern.matches.matches: for args in match_func.args: push_arg = int(args["push"][0].info.arg1, 16) # init registers and call the targeted function self.init() self.sb.call_callback(match_func.func_addr, push_arg, cb=self.end) # save the deobfuscated instruction if self.tmp_str: match_func.deobf_inst.append({ "args": args, "inst": self.tmp_str }) self.tmp_str = ""
def __init__(self, cfg, test_graph): """Initialization Arguments: - cfg(Dict): Config for a given pattern - test_graph(pygrap.graph_t): Grap representation of the binary """ self.cfg = cfg self.test_graph = test_graph self.matches = [] # search for patterns matches = pygrap.match_graph(self.cfg["func_pattern"], self.test_graph).items()[0][1] print Color.info("The graph {name} was found {size} time(s)".format(name=self.cfg["name"], size=len(matches))) # process matches for match in matches: try: self.matches.append(Match(match, self.test_graph, self.cfg)) except: continue
def loadColorsFromFile(self, path): """load color definitions from file""" config = ConfigObj(path) if 'colors' in config: colors = config['colors'] colorObjects = {} for key in colors.keys(): content = colors[key] if len(content ) == 2: # hex color/color name and alpha as float 0-1 colorString = content[0] alpha = float(content[1]) # create a new modRana color instance newColor = Color(key, colorStringAlphaTupple=(colorString, alpha)) colorObjects[key] = newColor return colorObjects else: return {}
def getCustomIcon(self, parameterList, w, h): """ there are six positional parameters: fill color,fill opacity, outline color, outline opacity, outline width (default 8) and corner radius (default 22) to use default value, just don't fill in the positional parameter ( len(parameter) == 0 ) USAGE: corner radius: default=22, 0 does right angle corners EXAMPLE: generic:green;1.0;blue;0.5;10;15 """ # check if the list has proper length if len(parameterList) != 6: return None semicolonSepList = parameterList # process the positional parameters if len(semicolonSepList[0]): fillColorString = semicolonSepList[0] else: fillColorString = None if len(semicolonSepList[1]): fillAlpha = float(semicolonSepList[1]) else: fillAlpha = 1.0 if len(semicolonSepList[2]): outlineColorString = semicolonSepList[2] else: outlineColorString = None if len(semicolonSepList[3]): outlineAlpha = float(semicolonSepList[3]) else: outlineAlpha = 1.0 if len(semicolonSepList[4]): outlineWidth = int(semicolonSepList[4]) else: outlineWidth = 4 if len(semicolonSepList[5]): cornerRadius = int(semicolonSepList[5]) else: cornerRadius = 22 # parse the colors (if defined) if fillColorString: fillColor = Color("fill", (fillColorString, fillAlpha)) fillColorRGBATuple = fillColor.getCairoColor() else: fillColorRGBATuple = self.buttonFillColor if outlineColorString: outlineColor = Color("outline", (outlineColorString, outlineAlpha)) outlineColorRGBATuple = outlineColor.getCairoColor() else: outlineColorRGBATuple = self.buttonOutlineColor # apply the alpha values try: (r, g, b, a) = fillColorRGBATuple fillColorRGBATuple = (r, g, b, fillAlpha) except Exception: import sys e = sys.exc_info()[1] print("** wrong fill color code or name: %s" % fillColorString) print("** exception: %s" % e) fillColorRGBATuple = self.buttonFillColor try: (r, g, b, a) = outlineColorRGBATuple outlineColorRGBATuple = (r, g, b, outlineAlpha) except Exception: import sys e = sys.exc_info()[1] print("** wrong outline color code or name: %s" % fillColorString) print("** exception: %s" % e) outlineColorRGBATuple = self.buttonOutlineColor # create the icon icon = self.roundedRectangle(w, h, fillColorRGBATuple, outlineColorRGBATuple, outlineWidth, cornerRadius) return icon
def getCustomIcon(self, parameterList, w, h): """ there are six positional parameters: fill color,fill opacity, outline color, outline opacity, outline width (default 8) and corner radius (default 22) to use default value, just don't fill in the positional parameter ( len(parameter) == 0 ) USAGE: corner radius: default=22, 0 does right angle corners EXAMPLE: generic:green;1.0;blue;0.5;10;15 """ # check if the list has proper length if len(parameterList) != 6: return None semicolonSepList = parameterList # process the positional parameters if len(semicolonSepList[0]): fillColorString = semicolonSepList[0] else: fillColorString = None if len(semicolonSepList[1]): fillAlpha = float(semicolonSepList[1]) else: fillAlpha = 1.0 if len(semicolonSepList[2]): outlineColorString = semicolonSepList[2] else: outlineColorString = None if len(semicolonSepList[3]): outlineAlpha = float(semicolonSepList[3]) else: outlineAlpha = 1.0 if len(semicolonSepList[4]): outlineWidth = int(semicolonSepList[4]) else: outlineWidth = 4 if len(semicolonSepList[5]): cornerRadius = int(semicolonSepList[5]) else: cornerRadius = 22 # parse the colors (if defined) if fillColorString: fillColor = Color("fill", (fillColorString, fillAlpha)) fillColorRGBATuple = fillColor.getCairoColor() else: fillColorRGBATuple = self.buttonFillColor if outlineColorString: outlineColor = Color("outline", (outlineColorString, outlineAlpha)) outlineColorRGBATuple = outlineColor.getCairoColor() else: outlineColorRGBATuple = self.buttonOutlineColor # apply the alpha values try: (r, g, b, a) = fillColorRGBATuple fillColorRGBATuple = (r, g, b, fillAlpha) except Exception: self.log.exception("** wrong fill color code or name: %s", fillColorString) fillColorRGBATuple = self.buttonFillColor try: (r, g, b, a) = outlineColorRGBATuple outlineColorRGBATuple = (r, g, b, outlineAlpha) except Exception: self.log.exception("** wrong outline color code or name: %s", fillColorString) outlineColorRGBATuple = self.buttonOutlineColor # create the icon icon = self.roundedRectangle(w, h, fillColorRGBATuple, outlineColorRGBATuple, outlineWidth, cornerRadius) return icon
if __name__ == "__main__": colors = None scrap = Scraper() if not os.path.exists("./data.json"): scrap.run_multi() colors = scrap.colors frozen = jsonpickle.encode(colors) with open('data.json', 'w') as text_file: print(frozen, file=text_file) else: with open('data.json', 'r') as text_file: colors = jsonpickle.decode(text_file.read()) while(True): choose = int(input("\n\n[1] Szukaj farby\n[2] Zakoncz dzialania\n>> ")) if choose == 1: rgb = input("Podaj rgb po spacji: ") rgb = [int(col) for col in rgb.split(' ')] point = Color(*rgb, 0) closest_colors = sorted(colors, key=lambda color: cie94(point.cie, color.cie)) closest_color = closest_colors[0:5] print(*closest_color, sep="\n") elif choose == 2: exit(0) else: print("Musisz wybrac 1 lub 2\n")
def _search(self): """Searching for the pattern in the binary""" print Color.step("Searching for the pattern {}".format(self.name)) self.matches = Matches(self.cfg, self.test_graph)
def __init__(self) -> None: if sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) < 0: raise RuntimeError("SDL could not initialize! SDL Error: " + str(sdl2.SDL_GetError())) if not sdl2.SDL_SetHint(sdl2.SDL_HINT_RENDER_SCALE_QUALITY, b"1"): print("Warning: Linear texture filtering not enabled.") img_flags = sdl2.sdlimage.IMG_INIT_PNG if not (sdl2.sdlimage.IMG_Init(img_flags) & img_flags): raise RuntimeError( "SDL_image could not initialize! SDL_image Error: " + str(sdl2.sdlimage.IMG_GetError())) if sdl2.sdlttf.TTF_Init() == -1: raise RuntimeError( "SDL_ttf could not initialize! SDL_ttf Error: " + str(sdl2.sdlttf.TTF_GetError())) settings = GameSettings('Test game', 800, 600) window = sdl2.SDL_CreateWindow(bytes(settings.name, 'utf-8'), sdl2.SDL_WINDOWPOS_UNDEFINED, sdl2.SDL_WINDOWPOS_UNDEFINED, settings.windowWidth, settings.windowHeight, sdl2.SDL_WINDOW_SHOWN) if not window: raise RuntimeError("Window could not be created. SDL Error: " + str(sdl2.SDL_GetError())) self.context = GameContext( sdl2.SDL_CreateRenderer( window, -1, sdl2.SDL_RENDERER_ACCELERATED | sdl2.SDL_RENDERER_PRESENTVSYNC), settings) sdl2.SDL_SetRenderDrawColor(self.context.renderer, 0xff, 0xff, 0xff, 0xff) self.world = World( self.context, Rect.make(0, 0, self.context.settings.windowWidth / 2, self.context.settings.windowHeight / 2)) self.ui = GameObject( self.context, Rect(Vector2D(), self.world.camera.originalSize.copy())) player = Player(self.context, Rect.make(0, 20, 10, 20)) player.idleAnimation = Animation.animation_with_single_render_object( RenderObject.render_object_from_file(self.context.renderer, b"img/idle.png")) player.moveAnimation = Animation.animation_with_speed_and_texture_path( 80, self.context.renderer, b"img/move.png", 40, 80, 6) player.jumpAnimation = Animation.animation_with_single_render_object( RenderObject.render_object_from_file(self.context.renderer, b"img/jump.png")) player.crouchAnimation = Animation.animation_with_single_render_object( RenderObject.render_object_from_file(self.context.renderer, b"img/crouch.png")) player.crouchMoveAnimation = Animation.animation_with_single_render_object( RenderObject.render_object_from_file(self.context.renderer, b"img/crouch.png")) player.speed = 1.3 player.jumpSpeed = 2.5 player.physics.gravityForce = 0.1 player.add_child(self.world.camera) self.world.add_child( Frame( self.context, Rect.make(0, 0, self.world.frame.size.width, self.world.frame.size.height), 10)) count = 200 power_count = 100 x = int(self.world.frame.size.width / 10 - 2) y = int(self.world.frame.size.height / 10 - 2) for pair in random.sample(set(pair_range(x, y)), count): random_x = pair[0] random_y = pair[1] rect = Rect.make( (self.world.frame.size.width / 2) - 15 - random_x * 10, (self.world.frame.size.height / 2) - 15 - random_y * 10, 10, 10) if power_count: game_object = Consumable(self.context, rect) game_object.renderObject = RenderObject.render_object_from_color( self.context.renderer, Color(0, 0xff, 0, 0x80)) power_count -= 1 else: game_object = Solid(self.context, rect) game_object.renderObject = RenderObject.render_object_from_file( self.context.renderer, b"img/brick.png") self.world.add_child(game_object) self.world.add_child(player) self.ui = GameObject(self.context, Rect(Vector2D(), self.world.camera.originalSize)) death_text = Text(self.context, Rect.make(0, 0, 100, 10)) death_text.set_text(b"You died! Game Over!") death_text.set_font(b"fonts/Scratch_.ttf", 28) death_text.set_color(sdl2.SDL_Color(0xff, 0, 0)) death_text.visible = False self.ui.add_child(death_text) player.deathText = death_text win_text = Text(self.context, Rect.make(0, 0, 100, 10)) win_text.set_text(b"Congratulations! You won!") win_text.set_font(b"fonts/Scratch_.ttf", 28) win_text.set_color(sdl2.SDL_Color(0, 0xff, 0)) win_text.visible = False self.ui.add_child(win_text) player.winText = win_text health_bar_holder = GameObject( self.context, Rect.make(-self.world.camera.originalSize.width / 2 + 16, -self.world.camera.originalSize.height / 2 + 2.5, 30, 3)) health_bar_holder.renderObject = RenderObject.render_object_from_color( self.context.renderer, Color.black()) self.ui.add_child(health_bar_holder) power_bar_holder = GameObject( self.context, Rect.make(self.world.camera.originalSize.width / 2 - 16, -self.world.camera.originalSize.height / 2 + 2.5, 30, 3)) power_bar_holder.renderObject = RenderObject.render_object_from_color( self.context.renderer, Color.black()) self.ui.add_child(power_bar_holder) health_bar = Bar(self.context, Rect.make(0, 0, 29, 2)) health_bar.renderObject = RenderObject.render_object_from_color( self.context.renderer, Color.red()) health_bar_holder.add_child(health_bar) player.healthBar = health_bar power_bar = Bar(self.context, Rect.make(0, 0, 29, 2)) power_bar.renderObject = RenderObject.render_object_from_color( self.context.renderer, Color.green()) power_bar.set_value(0) power_bar_holder.add_child(power_bar) player.powerBar = power_bar
def dump(self, path): """ Dump the script into a file""" with open(path, 'w') as f: f.writelines(self.script) print Color.step("Creation of an IDA script to rename function: {}".format(path))