forked from abrignoni/iLEAPP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ilapfuncs.py
3030 lines (2718 loc) · 108 KB
/
ilapfuncs.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
import sqlite3
import sys, os, re
import glob
import ccl_bplist
import datetime
import plistlib
from parse3 import ParseProto
import codecs
import json
import sqlite3
import io
import sys
import csv
import pathlib
import shutil
import textwrap
import base64
from time import process_time
nl = '\n'
now = datetime.datetime.now()
currenttime = str(now.strftime('%Y-%m-%d_%A_%H%M%S'))
reportfolderbase = './ILEAPP_Reports_'+currenttime+'/'
base = '/ILEAPP_Reports_'+currenttime+'/'
temp = reportfolderbase+'temp/'
def logfunc(message):
if pathlib.Path(reportfolderbase+'Script Logs/Screen Output.html').is_file():
with open(reportfolderbase+'Script Logs/Screen Output.html', 'a', encoding='utf8') as a:
print(message)
a.write(message+'<br>')
else:
with open(reportfolderbase+'Script Logs/Screen Output.html', 'a', encoding='utf8') as a:
print(message)
a.write(message+'<br>')
def datark(filefound):
logfunc(f'Data_ark.plist function executing.')
try:
os.makedirs(reportfolderbase+'Data_Ark/')
with open(reportfolderbase+'Data_Ark/Data Ark.html','w') as f:
f.write('<html><body>')
f.write('<h2>Mobile Activation Report</h2>')
f.write(f'Data_ark.plist located at {filefound[0]}<br>')
f.write('<style> table, th, td {border: 1px solid black; border-collapse: collapse;} tr:nth-child(even) {background-color: #f2f2f2;} </style>')
f.write('<br/>')
f.write('')
f.write(f'<table>')
f.write(f'<tr><td>Key</td><td>Values</td></tr>')
with open(filefound[0], 'rb') as fp:
pl = plistlib.load(fp)
for key, val in pl.items():
f.write(f'<tr><td>{key}</td><td>{val}</td></tr>')
f.write(f'</table></body></html>')
logfunc(f'Data_ark.plist function completed')
except:
logfunc('Error in Sys Diagnose Network Preferences function.')
def mobilact(filefound):
logfunc(f'Mobile Activation function executing.')
try:
linecount = 0
hitcount = 0
activationcount = 0
filescounter = 0
if os.path.exists(reportfolderbase+'SysDiagnose/'):
pass
else:
os.makedirs(reportfolderbase+'SysDiagnose/')
f =open(reportfolderbase+'SysDiagnose/Mobile Activation Logs.html','w')
f.write('<html><body>')
f.write('<h2>Mobile Activation Report</h2>')
f.write('Logs in private/var/mobile/Library/Logs/mobileactivationd/mobileactivationd.log.*<br>')
for filename in filefound:
file = open(filename, 'r', encoding='utf8' )
filescounter = filescounter + 1
for line in file:
linecount += 1
if 'perform_data_migration' in line:
hitcount += 1
#print("\n" + line)
txts = line.split()
#print(txts, linecount)
#print(len(txts))
dayofweek = txts[0]
month = txts[1]
day = txts[2]
time = txts[3]
year = txts[4]
frombuild = txts[12]
tobuild = txts[14]
f.write("<br><br>" + day + " " + month + " " + year + " " + time + " Upgraded from " + frombuild + " to " + tobuild + " [line " + str(linecount) + "]")
if 'MA: main: ____________________ Mobile Activation Startup _____________________' in line:
activationcount += 1
#print("\n" + line)
txts = line.split()
#print(txts, linecount)
#print(len(txts))
dayofweek = txts[0]
month = txts[1]
day = txts[2]
time = txts[3]
year = txts[4]
f.write("<br><br>" + day + " " + month + " " + year + " " + time + " Mobile Activation Startup " + " [line " + str(linecount) + "]")
if 'MA: main: build_version:' in line:
#print("\n" + line)
txts = line.split()
#print(txts, linecount)
#print(len(txts))
dayofweek = txts[0]
month = txts[1]
day = txts[2]
time = txts[3]
year = txts[4]
buildver = txts[11]
f.write("<br>"+ day + " " + month + " " + year + " " + time + " Mobile Activation Build Version = " + buildver)
if 'MA: main: hardware_model:' in line:
#print("\n" + line)
txts = line.split()
#print(txts, linecount)
#print(len(txts))
dayofweek = txts[0]
month = txts[1]
day = txts[2]
time = txts[3]
year = txts[4]
hwmodel = txts[11]
f.write("<br>" + day + " " + month + " " + year + " " + time + " Mobile Activation Hardware Model = " + hwmodel)
if 'MA: main: product_type:' in line:
#print("\n" + line)
txts = line.split()
#print(txts, linecount)
#print(len(txts))
dayofweek = txts[0]
month = txts[1]
day = txts[2]
time = txts[3]
year = txts[4]
prod = txts[11]
f.write("<br>" + day + " " + month + " " + year + " " + time + " Mobile Activation Product Type = " + prod)
if 'MA: main: device_class:' in line:
#print("\n" + line)
txts = line.split()
#print(txts, linecount)
#print(len(txts))
dayofweek = txts[0]
month = txts[1]
day = txts[2]
time = txts[3]
year = txts[4]
devclass = txts[11]
f.write("<br>"+ day + " " + month + " " + year + " " + time + " Mobile Activation Device Class = " + devclass)
file.close()
f.write("<br><br>Found " + str(hitcount) + " Upgrade entries")
f.write("<br> Found " + str(activationcount) + " Mobile Activation Startup entries")
f.write('</body></html>')
f.close()
logfunc(f'Mobile Activation completed executing.')
except:
logfunc('Error in MobileActivation Logs section')
def bkupstate(filefound):
logfunc(f'BackupStateInfo function executing.')
try:
if os.path.exists(reportfolderbase+'SysDiagnose/'):
pass
else:
os.makedirs(reportfolderbase+'SysDiagnose/')
f =open(reportfolderbase+'SysDiagnose/BackupStateInfo.txt','w')
p = open(filefound[0], 'rb')
plist = plistlib.load(p)
#create html headers
filedatahtml = open(reportfolderbase+'SysDiagnose/BackupStateInfo.html', mode='a+')
filedatahtml.write('<html><body>')
filedatahtml.write('<h2>BackupStateInfo Report </h2>')
filedatahtml.write ('<style> table, th, td {border: 1px solid black; border-collapse: collapse;} tr:nth-child(even) {background-color: #f2f2f2;} </style>')
filedatahtml.write('<table>')
filedatahtml.write(f'<tr><td colspan = "2">BackupStateInfo Items</td></tr>')
pl = plist # This code taken from https://github.com/cheeky4n6monkey/iOS_sysdiagnose_forensic_scripts/blob/master/sysdiagnose-mobilebackup.py
if 'BackupStateInfo' in pl.keys():
for key, val in pl["BackupStateInfo"].items():
#print("key = " + str(key) + ", val = " + str(val))
if key == 'date':
filedatahtml.write(f'<tr><td>BackupStateInfo Date</td><td>{str(val)}</td></tr>')
if key == 'isCloud':
filedatahtml.write(f'<tr><td>BackupStateInfo isCloud</td><td>{str(val)}</td></tr>')
if 'RestoreInfo' in pl.keys():
for key, val in pl["RestoreInfo"].items():
if key == 'RestoreDate':
filedatahtml.write(f'<tr><td>RestoreInfo Date</td><td>{str(val)}</td></tr>')
if key == 'BackupBuildVersion':
filedatahtml.write(f'<tr><td>RestoreInfo BackupBuildVersion</td><td>{str(val)}</td></tr>')
if key == 'DeviceBuildVersion':
filedatahtml.write(f'<tr><td>RestoreInfo DeviceBuildVersion</td><td>{str(val)}</td></tr>')
if key == 'WasCloudRestore':
filedatahtml.write(f'<tr><td>RestoreInfo WasCloudRestore</td><td>{str(val)}</td></tr>')
filedatahtml.write('</table></html>')
filedatahtml.write('<br>')
filedatahtml.write('<table>')
filedatahtml.write(f'<tr><td colspan = "2">{filefound[0]}</td></tr>')
filedatahtml.write('<tr><td>Key</td><td>Value</td></tr>')
for key, val in plist.items():
f.write(f'{key} {val}{nl}')
filedatahtml.write(f'<tr><td>{key}</td><td>{val}</td></tr>')
f.close()
#close html footer
filedatahtml.write('</table></html>')
filedatahtml.close()
except:
logfunc('Error in BackupStateInfo function section')
logfunc(f'BackupStateInfo function completed.')
def datausage(filefound):
os.makedirs(reportfolderbase+'Data Usage/')
try:
db = sqlite3.connect(filefound[0])
cursor = db.cursor()
cursor.execute('''
SELECT
DATETIME(ZPROCESS.ZTIMESTAMP + 978307200, 'unixepoch') AS "PROCESS TIMESTAMP",
DATETIME(ZPROCESS.ZFIRSTTIMESTAMP + 978307200, 'unixepoch') AS "PROCESS FIRST TIMESTAMP",
DATETIME(ZLIVEUSAGE.ZTIMESTAMP + 978307200, 'unixepoch') AS "LIVE USAGE TIMESTAMP",
ZBUNDLENAME AS "BUNDLE ID",
ZPROCNAME AS "PROCESS NAME",
ZWIFIIN AS "WIFI IN",
ZWIFIOUT AS "WIFI OUT",
ZWWANIN AS "WWAN IN",
ZWWANOUT AS "WWAN OUT",
ZLIVEUSAGE.Z_PK AS "ZLIVEUSAGE TABLE ID"
FROM ZLIVEUSAGE
LEFT JOIN ZPROCESS ON ZPROCESS.Z_PK = ZLIVEUSAGE.ZHASPROCESS
''')
all_rows = cursor.fetchall()
usageentries = len(all_rows)
if usageentries > 0:
logfunc(f'Data Usage - Zliveusage function executing')
with open(reportfolderbase+'Data Usage/Zliveusage.html', 'w', encoding='utf8') as f:
f.write('<html><body>')
f.write('<h2> Zliveusage report</h2>')
f.write(f'Zliveusage entries: {usageentries}<br>')
f.write(f'Zliveusage located at: {filefound[0]}<br>')
f.write('<style> table, th, td {border: 1px solid black; border-collapse: collapse;} tr:nth-child(even) {background-color: #f2f2f2;} </style>')
f.write('<br/>')
f.write('')
f.write(f'<table>')
f.write(f'<tr><td>Process Timestamp</td><td>Process First Timestamp</td><td>Live Usage Timestamp</td><td>Bundle ID</td><td>Process Name</td><td>WIFI In</td><td>WIFI Out</td><td>WWAN IN</td><td>WWAN Out</td><td>Table ID</td></tr>')
for row in all_rows:
f.write(f'<tr><td>{row[0]}</td><td>{row[1]}</td><td>{row[2]}</td><td>{row[3]}</td><td>{row[4]}</td><td>{row[5]}</td><td>{row[6]}</td><td>{row[7]}</td><td>{row[8]}</td><td>{row[9]}</td></tr>')
f.write(f'</table></body></html>')
logfunc(f'Data Usage - Zliveusage function completed')
else:
logfunc('No Data Usage - Zliveusage available')
except:
logfunc('Error in Data Usage - Zliveusage section.')
try:
db = sqlite3.connect(filefound[0])
cursor = db.cursor()
cursor.execute('''
SELECT
DATETIME(ZPROCESS.ZTIMESTAMP+ 978307200, 'unixepoch') AS "TIMESTAMP",
DATETIME(ZPROCESS.ZFIRSTTIMESTAMP + 978307200, 'unixepoch') AS "PROCESS FIRST TIMESTAMP",
ZPROCESS.ZPROCNAME AS "PROCESS NAME",
ZPROCESS.ZBUNDLENAME AS "BUNDLE ID",
ZPROCESS.Z_PK AS "ZPROCESS TABLE ID"
FROM ZPROCESS
''')
all_rows = cursor.fetchall()
usageentries = len(all_rows)
if usageentries > 0:
logfunc(f'Data Usage - Zprocess function executing')
with open(reportfolderbase+'Data Usage/Zprocess.html', 'w', encoding='utf8') as f:
f.write('<html><body>')
f.write('<h2> Zprocess report</h2>')
f.write(f'Zprocess entries: {usageentries}<br>')
f.write(f'Zprocess located at: {filefound[0]}<br>')
f.write('<style> table, th, td {border: 1px solid black; border-collapse: collapse;} tr:nth-child(even) {background-color: #f2f2f2;} </style>')
f.write('<br/>')
f.write('')
f.write(f'<table>')
f.write(f'<tr><tr><td>Process Timestamp</td><td>Process First Timestamp</td><td>Live Usage Timestamp</td><td>Bundle ID</td><td>Table ID</td></tr>')
for row in all_rows:
f.write(f'<tr><td>{row[0]}</td><td>{row[1]}</td><td>{row[2]}</td><td>{row[3]}</td><td>{row[4]}</td></tr>')
f.write(f'</table></body></html>')
logfunc(f'Data Usage - Zprocess function completed')
else:
logfunc('No Data Usage - Zprocess available')
except:
logfunc('Error in Data Usage - Zprocess Section.')
def medlib(filefound):
os.makedirs(reportfolderbase+'Media Library/')
try:
db = sqlite3.connect(filefound[0])
cursor = db.cursor()
cursor.execute('''
select
ext.title AS "Title",
ext.media_kind AS "Media Type",
itep.format AS "File format",
ext.location AS "File",
ext.total_time_ms AS "Total time (ms)",
ext.file_size AS "File size",
ext.year AS "Year",
alb.album AS "Album Name",
alba.album_artist AS "Artist",
com.composer AS "Composer",
gen.genre AS "Genre",
art.artwork_token AS "Artwork",
itev.extended_content_rating AS "Content rating",
itev.movie_info AS "Movie information",
ext.description_long AS "Description",
ite.track_number AS "Track number",
sto.account_id AS "Account ID",
strftime('%d/%m/%Y %H:%M:%S', datetime(sto.date_purchased + 978397200,'unixepoch'))date_purchased,
sto.store_item_id AS "Item ID",
sto.purchase_history_id AS "Purchase History ID",
ext.copyright AS "Copyright"
from
item_extra ext
join item_store sto using (item_pid)
join item ite using (item_pid)
join item_stats ites using (item_pid)
join item_playback itep using (item_pid)
join item_video itev using (item_pid)
left join album alb on sto.item_pid=alb.representative_item_pid
left join album_artist alba on sto.item_pid=alba.representative_item_pid
left join composer com on sto.item_pid=com.representative_item_pid
left join genre gen on sto.item_pid=gen.representative_item_pid
left join item_artist itea on sto.item_pid=itea.representative_item_pid
left join artwork_token art on sto.item_pid=art.entity_pid
''')
all_rows = cursor.fetchall()
usageentries = len(all_rows)
if usageentries > 0:
logfunc(f'Media Library function executing')
with open(reportfolderbase+'Media Library/Media Library.html', 'w', encoding='utf8') as f:
f.write('<html><body>')
f.write('<h2> Media Library report</h2>')
f.write(f'Media Library entries: {usageentries}<br>')
f.write(f'Media Library located at: {filefound[0]}<br>')
f.write('<style> table, th, td {border: 1px solid black; border-collapse: collapse;} tr:nth-child(even) {background-color: #f2f2f2;} </style>')
f.write('<br/>')
f.write('')
f.write(f'<table>')
f.write(f'<tr><td>Title</td><td>Media Type</td><td>File Format</td><td>File</td><td>Total Time (ms)</td><td>File Size</td><td>Year</td><td>Album Name</td><td>Artist</td><td>Composer</td><td>Genre</td><td>Artwork</td><td>Content Rating</td><td>Movie Information</td><td>Description</td><td>Track Number</td><td>Account ID</td><td>Date Purchased</td><td>Item ID</td><td>Purchase History ID</td><td>Copyright</td></tr>')
for row in all_rows:
f.write(f'<tr><td>{row[0]}</td><td>{row[1]}</td><td>{row[2]}</td><td>{row[3]}</td><td>{row[4]}</td><td>{row[5]}</td><td>{row[6]}</td><td>{row[7]}</td><td>{row[8]}</td><td>{row[9]}</td><td>{row[10]}</td><td>{row[11]}</td><td>{row[12]}</td><td>{row[13]}</td><td>{row[14]}</td><td>{row[15]}</td><td>{row[16]}</td><td>{row[17]}</td><td>{row[18]}</td><td>{row[19]}</td><td>{row[20]}</td></tr>')
f.write(f'</table></body></html>')
logfunc(f'Media Library function completed')
else:
logfunc('No Media Library available')
except:
logfunc('Error in Media Library Section.')
def accs(filefound):
os.makedirs(reportfolderbase+'Accounts/')
try:
db = sqlite3.connect(filefound[0])
cursor = db.cursor()
cursor.execute('''
SELECT
ZACCOUNTTYPEDESCRIPTION,
ZUSERNAME,
DATETIME(ZDATE+978307200,'UNIXEPOCH','UTC' ) AS 'ZDATE TIMESTAMP',
ZACCOUNTDESCRIPTION,
ZACCOUNT.ZIDENTIFIER,
ZACCOUNT.ZOWNINGBUNDLEID
FROM ZACCOUNT
JOIN ZACCOUNTTYPE ON ZACCOUNTTYPE.Z_PK=ZACCOUNT.ZACCOUNTTYPE
ORDER BY ZACCOUNTTYPEDESCRIPTION
''')
all_rows = cursor.fetchall()
usageentries = len(all_rows)
if usageentries > 0:
logfunc(f'Account Data function executing')
with open(reportfolderbase+'Accounts/Accounts.html', 'w', encoding='utf8') as f:
f.write('<html><body>')
f.write('<h2> Account Data report</h2>')
f.write(f'Account Data entries: {usageentries}<br>')
f.write(f'Account Data located at: {filefound[0]}<br>')
f.write('<style> table, th, td {border: 1px solid black; border-collapse: collapse;} tr:nth-child(even) {background-color: #f2f2f2;} </style>')
f.write('<br/>')
f.write('')
f.write(f'<table>')
f.write(f'<tr><td>Account Desc</td><td>Usermane</td><td>Timestamp</td><td>Description</td><td>Identifier</td><td>Bundle ID</td></tr>')
for row in all_rows:
f.write(f'<tr><td>{row[0]}</td><td>{row[1]}</td><td>{row[2]}</td><td>{row[3]}</td><td>{row[4]}</td><td>{row[5]}</td></tr>')
f.write(f'</table></body></html>')
logfunc(f'Account Data function completed')
else:
logfunc('No Account Data available')
except:
logfunc('Error in Account Data Section.')
def conndevices(filefound):
with open(filefound[0], "rb") as f:
data = f.read()
logfunc(f'Connected devices function executing.')
outpath = reportfolderbase +'Devices Connected/'
os.mkdir(outpath)
nl = '\n'
userComps = ""
logfunc("Data being interpreted for FRPD is of type: " + str(type(data)))
x = type(data)
byteArr = bytearray(data)
userByteArr = bytearray()
magicOffset = byteArr.find(b'\x01\x01\x80\x00\x00')
magic = byteArr[magicOffset:magicOffset + 5]
flag = 0
if magic == b'\x01\x01\x80\x00\x00':
logfunc("Found magic bytes in iTunes Prefs FRPD... Finding Usernames and Desktop names now")
f = open(outpath+'DevicesConnected.html', 'w')
f.write('<html>')
f.write(f'Artifact name and path: {filefound[0]}<br>')
f.write(f'Usernames and Computer names:<br><br>')
for x in range (int(magicOffset + 92), len(data)):
if (data[x]) == 0:
x = int(magicOffset) + 157
if userByteArr.decode() == "":
continue
else:
if flag == 0:
userComps += userByteArr.decode() + " - "
flag = 1
else:
userComps += userByteArr.decode() + "\n"
flag = 0
userByteArr = bytearray()
continue
else:
char = (data[x])
userByteArr.append(char)
logfunc(f'{userComps}{nl}')
f.write(f'{userComps}<br>')
f.write(f'</html>')
f.close()
logfunc(f'Connected devices function completed. ')
def applicationstate(filefound):
#iOSversion = versionf
logfunc(f'ApplicationState.db queries executing.')
outpath = reportfolderbase +'Application State/'
try:
os.mkdir(outpath)
os.mkdir(outpath+"exported-dirty/")
os.mkdir(outpath+"exported-clean/")
except OSError:
logfunc("Error making directories")
freepath = 1
for pathfile in filefound:
if isinstance(pathfile, pathlib.PurePath):
freepath = os.path.abspath(pathfile)
if freepath.endswith('.db'):
apstatefiledb = freepath
elif pathfile.endswith('.db'):
apstatefiledb = pathfile
#connect sqlite databases
db = sqlite3.connect(apstatefiledb)
cursor = db.cursor()
cursor.execute('''
select
application_identifier_tab.[application_identifier],
kvs.[value]
from kvs, key_tab,application_identifier_tab
where
key_tab.[key]='compatibilityInfo' and kvs.[key] = key_tab.[id]
and application_identifier_tab.[id] = kvs.[application_identifier]
order by application_identifier_tab.[id]
''')
all_rows = cursor.fetchall()
#poner un try except por si acaso
extension = '.bplist'
count = 0
for row in all_rows:
bundleid = str(row[0])
bundleidplist = bundleid+'.bplist'
f = row[1]
output_file = open(outpath+'/exported-dirty/'+bundleidplist, 'wb') #export dirty from DB
output_file.write(f)
output_file.close()
g = open(outpath+'/exported-dirty/'+bundleidplist, 'rb')
#plist = plistlib.load(g)
plist = ccl_bplist.load(g)
output_file = open(outpath+'exported-clean/'+bundleidplist, 'wb')
output_file.write(plist)
output_file.close()
#create html headers
filedatahtml = open(outpath+'Application State.html', mode='a+')
filedatahtml.write('<html><body>')
filedatahtml.write('<h2>iOS ApplicationState.db Report </h2>')
filedatahtml.write ('<style> table, th, td {border: 1px solid black; border-collapse: collapse;}tr:nth-child(even) {background-color: #f2f2f2;}</style>')
filedatahtml.write('<br/>')
filedatahtml.write('<table>')
filedatahtml.write(f'<tr><td colspan = "4">{apstatefiledb}</td></tr>')
filedatahtml.write('<tr><td>Bundle ID</td><td>Bundle Path</td><td>Sandbox Path</td></tr>')
for filename in glob.glob(outpath+'exported-clean/*.bplist'):
p = open(filename, 'rb')
#cfilename = os.path.basename(filename)
plist = ccl_bplist.load(p)
ns_keyed_archiver_obj = ccl_bplist.deserialise_NsKeyedArchiver(plist, parse_whole_structure=False)#deserialize clean
#logfunc(ns_keyed_archiver_obj)
bid = (ns_keyed_archiver_obj['bundleIdentifier'])
bpath = (ns_keyed_archiver_obj['bundlePath'])
bcontainer = (ns_keyed_archiver_obj['bundleContainerPath'])
bsandbox = (ns_keyed_archiver_obj['sandboxPath'])
if bsandbox == '$null':
bsandbox = ''
if bcontainer == '$null':
bcontainer = ''
#csv report
filedata = open(outpath+'ApplicationState_InstalledAppInfo.csv', mode='a+')
filewrite = csv.writer(filedata, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
filewrite.writerow([bid, bpath, bcontainer, bsandbox])
count = count + 1
filedata.close()
#html report
filedatahtml.write(f'<tr><td>{bid}</td><td>{bpath}</td><td>{bsandbox}</td></tr>')
filemetadata = open(outpath+'ApplicationState_InstalledAppInfo_Path.txt', mode='w')
filemetadata.write(f'Artifact name and file path: {apstatefiledb} ')
filemetadata.close()
#close html footer
filedatahtml.write('</table></html>')
filedatahtml.close()
logfunc(f'Installed app GUIDs and app locations processed: {count}')
logfunc(f'ApplicationState.db queries completed.')
def knowledgec(filefound):
logfunc(f'Incepted bplist extractions in knowlwdgeC.db executing.')
iOSversion = versionf
supportediOS = ['11', '12', '13']
if iOSversion not in supportediOS:
logfunc ("Unsupported version"+iOSversion)
return()
extension = '.bplist'
dump = True
#create directories
outpath = reportfolderbase+'KnowledgeC/'
try:
os.mkdir(outpath)
os.mkdir(outpath+"clean/")
os.mkdir(outpath+"/dirty")
except OSError:
logfunc("Error making directories")
#connect sqlite databases
db = sqlite3.connect(filefound[0])
cursor = db.cursor()
#variable initializations
dirtcount = 0
cleancount = 0
intentc = {}
intentv = {}
cursor.execute('''
SELECT
Z_PK,
Z_DKINTENTMETADATAKEY__SERIALIZEDINTERACTION,
Z_DKINTENTMETADATAKEY__INTENTCLASS,
Z_DKINTENTMETADATAKEY__INTENTVERB
FROM ZSTRUCTUREDMETADATA
WHERE Z_DKINTENTMETADATAKEY__SERIALIZEDINTERACTION is not null
''')
all_rows = cursor.fetchall()
for row in all_rows:
pkv = str(row[0])
pkvplist = pkv+extension
f = row[1]
intentclass = str(row[2])
intententverb = str(row[3])
output_file = open(outpath+'/dirty/D_Z_PK'+pkvplist, 'wb') #export dirty from DB
output_file.write(f)
output_file.close()
g = open(outpath+'/dirty/D_Z_PK'+pkvplist, 'rb')
plistg = ccl_bplist.load(g)
if (iOSversion == '11'):
ns_keyed_archiver_obj = ccl_bplist.deserialise_NsKeyedArchiver(plistg)
newbytearray = ns_keyed_archiver_obj
if (iOSversion == '12'):
ns_keyed_archiver_objg = ccl_bplist.deserialise_NsKeyedArchiver(plistg)
newbytearray = (ns_keyed_archiver_objg["NS.data"])
if (iOSversion == '13'):
ns_keyed_archiver_objg = ccl_bplist.deserialise_NsKeyedArchiver(plistg)
newbytearray = (ns_keyed_archiver_objg["NS.data"])
dirtcount = dirtcount+1
binfile = open(outpath+'/clean/C_Z_PK'+pkvplist, 'wb')
binfile.write(newbytearray)
binfile.close()
#add to dictionaries
intentc['C_Z_PK'+pkvplist] = intentclass
intentv['C_Z_PK'+pkvplist] = intententverb
cleancount = cleancount+1
h = open(outpath+'/StrucMetadata.html', 'w')
h.write('<html><body>')
h.write('<h2>iOS ' + iOSversion + ' - KnowledgeC ZSTRUCTUREDMETADATA bplist report</h2>')
h.write ('<style> table, th, td {border: 1px solid black; border-collapse: collapse;} tr:nth-child(even) {background-color: #f2f2f2;} </style>')
h.write('<br/>')
for filename in glob.glob(outpath+'/clean/*'+extension):
p = open(filename, 'rb')
cfilename = os.path.basename(filename)
plist = ccl_bplist.load(p)
ns_keyed_archiver_obj = ccl_bplist.deserialise_NsKeyedArchiver(plist, parse_whole_structure=True)#deserialize clean
#Get dictionary values
A = intentc.get(cfilename)
B = intentv.get(cfilename)
if A is None:
A = 'No value'
if B is None:
A = 'No value'
#logfunc some values from clean bplist
if iOSversion == '13':
NSdata = (ns_keyed_archiver_obj['root']['intent']['backingStore']['bytes'])
else:
NSdata = (ns_keyed_archiver_obj["root"]["intent"]["backingStore"]["data"]["NS.data"])
parsedNSData = ""
#Default true
if dump == True:
nsdata_file = outpath+'/clean/'+cfilename+'_nsdata.bin'
binfile = open(nsdata_file, 'wb')
if iOSversion == '13':
binfile.write(ns_keyed_archiver_obj['root']['intent']['backingStore']['bytes'])
else:
binfile.write(ns_keyed_archiver_obj["root"]["intent"]["backingStore"]["data"]["NS.data"])
binfile.close()
messages = ParseProto(nsdata_file)
messages_json_dump = json.dumps(messages, indent=4, sort_keys=True, ensure_ascii=False)
parsedNSData = str(messages_json_dump).encode(encoding='UTF-8',errors='ignore')
NSstartDate = ccl_bplist.convert_NSDate((ns_keyed_archiver_obj["root"]["dateInterval"]["NS.startDate"]))
NSendDate = ccl_bplist.convert_NSDate((ns_keyed_archiver_obj["root"]["dateInterval"]["NS.endDate"]))
NSduration = ns_keyed_archiver_obj["root"]["dateInterval"]["NS.duration"]
Siri = ns_keyed_archiver_obj["root"]["_donatedBySiri"]
h.write(cfilename)
h.write('<br />')
h.write('Intent Class: '+str(A))
h.write('<br />')
h.write('Intent Verb: '+str(B))
h.write('<br />')
h.write('<table>')
h.write('<tr>')
h.write('<th>Data type</th>')
h.write('<th>Value</th>')
h.write('</tr>')
#Donated by Siri
h.write('<tr>')
h.write('<td>Siri</td>')
h.write('<td>'+str(Siri)+'</td>')
h.write('</tr>')
#NSstartDate
h.write('<tr>')
h.write('<td>NSstartDate</td>')
h.write('<td>'+str(NSstartDate)+' Z</td>')
h.write('</tr>')
#NSsendDate
h.write('<tr>')
h.write('<td>NSendDate</td>')
h.write('<td>'+str(NSendDate)+' Z</td>')
h.write('</tr>')
#NSduration
h.write('<tr>')
h.write('<td>NSduration</td>')
h.write('<td>'+str(NSduration)+'</td>')
h.write('</tr>')
#NSdata
h.write('<tr>')
h.write('<td>NSdata</td>')
h.write('<td>'+str(NSdata)+'</td>')
h.write('</tr>')
#NSdata better formatting
if parsedNSData:
h.write('<tr>')
h.write('<td>NSdata - Protobuf Decoded</td>')
h.write('<td><pre id=\"json\">'+str(parsedNSData).replace('\\n', '<br>')+'</pre></td>')
h.write('</tr>')
else:
#This will only run if -nd is used
h.write('<tr>')
h.write('<td>NSdata - Protobuf</td>')
h.write('<td>'+str(NSdata).replace('\\n', '<br>')+'</td>')
h.write('</tr>')
h.write('<table>')
h.write('<br />')
#logfunc(NSstartDate)
#logfunc(NSendDate)
#logfunc(NSduration)
#logfunc(NSdata)
#logfunc('')
logfunc("")
logfunc("iOS - KnowledgeC ZSTRUCTUREDMETADATA bplist extractor")
logfunc("By: @phillmoore & @AlexisBrignoni")
logfunc("thinkdfir.com & abrignoni.com")
logfunc("")
logfunc("Bplists from the Z_DKINTENTMETADATAKEY__SERIALIZEDINTERACTION field.")
logfunc("Exported bplists (dirty): "+str(dirtcount))
logfunc("Exported bplists (clean): "+str(cleancount))
logfunc("")
logfunc(f'Triage report completed.')
logfunc('Incepted bplist extractions in knowlwdgeC.db completed')
logfunc(f'KnowledgeC.db App Usage executing')
#outpath = reportfolderbase+'KnowledgeC App Use/'
#connect sqlite databases
db = sqlite3.connect(filefound[0])
cursor = db.cursor()
cursor.execute('''
SELECT
datetime(ZOBJECT.ZCREATIONDATE+978307200,'UNIXEPOCH', 'LOCALTIME') as "ENTRY CREATION",
CASE ZOBJECT.ZSTARTDAYOFWEEK
WHEN "1" THEN "Sunday"
WHEN "2" THEN "Monday"
WHEN "3" THEN "Tuesday"
WHEN "4" THEN "Wednesday"
WHEN "5" THEN "Thursday"
WHEN "6" THEN "Friday"
WHEN "7" THEN "Saturday"
END "DAY OF WEEK",
ZOBJECT.ZSECONDSFROMGMT/3600 AS "GMT OFFSET",
datetime(ZOBJECT.ZSTARTDATE+978307200,'UNIXEPOCH', 'LOCALTIME') as "START",
datetime(ZOBJECT.ZENDDATE+978307200,'UNIXEPOCH', 'LOCALTIME') as "END",
(ZOBJECT.ZENDDATE-ZOBJECT.ZSTARTDATE) as "USAGE IN SECONDS",
ZOBJECT.ZSTREAMNAME,
ZOBJECT.ZVALUESTRING
FROM ZOBJECT
WHERE ZSTREAMNAME IS "/app/inFocus"
ORDER BY "START" ''')
all_rows = cursor.fetchall()
usageentries = len(all_rows)
with open(reportfolderbase+'KnowledgeC/App Usage.html', 'w', encoding='utf8') as f:
f.write('<html><body>')
f.write('<h2>iOS ' + iOSversion + ' - KnowledgeC App Usage report</h2>')
f.write(f'KnowledgeC App Usage entries: {usageentries}<br>')
f.write(f'KnowledgeC located at: {filefound[0]}<br>')
f.write('<style> table, th, td {border: 1px solid black; border-collapse: collapse;} tr:nth-child(even) {background-color: #f2f2f2;} </style>')
f.write('<br/>')
f.write('')
f.write(f'<table>')
f.write(f'<tr><td>Entry Creation</td><td>Day of Week</td><td>GMT Offset</td><td>Start</td><td>End</td><td>Usage in Seconds</td><td>ZSTREAMNAME</td><td>ZVALUESTRING</td></tr>')
for row in all_rows:
ec = row[0]
dw = row[1]
go = row[2]
st = row[3]
en = row[4]
us = row[5]
zs = row[6]
zv = row[7]
f.write(f'<tr><td>{ec}</td><td>{dw}</td><td>{go}</td><td>{st}</td><td>{en}</td><td>{us}</td><td>{zs}</td><td>{zv}</td></tr>')
f.write(f'</table></body></html>')
logfunc(f'KnowledgeC App Usage completed')
logfunc(f'KnowledgeC App Activity Executing')
#connect sqlite databases
db = sqlite3.connect(filefound[0])
cursor = db.cursor()
cursor.execute('''
SELECT
datetime(ZOBJECT.ZCREATIONDATE+978307200,'UNIXEPOCH', 'LOCALTIME') as "ENTRY CREATION",
CASE ZOBJECT.ZSTARTDAYOFWEEK
WHEN "1" THEN "Sunday"
WHEN "2" THEN "Monday"
WHEN "3" THEN "Tuesday"
WHEN "4" THEN "Wednesday"
WHEN "5" THEN "Thursday"
WHEN "6" THEN "Friday"
WHEN "7" THEN "Saturday"
END "DAY OF WEEK",
datetime(ZOBJECT.ZSTARTDATE+978307200,'UNIXEPOCH', 'LOCALTIME') as "START",
datetime(ZOBJECT.ZENDDATE+978307200,'UNIXEPOCH', 'LOCALTIME') as "END",
ZOBJECT.ZSTREAMNAME,
ZOBJECT.ZVALUESTRING,
ZSTRUCTUREDMETADATA.Z_DKAPPLICATIONACTIVITYMETADATAKEY__ACTIVITYTYPE AS "ACTIVITY TYPE",
ZSTRUCTUREDMETADATA.Z_DKAPPLICATIONACTIVITYMETADATAKEY__TITLE as "TITLE",
datetime(ZSTRUCTUREDMETADATA.Z_DKAPPLICATIONACTIVITYMETADATAKEY__EXPIRATIONDATE+978307200,'UNIXEPOCH', 'LOCALTIME') as "EXPIRATION DATE",
ZSTRUCTUREDMETADATA.Z_DKAPPLICATIONACTIVITYMETADATAKEY__ITEMRELATEDCONTENTURL as "CONTENT URL",
datetime(ZSTRUCTUREDMETADATA.ZCOM_APPLE_CALENDARUIKIT_USERACTIVITY_DATE+978307200,'UNIXEPOCH', 'LOCALTIME') as "CALENDAR DATE",
datetime(ZSTRUCTUREDMETADATA.ZCOM_APPLE_CALENDARUIKIT_USERACTIVITY_ENDDATE+978307200,'UNIXEPOCH', 'LOCALTIME') as "CALENDAR END DATE"
FROM ZOBJECT
left join ZSTRUCTUREDMETADATA on ZOBJECT.ZSTRUCTUREDMETADATA = ZSTRUCTUREDMETADATA.Z_PK
left join ZSOURCE on ZOBJECT.ZSOURCE = ZSOURCE.Z_PK
WHERE ZSTREAMNAME is "/app/activity"
ORDER BY "ENTRY CREATION"''')
all_rows = cursor.fetchall()
usageentries = len(all_rows)
with open(reportfolderbase+'KnowledgeC/App Activity.html', 'w', encoding='utf8') as f:
f.write('<html><body>')
f.write('<h2>iOS ' + iOSversion + ' - KnowledgeC App Activity report</h2>')
f.write(f'KnowledgeC App Activity entries: {usageentries}<br>')
f.write(f'KnowledgeC located at: {filefound[0]}<br>')
f.write('<style> table, th, td {border: 1px solid black; border-collapse: collapse;} tr:nth-child(even) {background-color: #f2f2f2;} </style>')
f.write('<br/>')
f.write('')
f.write(f'<table>')
f.write(f'<tr><td>Entry Creation</td><td>Day of Week</td><td>Start</td><td>End</td><td>ZSTREAMNAME</td><td>ZVALUESTRING</td><td>Activity Type</td><td>Title</td><td>Expiration Date</td><td>Content URL</td><td>Calendar Date</td><td>Calendar End Date</td></tr>')
for row in all_rows:
ec = row[0]
dw = row[1]
st = row[2]
en = row[3]
zs = row[4]
zv = row[5]
tl = row[6]
ed = row[7]
cu = row[8]
cd = row[9]
ce = row[10]
ced = row[11]
f.write(f'<tr><td>{ec}</td><td>{dw}</td><td>{st}</td><td>{en}</td><td>{zs}</td><td>{zv}</td><td>{tl}</td><td>{ed}</td><td>{cu}</td><td>{cd}</td><td>{ce}</td><td>{ced}</td></tr>')
f.write(f'</table></body></html>')
logfunc(f'KnowledgeC App Activity completed')
logfunc(f'KnowledgeC App in Focus executing')
db = sqlite3.connect(filefound[0])
cursor = db.cursor()
cursor.execute('''
SELECT
ZOBJECT.ZVALUESTRING AS "BUNDLE ID",
(ZOBJECT.ZENDDATE-ZOBJECT.ZSTARTDATE) as "USAGE IN SECONDS",
CASE ZOBJECT.ZSTARTDAYOFWEEK
WHEN "1" THEN "Sunday"
WHEN "2" THEN "Monday"
WHEN "3" THEN "Tuesday"
WHEN "4" THEN "Wednesday"
WHEN "5" THEN "Thursday"
WHEN "6" THEN "Friday"
WHEN "7" THEN "Saturday"
END "DAY OF WEEK",
ZOBJECT.ZSECONDSFROMGMT/3600 AS "GMT OFFSET",
DATETIME(ZOBJECT.ZSTARTDATE+978307200,'UNIXEPOCH') as "START",
DATETIME(ZOBJECT.ZENDDATE+978307200,'UNIXEPOCH') as "END",
DATETIME(ZOBJECT.ZCREATIONDATE+978307200,'UNIXEPOCH') as "ENTRY CREATION",
ZOBJECT.Z_PK AS "ZOBJECT TABLE ID"
FROM ZOBJECT
WHERE ZSTREAMNAME IS "/app/inFocus"''')
all_rows = cursor.fetchall()
usageentries = len(all_rows)
with open(reportfolderbase+'KnowledgeC/App in Focus.html', 'w', encoding='utf8') as f:
f.write('<html><body>')
f.write('<h2>iOS ' + iOSversion + ' - KnowledgeC App App in Focus report</h2>')
f.write(f'KnowledgeC App in Focus entries: {usageentries}<br>')
f.write(f'KnowledgeC located at: {filefound[0]}<br>')
f.write('<style> table, th, td {border: 1px solid black; border-collapse: collapse;} tr:nth-child(even) {background-color: #f2f2f2;} </style>')
f.write('<br/>')
f.write('')
f.write(f'<table>')
f.write(f'<tr><td>Bundle ID</td><td>Usage in Seconds</td><td>Day of the Week</td><td>GMT Offset</td><td>Start</td><td>End</td><td>Entry Creation</td><td>ZOBJECT Table ID</td></tr>')
for row in all_rows:
f.write(f'<tr><td>{row[0]}</td><td>{row[1]}</td><td>{row[2]}</td><td>{row[3]}</td><td>{row[4]}</td><td>{row[5]}</td><td>{row[6]}</td><td>{row[7]}</td></tr>')
f.write(f'</table></body></html>')
logfunc(f'KnowledgeC App in Focus completed')
logfunc(f'KnowledgeC App Battery Level executing')
cursor.execute('''
SELECT
ZOBJECT.ZVALUEDOUBLE as "BATTERY LEVEL",
(ZOBJECT.ZENDDATE - ZOBJECT.ZSTARTDATE) AS "USAGE IN SECONDS",
CASE ZOBJECT.ZSTARTDAYOFWEEK
WHEN "1" THEN "Sunday"
WHEN "2" THEN "Monday"
WHEN "3" THEN "Tuesday"
WHEN "4" THEN "Wednesday"
WHEN "5" THEN "Thursday"
WHEN "6" THEN "Friday"
WHEN "7" THEN "Saturday"
END "DAY OF WEEK",
ZOBJECT.ZSECONDSFROMGMT/3600 AS "GMT OFFSET",
DATETIME(ZOBJECT.ZSTARTDATE+978307200,'UNIXEPOCH') as "START",
DATETIME(ZOBJECT.ZENDDATE+978307200,'UNIXEPOCH') as "END",
DATETIME(ZOBJECT.ZCREATIONDATE+978307200,'UNIXEPOCH') as "ENTRY CREATION",
ZOBJECT.Z_PK AS "ZOBJECT TABLE ID"
FROM
ZOBJECT
LEFT JOIN
ZSTRUCTUREDMETADATA
ON ZOBJECT.ZSTRUCTUREDMETADATA = ZSTRUCTUREDMETADATA.Z_PK
LEFT JOIN
ZSOURCE
ON ZOBJECT.ZSOURCE = ZSOURCE.Z_PK
WHERE
ZSTREAMNAME LIKE "/device/BatteryPercentage"
''')
all_rows = cursor.fetchall()
usageentries = len(all_rows)
with open(reportfolderbase+'KnowledgeC/Battery Level.html', 'w', encoding='utf8') as f:
f.write('<html><body>')
f.write('<h2>KnowledgeC Battery Level report</h2>')
f.write(f'KnowledgeC Battery Level entries: {usageentries}<br>')
f.write(f'KnowledgeC Battery Level located at: {filefound[0]}<br>')
f.write('<style> table, th, td {border: 1px solid black; border-collapse: collapse;} tr:nth-child(even) {background-color: #f2f2f2;} </style>')
f.write('<br/>')
f.write('')
f.write(f'<table>')
f.write(f'<tr><td>Battery Level</td><td>Usage in Seconds</td><td>Day of the Week</td><td>GMT Offset</td><td>Start</td><td>End</td><td>Entry Creation</td><td>ZOBJECT Table ID</td></tr>')
for row in all_rows:
f.write(f'<tr><td>{row[0]}</td><td>{row[1]}</td><td>{row[2]}</td><td>{row[3]}</td><td>{row[4]}</td><td>{row[5]}</td><td>{row[6]}</td><td>{row[7]}</td></tr>')
f.write(f'</table></body></html>')
logfunc(f'KnowledgeC App Battery Level completed')
logfunc(f'KnowledgeC Apps Installed executing')
cursor.execute('''
SELECT
ZOBJECT.ZVALUESTRING AS "BUNDLE ID",
CASE ZOBJECT.ZSTARTDAYOFWEEK