def inj_code_chunk(chunk): """ Inject required code into chunk using smali tools 1. remove original "const-string" 2. get code chunks and line nums for insertion reg_num for original const-string: original reg_num for an additional register: 0, 1 """ mark = False lines_chunk = ret_lined_list(chunk) lines_chunk_new = [] new_codes = [] new_appends = [] line_nums = [] i = 0 for line in lines_chunk: # if const-string exist in line(chunk) if "const-string" in line: line_void = nullify(line) lines_chunk_new.append(line_void) i += 1 line = reg_p_to_v(chunk, line) line = reg_num_incr(line) # inc reg +1 line = reg_num_incr(line) # inc reg +1 line = base64_str(line) + "\n" line = line + gen_string(ret_reg_num(line)) new_codes.append(line) new_appends.append('') line_nums.append(i - 1) mark = True else: lines_chunk_new.append(line) i += 1 modified_chunk = '\n'.join(lines_chunk_new) # insert using smali tools # get obfuscated code chunks if mark: block = smali_tool.MethodBlock(modified_chunk) block.insert(2, new_codes, new_appends, line_nums, try_catch_flag=True) result = block.get_code() else: result = chunk return result, mark
def process_string(smali, filename): """ Encrypt string and - current file => split chunk => modify register => modify all const_string => write to file """ filename = smali + filename #print "Opening %s" % filename smali_file = open(filename, 'r') smali_code = smali_file.read() func_array = smali_code.split('.method') head = func_array[0] func_array = ['.method' + x for x in func_array[1:]] mark = False chunk_array = [] for chunk in func_array: # NOTE this check and continue is just a test for safe-insert temp = smali_tool.MethodBlock(chunk) nlocals = temp.nlocal nparams = temp.nparam if nlocals + nparams + STR_USING_REG > MAX_REG: chunk_array.append(chunk) continue chunk, temp_mark = inj_code_chunk(chunk) chunk_array.append(chunk) mark = mark or temp_mark output = head + '\n'.join(chunk_array) ofile = open(filename, 'w') ofile.write(output) ofile.close() return mark
def reg_p_to_v(chunk, line): """ change string in parameter to register e.g., PREV: const-string p0, "CzkbuVyq" NEXT: const-string v0, "CzkbuVyq" """ line = line.strip() inst, args = line.split(' ', 1) reg, string = args.split(',', 1) reg = reg.strip() string = string.strip() if reg[0] == 'p': temp = smali_tool.MethodBlock(chunk) nlocals = temp.nlocal nparams = temp.nparam pnum = int(reg[1:]) vnum = nlocals + pnum reg = 'v{0}'.format(vnum) line = '{0} {1}, {2}'.format(inst, reg, string) return line