forked from Rorschach123/DexScanner
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
212 lines (186 loc) · 6.71 KB
/
main.py
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
__author__ = 'Rorschach'
import sys,re,zipfile,time,os,shutil,_winreg,gc,random
import DexFormMap,DexFormLoader,DexFormAnalyzer,DexFormDetect
def GetDesktop():
key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders',)
return _winreg.QueryValueEx(key, "Desktop")[0]
def GetFilePath():
list = []
if len(sys.argv) > 1:
list.append(sys.argv[1])
else:
arg1 = raw_input("please input apk file path:\n")
#arg1 = TransString(arg1)
list.append(arg1)
return list
def RetDexPathByCmd():
listArgv = GetFilePath()
dexPath = listArgv[0]
if dexPath == "":
print "--Fail-- Ret file path "
exit(-1)
print "--Sucs-- Ret file path "
return dexPath
def RetDexPathByZipApk(apkPath):
unzipDirPath = UnzipFile(apkPath,GetDesktop())
if unzipDirPath == "":
print "--Fail-- Fail to unzip classes.dex"
return ""
else:
print "--Succ--"
return unzipDirPath
def GetSaltTimeStr():
return time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime()) + str(random.randint(0, 99999999))
def UnzipFile(path,unzipPath):
isZip = zipfile.is_zipfile(path)
starttime = GetSaltTimeStr()
hasFindAM = 0
hasFindDex = 0
if isZip:
filezip = zipfile.ZipFile(path,'r')
for file in filezip.namelist():
if file == "classes.dex":
if not os.path.isdir(unzipPath+"/"+ starttime +"/"):
os.makedirs(unzipPath+"/"+ starttime)
filezip.extract(file,unzipPath+"/"+ starttime +"/")
print "--Succ-- UnZip classes.dex Success"
hasFindDex += 1
if file == "AndroidManifest.xml":
if not os.path.isdir(unzipPath+"/"+ starttime +"/"):
os.makedirs(unzipPath+"/"+ starttime)
filezip.extract(file,unzipPath+"/"+ starttime +"/")
print "--Succ-- UnZip AndroidManifest.xml Success"
hasFindAM += 1
else:
print "--Fail-- Not Zip File"
if hasFindDex == 0:
hasFindDex = FindDexFileInOdex(unzipPath + "/" + starttime + "/",path)
if hasFindDex == 1 and hasFindAM == 1:
return unzipPath + "/" + starttime + "/"
else:
if os.path.isdir(unzipPath + "/" + starttime + "/"):
shutil.rmtree(unzipPath + "/" + starttime + "/")
return ""
def FindDexFileInOdex(unzipPath,apkPath):
strlen = len(apkPath)
while strlen != 0:
if apkPath[strlen-1:strlen] == "\\":
apkPath = apkPath[0:strlen]
break
strlen -= 1
odexList = []
LoopDirFiles(apkPath,odexList,".odex",5)
if len(odexList) == 1:
#cp file to unzipPath,cut before dex
open(unzipPath+"classes.dex", "wb").write(open(odexList[0], "rb").read())
ret = FixOdexToDex(unzipPath+"classes.dex")
return ret
return 0
def FixOdexToDex(dexFile):
try:
file = open(dexFile,"rb")
f = file.read()
cutOffset = 0
for i in range(0,len(f)):
if ord(f[i]) == 0x64 and ord(f[i+1]) == 0x65 and ord(f[i+2]) == 0x78 and ord(f[i+3]) == 0x0A:
cutOffset = i
break
file.seek(0,2)
fileSize = file.tell()
file.seek(cutOffset,0)
basePointer = []
for j in range(cutOffset,fileSize):
ch = file.read(1)
basePointer.append(ch)
except Exception,e:
return 0
finally:
file.close()
os.remove(dexFile)
try:
classFile = open(dexFile,"wb")
for j in basePointer:
classFile.write(j)
finally:
classFile.close()
return 1
def LoopDirFiles(path,fileList,keyStr,lens):
files = os.listdir(path)
for file in files:
filePath = os.path.join(path,file)
if os.path.isdir(filePath):
LoopDirFiles(filePath,fileList,keyStr,lens)
else:
strLen = len(filePath)
if filePath[strLen-lens:strLen] == keyStr:
fileList.append(filePath)
#remove unzip file
def CleanFiles(dexPath,amTime):
pathList = dexPath.split("/")
dexDirPath = ""
for listNum in range(0,(len(pathList) - 1)):
dexDirPath = dexDirPath + pathList[listNum] + "/"
if os.path.isdir(dexDirPath):
shutil.rmtree(dexDirPath)
if __name__ == '__main__':
print "--------------Start Main Func------------------"
#get file path list:
apkPath = RetDexPathByCmd()
apkList = []
if os.path.isdir(apkPath):
#dir:loop all files
LoopDirFiles(apkPath,apkList,".apk",4)
else:
strLen = len(apkPath)
if apkPath[strLen-4:strLen] == ".apk":
apkList.append(apkPath)
try:
logFileName = GetDesktop()+"\\log-" + GetSaltTimeStr()
logFile = open(logFileName,"w+")
oldStdOut = sys.stdout
sys.stdout = logFile
finally:
r0 = 0
#analyze dex file path
for file in apkList:
dexFormMap = DexFormMap.DexMap()
dexFormLoader = DexFormLoader.DexLoader()
dexFormAnalyzer = DexFormAnalyzer.DexAnalyzer()
print "File :" + file
print "--Load-- Get dex file path"
unzipDir = RetDexPathByZipApk(file)
if unzipDir == "":
print "--Fail-- Not Found Unzip Dir"
continue
dexPath = unzipDir + "classes.dex"
amTime = GetSaltTimeStr()
#read dex file
print "--Load-- Read Dex file"
try:
dexFormLoader.GetMapFile(dexFormMap,dexPath)
except Exception,e:
CleanFiles(dexPath,amTime)
continue
#analyze dex file
dexHeader = DexFormAnalyzer.DexHeaderProperty(dexFormLoader.mapfile)
dexFormLoader.LoadAllClassAndMethod(dexHeader)
#Resolute ins
dexDetect = DexFormDetect.DexDetect()
dexDetect.SetDexLoaderObj(dexFormLoader)
#Count number of set port
print "--------------------------------------------------------------------------"
countSetPort = dexDetect.DetectApkApi(dexHeader)
print "--------------------------------------------------------------------------"
CleanFiles(dexPath,amTime)
print ""
del dexFormMap
del dexFormLoader
del dexFormAnalyzer
gc.collect()
if logFile:
logFile.close()
if oldStdOut:
sys.stdout = oldStdOut
print "--------------Finish Main Fnc------------------"
os.system('pause')
#r"C:\Users\Rorschach\Desktop\MI5\sapp\AntHalService\AntHalService.apk"