用python枚举smali中使用到的常量

前言

在分析安卓apk时,有时需要逆向出smali代码进行分析。本文提供通过python语言的方法,快速浏览出apk中包含的常量,从而实现对apk的快速分析。

1. python枚举目录

a) 枚举根路径中的子路径和文件,返回所有意smali结尾的文件的文件目录和名称。

def list_all_files(rootdir):
    import os
    _files = []
    list = os.listdir(rootdir) #列出文件夹下所有的目录与文件
    for i in range(0,len(list)):
           path = os.path.join(rootdir,list[i])
           if os.path.isdir(path):
              _files.extend(list_all_files(path))
           if os.path.isfile(path) and path.endswith(('.smali', '.SMALI')):
              _files.append(path)
    return _files

2. 查找smali文件中的常量

a) 在逆向出的smali文件中,字符串常量都是通过const-string进行赋值的。搜索const-string,解析出后面双引号中的值,即为程序中使用到的常量。

def find_const_string(filename):
	_consts = set()
	with open(filename) as f_txt:
		for line in f_txt:
			if line.find('const-string')>0:
				pos1 = line.find('"', 12)
				pos2 = line.find('"', pos1+1)
				if pos1>0 and pos2>0:
					_consts.add(line[pos1+1:pos2])
	return _consts

3. 输入路径,将结果保存到文件中

程序入口,调用上面的函数,枚举出apk中使用的常量,并将结果保存到文件中。

if __name__ == "__main__" :
    if len(sys.argv) <= 1:
        print("please input the smali root path\n")
    else:
        files = list_all_files(sys.argv[1])
        cs = set();
        for file in files:
            cs |= find_const_string(file)

        with open('conststrs.txt', 'w') as wf:
            for c in cs:
                wf.write(c)
                wf.write('\n')

4,在命令行中调用

注意,本python使用的时3.6版本,2.7的版本未进行测试
在window上,命令行调用方法

C:\Users\HP\Desktop>python findconst.py C:\Users\HP\Desktop\testapk\smali

猜你喜欢

转载自blog.csdn.net/harborian/article/details/85043767