forked from zsdlove/ApkVulCheck
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAndroidCodeCheck.py
More file actions
Latest commit
294 lines (259 loc) · 8.42 KB
/
Copy pathAndroidCodeCheck.py
File metadata and controls
294 lines (259 loc) · 8.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
# -- coding:utf-8 --
'''
Coded by zsdlove
This is a toolt to help android app developers to check the flaws in their sourcecode
'''
importos
importdatetime
fromplugin.manifestAnalysisimportcomponentcheck
fromplugin.mobileSDKAnalysisimportmobileSDKAnalysis
fromplugin.apkInfoCrawlerimportapkinfoCrawler
fromplugin.permissionAnalyzerimportpermissionAnalyzer
fromconfigimport*
importjson
importhashlib
importplatform
fromplugin.shellDetectorimportshellDetector
fromplugin.fastanalyzeimportfastAnalyze
importclick
importrandom
importzipfile
importjson2html
defhandleResult(func):
'''
处理apk检测结果
'''
defwrapper(*args,**kwargs):
ret=func(*args,**kwargs)
ifret[1]=="json":
withopen("./report/{}.json".format(ret[4]),"w")asf:
f.write(json.dumps(ret[0], indent=2))
elifret[1]=="html":
html_content='''
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<title>ApkVulCheck-{}-风险检测报告</title>
<meta charset="utf-8" />
</head>
<body>
<h1 style="text-align:center">ApkVulCheck-{}-风险检测报告</h1>
<hr />
{}
<div>2020 ApkVulCheck,inc.</div>
</body>
'''
withopen("./report/{}.html".format(ret[4]), "w")asf:
f.write(html_content.format(ret[4],ret[4],json2html.json2html.convert(ret[0])))
else:
withopen("./report/{}.json".format(ret[4]),"w")asf:
f.write(json.dumps(ret[0], indent=2))
withopen(ret[2],"w")asf:
f.write(json.dumps(ret[0], indent=2))
print(ret[0])
print("[Reporter] - generate result successfully.")
returnwrapper
defprovide_env():
ifplatform.system()=="Windows":
print("不支持windows,请自行修复路径问题.")
exit(0)
'''
准备缓存文件
'''
ifnotos.path.exists("/tmp/hades/result/"):
ifos.path.exists("/tmp/hades/"):
os.mkdir("/tmp/hades/result")
else:
os.mkdir("/tmp/hades/")
os.mkdir("/tmp/hades/result/")
classapkAnalysis():
'''
apk静态分析
'''
def__init__(self):
self.result={}
provide_env()
defgetAndroidManifest(self,apkpath,outputpath):
'''
获取manifest.xml
'''
try:
zipfiles=zipfile.ZipFile(apkpath)
a=zipfiles.read('AndroidManifest.xml')
ifa!='':
apkdir=outputpath
ifnotos.path.exists(apkdir):
os.makedirs(apkdir)
dexfile=open('{}/AndroidManifest.xml'.format(outputpath),'wb')
dexfile.write(a)
else:
logging.error('- [error] function getAndroidManifest(apkname) 找不到AndroidManifest.xml文件!')
except:
logging.error('- [error] function getAndroidManifest(apkname) 找不到AndroidManifest.xml文件!')
defdecompile_AndroidManifest(self,apkpath,outputpath):
'''
解析manifest.xml
'''
try:
ifnotos.path.exists(apkpath):
os.makedirs(apkpath)
self.getAndroidManifest(apkpath, outputpath) # 获取apk中的AndroidManifest.xml文件
cmd="java -jar lib/AXMLPrinter2.jar {}/AndroidManifest.xml > {}/AndroidManifest_resolved.xml".format(outputpath,outputpath)
os.system(cmd)
logging.info("[init] - Decode the AndroidManifest.xml file Successfully!")
print("[init] - Decode the AndroidManifest.xml file Successfully!")
except:
logging.info("- [init] - Can't Decode the AndroidMnifest.xml file.")
print("- [init] - Can't Decode the AndroidMnifest.xml file.")
defdecompiledex(self, apkpath, outputPath):
'''
@param apkpath path of malware_test.
@param outputpath path of result file.
反编译dex文件
'''
try:
cmd="java -jar lib/baksmali.jar %s -o %s"%(apkpath,outputPath)
print("outputpath=>%s"%outputPath)
os.system(cmd)
logging.info("[init] - Decompile the dex file Successfully.")
print("[init] - Decompile the dex file Successfully.")
except:
logging.info("[init] - Can't decompile the dex file.")
print("[init] - Can't decompile the dex file.")
@handleResult
deffastScanEngine(self,task):
'''
快速分析apk
:param task:
:return:
'''
stattime=str(datetime.datetime.now())[:19]
provide_env()
filepath=task.get("taskpath")
taskname=filepath.split('/')[-1].split('.')[0]
outputPath='/tmp/hades/result/%s'%taskname+str(random.randint(10000,99999))
resultpath="{}/result.json".format(outputPath)
self.decompile_AndroidManifest(filepath,outputPath)
self.decompiledex(filepath,outputPath)
cptcheck=componentcheck(outputPath)#component analysis
cptcheck.run()
activityEntryList,serviceEntryList=cptcheck.activityPathList,cptcheck.servicePathList
providerEntryList,broadcastEntryList,packageName,version=cptcheck.providerPathList,cptcheck.broadcastPathList,cptcheck.packageName,cptcheck.version
totalEntryList=activityEntryList+serviceEntryList+providerEntryList+broadcastEntryList
msa=mobileSDKAnalysis()
nastySDKList,Advertisement,thirdpartPayAPI,otherSDKs=msa.analysis(totalEntryList)
aic=apkinfoCrawler()
crawlresult=aic.Micrawler(packageName)
ifcrawlresult.get("developer")=="default":
crawlresult=aic.Micrawler(packageName)
developer=crawlresult.get('developer')
classify=crawlresult.get('classify')
apkname=os.popen("lib/aapt2 dump badging %s |grep application-label:"%filepath).read().replace("\n","").split(":")[1].replace("'","")
donwloads=crawlresult.get('downloads')
history=crawlresult.get('history')
apkfrom=crawlresult.get('from')
'''
权限检查
'''
pA=permissionAnalyzer()
dangerous_permissions=pA.analysis(cptcheck.permissionList)
apksize=os.path.getsize(filepath)
defgethash(file):
m,s1,s256=hashlib.md5(),hashlib.sha1(),hashlib.sha256()
withopen(file, 'rb') asf:
forlineinf:
m.update(line)
s1.update(line)
s256.update(line)
returnm.hexdigest(),s1.hexdigest(),s256.hexdigest()
md5str, shastr, sha256str=gethash(filepath)
'''
壳校验
'''
sd=shellDetector()
isShelled,shellType=sd.shellDetector(filepath)
'''
开始快速模式扫描
'''
ipv4_s, ipv6_s, senAPI_s, pathlist, urlslist, emaillist, flaws_s= [], [], [], [], [], [],[]
pathlist=[os.path.join(root, file)
forroot,dirs,filesinos.walk(outputPath)
forfileinfiles
ifos.path.splitext(file)[1] =='.smali' ]
pathlist=[path
forpathinpathlist
if"com/google"notinpathand"android/"notinpathand"androidx"notinpath]
forpathinpathlist:
try:
print("[*]ananlysis %s"%path)
sensitiveAPI,ipv4,ipv6,urls,emails,flaws=fastAnalyze(path).analyze()
iflen(ipv4)>0:[ipv4_s.append(ip) foripinipv4]
iflen(ipv6)>0:[ipv6_s.append(ip) foripinipv6]
iflen(sensitiveAPI)>0:senAPI_s.append(sensitiveAPI)
iflen(urls)>0:[urlslist.append(url) forurlinurls]
iflen(emails)>0:[emaillist.append(email)foremailinemails]
iflen(flaws)>0:flaws_s.append(flaws)
except:
pass
self.result= {
"Advertisement": Advertisement,
"thirdpartPayAPI": thirdpartPayAPI,
"nastySDKs": nastySDKList,
"otherSDKs": otherSDKs,
"packageName": packageName,
"version": version,
"size": str(apksize/1048576) +"MB"ifapksize>1048576elsestr(apksize/1024) +"KB",
"from": apkfrom,
"time": str(datetime.datetime.now()),
"md5": md5str,
"sha1": shastr,
"sha256": sha256str,
"permission": dangerous_permissions,
'activity': activityEntryList,
'service': serviceEntryList,
'provider': providerEntryList,
'receiver': broadcastEntryList,
"developer": developer,
"classify": classify,
"apkname": apkname,
"shelltype": shellType,
"donwloads": donwloads,
"history": history,
"taskid": task.get("taskid"),
"target": filepath,
"starttime": stattime,
"endtime": str(datetime.datetime.now())[:19],
"ipv4":ipv4_s,
"ipv6":ipv6_s,
"sensitiveAPI":senAPI_s,
"urls":urlslist,
"emails":emaillist,
"flaws":flaws_s,
}
returnself.result,task.get("output"),resultpath,task.get('taskid'),apkname
defgentaskid(taskpath):
'''
生成taskid
'''
m=hashlib.md5()
m.update(taskpath.encode("utf-8"))
returnm.hexdigest()+str(random.randint(10000,99999))
defpath_validate(filepath):
'''
路径校验
:param filepath:
:return:
'''
returnTrueiffilepath.endswith(".apk") and".."notinfilepathelseFalse
@click.command()
@click.option("--taskpath",default="test/3436test1.apk",help='please input the apk path')
@click.option("--output",default="undefined",help='please input the path of the output')
defstartprocess(**kwargs):
apkAnalysis().fastScanEngine({
"taskpath":kwargs.get("taskpath"),
"taskid":gentaskid(kwargs.get("taskpath")),
"output":kwargs.get("output")
}
)
if__name__=='__main__':
startprocess()