def test_keep_tags(): """Test keep_tags keyword arg.""" assert_both = partial(assert_both_values, kind='Color color') instance = Color('{red}Test{/red}', keep_tags=True) assert_both(instance, '{red}Test{/red}', '{red}Test{/red}') assert_both(instance.upper(), '{RED}TEST{/RED}', '{RED}TEST{/RED}') assert len(instance) == 15 instance = Color('{red}\033[41mTest\033[49m{/red}', keep_tags=True) assert_both(instance, '{red}Test{/red}', '{red}\033[41mTest\033[49m{/red}') assert_both(instance.upper(), '{RED}TEST{/RED}', '{RED}\033[41mTEST\033[49m{/RED}') assert len(instance) == 15
def _process_mtd(self, mtd): if DEBUG: from colorclass.color import Color print('\n', '+' * 100) print('Starting to decode ...') print(Color.green(mtd)) # 如果存在数组 array_data_content = [] arr_res = self.arr_data_ptn.search(mtd.get_body()) if arr_res: array_data_content = re.split(r'\n\s', arr_res.group()) lines = re.split(r'\n\s*', mtd.get_body()) old_body = lines.copy() # 存放原始方法体 new_body = [] # 存放解密后的方法体 snippet = [] # 存放smali代码,用于模拟执行 args = {} # 存放方法参数,用于smaliemu执行 index = -1 # 用于计数 for line in lines: snippet.append(line) new_body.append(line) # 解密结果,直接放后面即可 index += 1 if 'invoke-' not in line and 'iget-' not in line: continue from smafile import SmaliLine # 函数有两种类型: # 1. 字符串内置类型 - smaliemu能直接执行 # 2. 其他类型 - 需要发射调用 if DEBUG: print('LINE:', Color.red(line)) if 'Ljava/lang/String;->' in line: if '<init>' not in line: continue if DEBUG: print(Color('{autoyellow}process new string...{/yellow} ')) # 如果是字符串函数,参数为[B/[C/[I,则考虑 rtn_name, rnames = SmaliLine.parse_string(line) if not rnames: continue # 直接执行emu解密 try: ll = args[rnames[1]] # print(ll) except KeyError: continue if not isinstance(ll, list): continue no_str = False for i in ll: if i < 0: no_str = True break if no_str: continue result = ''.join(chr(x) for x in ll) if DEBUG: print(result) # 更新寄存器 args[rtn_name] = result # 更新代码 new_line = 'const-string {}, "{}"'.format(rtn_name, result) new_body = new_body[:-1] new_body.append(new_line) self.make_changes = True mtd.set_modified(True) continue elif 'invoke-static' in line: # 获取函数相关信息 cname, mname, ptypes, rtype, rnames = SmaliLine.parse_invoke_static( line) if cname in ['Ljava/lang/reflect/Method;']: print(cname, 'will skip') continue # 返回值不能其他引用类型 if rtype[0] == 'L' and rtype != 'Ljava/lang/String;': continue if rtype in ['V', 'Z']: continue flagx = False for i in [ 'Landroid/content/Context;', 'Landroid/app/Activity;' ]: if i in ptypes: flagx = True break if flagx: continue elif 'iget-object' in line: # iget-object v3, p0, Lcom/fmsd/a/d;->q:Ljava/lang/String; # 这种情况,需要直接通过反射获取 # clz_name, field_name, rname = cname, fname, rtype, rname = SmaliLine.parse_iget_object(line) if rtype != 'Ljava/lang/String;': continue self.json_list = {'type': 'field', 'data': []} json_item = {'className': cname, 'fieldName': [fname]} # print(json_item) self.json_list['data'].append(json_item) result = self.get_field_value() if not result: continue value = result[fname] args[rname] = value continue else: continue # print('>', cname) # print('>', mname) # print('>', ptypes) # print('>', rnames) # print(">", 'return Type:', rtype) # 参数名(寄存器的名),类名,方法名,proto(简称) # register_name, class_name, mtd_name, ptypescc # ('v1, v2, v3', 'Lcom/game/pay/sdk/y', 'a', 'ISB') # 解密参数的寄存器名 # 初始化所有寄存器 del snippet[-1] snippet.extend(array_data_content) try: args.update(self.pre_process(snippet)) except TIMEOUT_EXCEPTION: pass try: # for lx in snippet: # print(lx) self.emu.call(snippet, args=args, cv=True, thrown=False) registers = self.emu.vm.variables # registers = self.get_vm_variables(snippet, args, rnames) # print('smali执行后,寄存器内容', registers) # args = registers if registers else args if registers: for k, v in registers.items(): if v is None: continue args[k] = v registers = args except TIMEOUT_EXCEPTION: snippet.clear() continue # print('更新寄存器内容', args) # if not registers: # registers = args obj_flag = False if len(ptypes) == 1 and ptypes[0][0] == 'L' and ptypes != [ 'Ljava/lang/String;' ]: # 单独处理参数为对象的情况 obj_flag = True # 已经执行过的代码,不再执行 snippet.clear() if not registers and not obj_flag: continue # print('----->>>>>>>>>>') # 从寄存器中获取对应的参数 # 参数获取 "arguments": ["I:198", "I:115", "I:26"]} arguments = [] # args = {} # the parameter of smali method if not obj_flag: ridx = -1 for item in ptypes: ridx += 1 rname = rnames[ridx] if rname not in registers: break value = registers[rnames[ridx]] argument = self.convert_args(item, value) if argument is None: break arguments.append(argument) else: arguments.append('Object:' + self.smali2java(ptypes[0])) # print('参数类型', ptypes) # print('参数值', arguments) if len(arguments) != len(ptypes): continue json_item = self.get_json_item(cname, mname, arguments) # print('生成json item') # {id}_{rtn_name} 让这个唯一化,便于替换 old_content = '# %s' % json_item['id'] # 如果 move_result_obj 操作存在的话,解密后一起替换 find = self.move_result_obj_ptn.search(lines[index + 1]) # 必须要找到返回值操作,用于更新寄存器 if not find: # print('找不到返回寄存器') continue rtn_name = find.groups()[0] # 为了避免 '# abc_v10' 替换成 '# abc_v1' old_content = old_content + '_' + rtn_name + 'X' self.append_json_item(json_item, mtd, old_content, rtn_name) # print(json_item) result = self.get_result(rtype) # print("解密结果", result) self.json_list.clear() if result: new_body = new_body[:-1] else: continue if not args: args = {} if rtype == 'Ljava/lang/String;': result = list(result.values())[0][0] # 更新寄存器 args[rtn_name] = result # 更新代码 new_line = 'const-string {}, "{}"'.format(rtn_name, result) new_body.append(new_line) self.make_changes = True # print(args) mtd.set_modified(True) elif rtype.startswith('['): # print("返回值为数组,更新寄存器内容") # print(result) args[rtn_name] = result # print(args) else: print("返回值并非字符串,也不是B/C数组") # print('-' * 100) mtd.set_body('\n'.join(new_body))
Example usage: echo "{red}Red{/red}" |python -m colorclass """ from __future__ import print_function import fileinput import os from colorclass.color import Color from colorclass.toggles import disable_all_colors from colorclass.toggles import enable_all_colors from colorclass.toggles import set_dark_background from colorclass.toggles import set_light_background from colorclass.windows import Windows TRUTHY = ('true', '1', 'yes', 'on') if __name__ == '__main__': if os.environ.get('COLOR_ENABLE', '').lower() in TRUTHY: enable_all_colors() elif os.environ.get('COLOR_DISABLE', '').lower() in TRUTHY: disable_all_colors() if os.environ.get('COLOR_LIGHT', '').lower() in TRUTHY: set_light_background() elif os.environ.get('COLOR_DARK', '').lower() in TRUTHY: set_dark_background() Windows.enable() for LINE in fileinput.input(): print(Color(LINE))
def test_colorize_methods(): """Test colorize convenience methods.""" assert Color.black('TEST').value_colors == '\033[30mTEST\033[39m' assert Color.bgblack('TEST').value_colors == '\033[40mTEST\033[49m' assert Color.red('TEST').value_colors == '\033[31mTEST\033[39m' assert Color.bgred('TEST').value_colors == '\033[41mTEST\033[49m' assert Color.green('TEST').value_colors == '\033[32mTEST\033[39m' assert Color.bggreen('TEST').value_colors == '\033[42mTEST\033[49m' assert Color.yellow('TEST').value_colors == '\033[33mTEST\033[39m' assert Color.bgyellow('TEST').value_colors == '\033[43mTEST\033[49m' assert Color.blue('TEST').value_colors == '\033[34mTEST\033[39m' assert Color.bgblue('TEST').value_colors == '\033[44mTEST\033[49m' assert Color.magenta('TEST').value_colors == '\033[35mTEST\033[39m' assert Color.bgmagenta('TEST').value_colors == '\033[45mTEST\033[49m' assert Color.cyan('TEST').value_colors == '\033[36mTEST\033[39m' assert Color.bgcyan('TEST').value_colors == '\033[46mTEST\033[49m' assert Color.white('TEST').value_colors == '\033[37mTEST\033[39m' assert Color.bgwhite('TEST').value_colors == '\033[47mTEST\033[49m' assert Color.black( 'this is a test.', auto=True) == Color('{autoblack}this is a test.{/autoblack}') assert Color.black('this is a test.') == Color( '{black}this is a test.{/black}') assert Color.bgblack( 'this is a test.', auto=True) == Color('{autobgblack}this is a test.{/autobgblack}') assert Color.bgblack('this is a test.') == Color( '{bgblack}this is a test.{/bgblack}') assert Color.red('this is a test.', auto=True) == Color('{autored}this is a test.{/autored}') assert Color.red('this is a test.') == Color('{red}this is a test.{/red}') assert Color.bgred( 'this is a test.', auto=True) == Color('{autobgred}this is a test.{/autobgred}') assert Color.bgred('this is a test.') == Color( '{bgred}this is a test.{/bgred}') assert Color.green( 'this is a test.', auto=True) == Color('{autogreen}this is a test.{/autogreen}') assert Color.green('this is a test.') == Color( '{green}this is a test.{/green}') assert Color.bggreen( 'this is a test.', auto=True) == Color('{autobggreen}this is a test.{/autobggreen}') assert Color.bggreen('this is a test.') == Color( '{bggreen}this is a test.{/bggreen}') assert Color.yellow( 'this is a test.', auto=True) == Color('{autoyellow}this is a test.{/autoyellow}') assert Color.yellow('this is a test.') == Color( '{yellow}this is a test.{/yellow}') assert Color.bgyellow( 'this is a test.', auto=True) == Color('{autobgyellow}this is a test.{/autobgyellow}') assert Color.bgyellow('this is a test.') == Color( '{bgyellow}this is a test.{/bgyellow}') assert Color.blue( 'this is a test.', auto=True) == Color('{autoblue}this is a test.{/autoblue}') assert Color.blue('this is a test.') == Color( '{blue}this is a test.{/blue}') assert Color.bgblue( 'this is a test.', auto=True) == Color('{autobgblue}this is a test.{/autobgblue}') assert Color.bgblue('this is a test.') == Color( '{bgblue}this is a test.{/bgblue}') assert Color.magenta( 'this is a test.', auto=True) == Color('{automagenta}this is a test.{/automagenta}') assert Color.magenta('this is a test.') == Color( '{magenta}this is a test.{/magenta}') assert Color.bgmagenta( 'this is a test.', auto=True) == Color('{autobgmagenta}this is a test.{/autobgmagenta}') assert Color.bgmagenta('this is a test.') == Color( '{bgmagenta}this is a test.{/bgmagenta}') assert Color.cyan( 'this is a test.', auto=True) == Color('{autocyan}this is a test.{/autocyan}') assert Color.cyan('this is a test.') == Color( '{cyan}this is a test.{/cyan}') assert Color.bgcyan( 'this is a test.', auto=True) == Color('{autobgcyan}this is a test.{/autobgcyan}') assert Color.bgcyan('this is a test.') == Color( '{bgcyan}this is a test.{/bgcyan}') assert Color.white( 'this is a test.', auto=True) == Color('{autowhite}this is a test.{/autowhite}') assert Color.white('this is a test.') == Color( '{white}this is a test.{/white}') assert Color.bgwhite( 'this is a test.', auto=True) == Color('{autobgwhite}this is a test.{/autobgwhite}') assert Color.bgwhite('this is a test.') == Color( '{bgwhite}this is a test.{/bgwhite}')
def test_windows_stream(): """Test class.""" # Test error. if windows.IS_WINDOWS: stream = windows.WindowsStream(windows.init_kernel32()[0], windows.INVALID_HANDLE_VALUE, StringIO()) assert stream.colors == (windows.WINDOWS_CODES['white'], windows.WINDOWS_CODES['black']) stream.colors = windows.WINDOWS_CODES['red'] | windows.WINDOWS_CODES[ 'bgblue'] # No exception, just ignore. assert stream.colors == (windows.WINDOWS_CODES['white'], windows.WINDOWS_CODES['black']) # Test __getattr__() and color resetting. original_stream = StringIO() stream = windows.WindowsStream(MockKernel32(), windows.INVALID_HANDLE_VALUE, original_stream) assert stream.writelines == original_stream.writelines # Test __getattr__(). assert stream.colors == (windows.WINDOWS_CODES['white'], windows.WINDOWS_CODES['black']) stream.colors = windows.WINDOWS_CODES['red'] | windows.WINDOWS_CODES[ 'bgblue'] assert stream.colors == (windows.WINDOWS_CODES['red'], windows.WINDOWS_CODES['bgblue']) stream.colors = None # Resets colors to original. assert stream.colors == (windows.WINDOWS_CODES['white'], windows.WINDOWS_CODES['black']) # Test special negative codes. stream.colors = windows.WINDOWS_CODES['red'] | windows.WINDOWS_CODES[ 'bgblue'] stream.colors = windows.WINDOWS_CODES['/fg'] assert stream.colors == (windows.WINDOWS_CODES['white'], windows.WINDOWS_CODES['bgblue']) stream.colors = windows.WINDOWS_CODES['red'] | windows.WINDOWS_CODES[ 'bgblue'] stream.colors = windows.WINDOWS_CODES['/bg'] assert stream.colors == (windows.WINDOWS_CODES['red'], windows.WINDOWS_CODES['black']) stream.colors = windows.WINDOWS_CODES['red'] | windows.WINDOWS_CODES[ 'bgblue'] stream.colors = windows.WINDOWS_CODES['bgblack'] assert stream.colors == (windows.WINDOWS_CODES['red'], windows.WINDOWS_CODES['black']) # Test write. stream.write(Color('{/all}A{red}B{bgblue}C')) original_stream.seek(0) assert original_stream.read() == 'ABC' assert stream.colors == (windows.WINDOWS_CODES['red'], windows.WINDOWS_CODES['bgblue']) # Test ignore invalid code. original_stream.seek(0) original_stream.truncate() stream.write('\x1b[0mA\x1b[31mB\x1b[44;999mC') original_stream.seek(0) assert original_stream.read() == 'ABC' assert stream.colors == (windows.WINDOWS_CODES['red'], windows.WINDOWS_CODES['bgblue'])