-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathforensics.py
More file actions
2778 lines (1757 loc) · 84 KB
/
forensics.py
File metadata and controls
2778 lines (1757 loc) · 84 KB
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
'''
This is my old forensics project for iOS.
- Piotr Bania / https://piotrbania.com
# iOS Backup Report Generator
This tool generates detailed reports from iOS backups, with support for both unencrypted and encrypted backups (requires password for encrypted ones). It produces responsive reports in web format, as well as PDF or raw JSON files for flexibility. The tool processes data locally, ensuring that your private information remains on your computer.
## Features
The generated report includes the following data extracted from the iOS backup:
- Device details
- Address book contacts
- Calendar events
- WiFi configurations
- Cloud notes
- SMS and text message history
- Stored cookies
- WhatsApp chat data
- File metadata
## System Requirements
- Compatible with **Windows 7/8/10 64-bit**.
- Requires a **modern web browser**.
- Backups can be created using **iTunes** or **iRepair**.
- Supports iOS versions **11, 12, and 13**.
'''
import sqlite3
import plistlib
import re
import hashlib
import os
import shutil
import sys
import json
import zipfile
import base64
import zlib
import time
import platform
import linecache
import binascii
import random
import ctypes
import cffi
from pprint import pprint
from datetime import datetime
from struct import unpack
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
from io import BytesIO
from pathlib import Path, PureWindowsPath
import urllib.request as urllib
import warnings
warnings.filterwarnings("ignore",category=DeprecationWarning)
import pkg_resources
import subprocess
required = {'Crypto', 'fastpbkdf2', 'biplist'}
installed = {pkg.key for pkg in pkg_resources.working_set}
missing = required - installed
# to install fastpbkdf2 on windows you need to
# 1) install https://slproweb.com/download/Win64OpenSSL-1_1_1g.exe
# 2) copy include to E:\Python3\
# 3) copy lib to E:\Python3\libs
if missing:
python = sys.executable
print("- Warning: some packages are missing: " + ', '.join(missing))
print("+ Trying to install those packages with pip, if it fails please do this manually")
#subprocess.check_call([python, '-m', 'pip', 'install', *missing])
#subprocess.check_call(["cmd.exe", "/C", "echo %PATH%"], env=my_env)
#sys.exit(0)
#import Cryptodome # pip install pycryptodomex or pip install pycryptodome
from Cryptodome.Cipher import AES # pip install pycryptodomex or pip install pycryptodome
if sys.version[0] == "3":
unicode = str
__author__ = 'Piotr Bania'
__version__ = '1.0.0'
null = 0
PBEGIN = ''
SEP = '/'
DB_VAR_MARKER = 'DB_iREPAIR__' # just some random string for filteirng
DECYRPTED_PREFIX = ".DECRYPTED"
IS_DB_ENCRYPTED = False
hLib = None
TESTFASTPBKDF2_DLL_PATH = "testfastpbkdf2_python64.dll"
if platform.system() == 'Windows':
#print("+ Running on Windows")
SEP = '\\'
PBEGIN = '\\\\?\\'
# this is for windows only
#hDll = ctypes.WinDLL(TESTFASTPBKDF2_DLL_PATH)
ffi = cffi.FFI()
ffi.cdef("""
void fastpbkdf2_hmac_sha1(const uint8_t *, size_t,
const uint8_t *, size_t,
uint32_t,
uint8_t *, size_t);
void fastpbkdf2_hmac_sha256(const uint8_t *, size_t,
const uint8_t *, size_t,
uint32_t,
uint8_t *, size_t);
void fastpbkdf2_hmac_sha512(const uint8_t *, size_t,
const uint8_t *, size_t,
uint32_t,
uint8_t *, size_t);
""")
hLib = ffi.dlopen(TESTFASTPBKDF2_DLL_PATH)
algorithm = {
"sha1": (hLib.fastpbkdf2_hmac_sha1, 20),
"sha256": (hLib.fastpbkdf2_hmac_sha256, 32),
"sha512": (hLib.fastpbkdf2_hmac_sha512, 64),
}
def pbkdf2_hmac(name, password, salt, rounds, dklen=None):
print('+ Using Password = %s / len = %d' % (str(password), len(password) ))
if not isinstance(password, bytes):
password = password.encode('ascii')
try:
if name not in ["sha1", "sha256", "sha512"]:
raise ValueError("unsupported hash type")
out_length = dklen or algorithm[name][1]
out = ffi.new("uint8_t[]", out_length)
algorithm[name][0](
password, len(password),
salt, len(salt),
rounds,
out, out_length
)
return ffi.buffer(out)[:]
except:
PrintException()
return False
db_files = [ 'KeychainDomain-keychain-backup.plist', # 51a4616e576dd33cd2abadfea874eb8ff246bf0e
'HomeDomain-Library/Safari/History.plist',
'HomeDomain-Library/Preferences/com.apple.springboard.plist',
'HomeDomain-Library/SMS/sms.db', # 3d0d7e5fb2ce288813306e4d4636395e047a3d28
'HomeDomain-Library/AddressBook/AddressBook.sqlitedb', # 31bb7ba8914766d4ba40d6dfb6113c8b614be442
'HomeDomain-Library/AddressBook/AddressBookImages.sqlitedb', # cd6702cea29fe89cf280a76794405adb17f9a0ee
'WirelessDomain-Library/CallHistory/call_history.db', # 2b2b0084a1bc3a5ac8c27afdf14afb42c61a19ca
'HomeDomain-Library/Notes/notes.sqlite', # ca3bc056d4da0bbf88b5fb3be254f3b7147e639c
'HomeDomain-Library/Calendar/Calendar.sqlitedb', # 2041457d5fe04d39d0ab481178355df6781e6858
'HomeDomain-Library/Voicemail/voicemail.db', # 992df473bbb9e132f4b3b6e4d33f72171e97bc7a
'CameraRollDomain-Media/PhotoData/Photos.sqlite', # 12b144c0bd44f2b3dffd9186d3f9c05b917cee25
'MediaDomain-Media/Recordings/Recordings.db', # 303e04f2a5b473c5ca2127d65365db4c3e055c05
'HomeDomain-Library/Safari/Bookmarks.db']
db_SMS = 'HomeDomain-Library/SMS/sms.db'
db_AddressBook = 'HomeDomain-Library/AddressBook/AddressBook.sqlitedb'
db_Calendar = 'HomeDomain-Library/Calendar/Calendar.sqlitedb'
db_Notes = 'HomeDomain-Library/Notes/notes.sqlite'
db_CloudNotes = 'AppDomainGroup-group.com.apple.notes-NoteStore.sqlite'
db_CallHistory = 'WirelessDomain-Library/CallHistory/call_history.db'
db_WhatsApp = 'AppDomainGroup-group.net.whatsapp.WhatsApp.shared-ChatStorage.sqlite'
bin_cookies = 'AppDomain-com.apple.mobilesafari-Library/Cookies/Cookies.binarycookies'
plist_WiFi = 'SystemPreferencesDomain-SystemConfiguration/com.apple.wifi.plist'
db_AddressBook_file = 0
db_SMS_file = 0
db_Calendar_file = 0
db_Notes_file = 0
db_CloudNotes_file = 0
db_WhatsApp_file = 0
plist_WiFi_file = 0
bin_cookies_file = 0
dateEpoch2001 = lambda ts: datetime.utcfromtimestamp(978307200 + ts)
DEBUG_MODE = 1
#
#
# ENCRYPTED BACKUPs SUPPORT
#
#
# this section is mostly copied from parts of iphone-dataprotection
# http://code.google.com/p/iphone-dataprotection/
import struct
CLASSKEY_TAGS = [b"CLAS", b"WRAP", b"WPKY", b"KTYP", b"PBKY"]
KEYBAG_TYPES = ["System", "Backup", "Escrow", "OTA (icloud)"]
KEY_TYPES = ["AES", "Curve25519"]
PROTECTION_CLASSES={
1:"NSFileProtectionComplete",
2:"NSFileProtectionCompleteUnlessOpen",
3:"NSFileProtectionCompleteUntilFirstUserAuthentication",
4:"NSFileProtectionNone",
5:"NSFileProtectionRecovery?",
6: "kSecAttrAccessibleWhenUnlocked",
7: "kSecAttrAccessibleAfterFirstUnlock",
8: "kSecAttrAccessibleAlways",
9: "kSecAttrAccessibleWhenUnlockedThisDeviceOnly",
10: "kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly",
11: "kSecAttrAccessibleAlwaysThisDeviceOnly"
}
WRAP_DEVICE = 1
WRAP_PASSCODE = 2
ANONYMIZE_OUTPUT = 0
class Keybag(object):
def __init__(self, data):
self.type = None
self.uuid = None
self.wrap = None
self.deviceKey = None
self.attrs = {}
self.classKeys = {}
self.KeyBagKeys = None #DATASIGN blob
self.parseBinaryBlob(data)
def parseBinaryBlob(self, data):
currentClassKey = None
for tag, data in loopTLVBlocks(data):
#print("DEBUG: tag=%s" % tag)
if len(data) == 4:
data = struct.unpack(">L", data)[0]
if tag == b"TYPE":
self.type = data
if self.type > 3:
print("FAIL: keybag type > 3 : %d" % self.type)
elif tag == b"UUID" and self.uuid is None:
self.uuid = data
elif tag == b"WRAP" and self.wrap is None:
self.wrap = data
elif tag == b"UUID":
if currentClassKey:
self.classKeys[currentClassKey[b"CLAS"]] = currentClassKey
currentClassKey = {b"UUID": data}
elif tag in CLASSKEY_TAGS:
currentClassKey[tag] = data
else:
self.attrs[tag] = data
if currentClassKey:
self.classKeys[currentClassKey[b"CLAS"]] = currentClassKey
def unlockWithPasscode(self, passcode, passcode_key=None):
global hLib
try:
if passcode_key is None:
passcode1 = pbkdf2_hmac('sha256', passcode,
self.attrs[b"DPSL"],
self.attrs[b"DPIC"], 32)
passcode_key = pbkdf2_hmac('sha1', passcode1,
self.attrs[b"SALT"],
self.attrs[b"ITER"], 32)
print('== Passcode key')
print(anonymize(binascii.hexlify(passcode_key)))
#print('== Pasccode key ascii: ' + passcode_key.encode('utf-8'))
for classkey in self.classKeys.values():
if b"WPKY" not in classkey:
continue
k = classkey[b"WPKY"]
if classkey[b"WRAP"] & WRAP_PASSCODE:
k = AESUnwrap(passcode_key, classkey[b"WPKY"])
if not k:
return False
classkey[b"KEY"] = k
except:
PrintException()
return True
def unwrapKeyForClass(self, protection_class, persistent_key):
ck = self.classKeys[protection_class][b"KEY"]
if len(persistent_key) != 0x28:
raise Exception("Invalid key length")
return AESUnwrap(ck, persistent_key)
def printClassKeys(self):
try:
print("== Keybag")
print("Keybag type: %d" % self.type)
print("Keybag type: %s keybag (%d)" % (KEYBAG_TYPES[self.type], self.type))
print("Keybag version: %d" % self.attrs[b"VERS"])
print("Keybag UUID: %s" % anonymize(binascii.hexlify(self.uuid, ' ')))
print("-"*209)
print("".join(["Class".ljust(53),
"WRAP".ljust(5),
"Type".ljust(11),
"Key".ljust(65),
"WPKY".ljust(65),
"Public key"]))
print("-"*208)
for k, ck in self.classKeys.items():
if k == 6:print("")
__WRAP = ck.get(b"WRAP", "")
__KTYP = ck.get(b"KTYP", 0)
__KEY = ck.get(b"KEY", b"")
__WPKY = ck.get(b"WPKY", b"")
#print("__KTYP = %d" % __KTYP)
#print("__KEY = " + str(binascii.hexlify(__KEY)))
#print("__WPKY = " + str(binascii.hexlify(__WPKY)))
print("".join(
[PROTECTION_CLASSES.get(k).ljust(53),
str(__WRAP).ljust(5),
KEY_TYPES[__KTYP].ljust(11),
anonymize(str(binascii.hexlify(__KEY))).ljust(65),
anonymize(str(binascii.hexlify(__WPKY))).ljust(65),
]))
print()
except:
PrintException()
def loopTLVBlocks(blob):
i = 0
while i + 8 <= len(blob):
tag = blob[i:i+4]
length = struct.unpack(">L",blob[i+4:i+8])[0]
data = blob[i+8:i+8+length]
yield (tag,data)
i += 8 + length
def unpack64bit(s):
return struct.unpack(">Q",s)[0]
def pack64bit(s):
out = struct.pack(">Q",s)
#pprint(out)
return out
def AESUnwrap(kek, wrapped):
try:
C = []
for i in range(len(wrapped) // 8):
C.append(unpack64bit(wrapped[i*8:i*8+8]))
n = len(C) - 1
R = [0] * (n+1)
A = C[0]
for i in range(1, n+1):
R[i] = C[i]
for j in reversed(range(0,6)):
for i in reversed(range(1,n+1)):
todec = pack64bit(A ^ (n*j+i))
todec += pack64bit(R[i])
#B = Cryptodome.Cipher.AES.new(kek).decrypt(todec)
B = AES.new(kek, AES.MODE_ECB).decrypt(todec)
A = unpack64bit(B[:8])
R[i] = unpack64bit(B[8:])
if A != 0xa6a6a6a6a6a6a6a6:
return None
res = b"".join(map(pack64bit, R[1:]))
return res
except:
PrintException()
return False
ZEROIV = b"\x00"*16
def AESdecryptCBC(data, key, iv=ZEROIV, padding=False):
if len(data) % 16:
print("- Error: AESdecryptCBC: data length not /16, truncating")
data = data[0:(len(data)/16) * 16]
try:
#data = Crypto.Cipher.AES.new(key, Crypto.Cipher.AES.MODE_CBC, iv).decrypt(data)
#pprint(ZEROIV)
data = AES.new(key, AES.MODE_CBC, iv).decrypt(data)
if padding:
return removePadding(16, data)
#print("+ AESdecryptCBC returned=")
#pprint(data)
return data
except:
PrintException()
return False
##
# here are some utility functions, one making sure I don’t leak my
# secret keys when posting the output on Stack Exchange
anon_random = random.Random(0)
memo = {}
def anonymize(s):
global anon_random, memo
if ANONYMIZE_OUTPUT:
if s in memo:
return memo[s]
possible_alphabets = [
string.digits,
string.digits + 'abcdef',
string.letters,
"".join(chr(x) for x in range(0, 256)),
]
for a in possible_alphabets:
if all(c in a for c in s):
alphabet = a
break
ret = "".join([anon_random.choice(alphabet) for i in range(len(s))])
memo[s] = ret
return ret
else:
return s
def wrap(s, width=78):
"Return a width-wrapped repr(s)-like string without breaking on \’s"
s = repr(s)
quote = s[0]
s = s[1:-1]
ret = []
while len(s):
i = s.rfind('\\', 0, width)
if i <= width - 4: # "\x??" is four characters
i = width
ret.append(s[:i])
s = s[i:]
return '\n'.join("%s%s%s" % (quote, line ,quote) for line in ret)
def removePadding(data, blocksize=16):
n = int(data[-1]) # RFC 1423: last byte contains number of padding bytes.
if n > blocksize or n > len(data):
raise Exception('Invalid CBC padding')
return data[:-n]
def readBackupEncrypted(BackupPath, OutPath, OutPathReport, Password):
ManifestPlistPath = pathConvert(os.path.join(BackupPath, 'Manifest.plist'))
dbPath = pathConvert(os.path.join(BackupPath, 'Manifest.db'))
outJSON = pathConvert(os.path.join(OutPathReport, 'Info.json'))
dbDecryptedPath = pathConvert(os.path.join(BackupPath, 'Manifest.db' + DECYRPTED_PREFIX))
try:
with open(ManifestPlistPath, 'rb') as f:
info = plistlib.load(f)
IsEncrypted = info.get('IsEncrypted')
BackupKeyBag = info.get('BackupKeyBag')
BackupKeyBagAsc = str(binascii.hexlify(BackupKeyBag, ' '))
ManifestKey = info.get('ManifestKey')
ManifestKeyAsc = str(binascii.hexlify(ManifestKey, ' '))
keybag = Keybag(BackupKeyBag)
keybag.printClassKeys()
passcode_key = None
if not keybag.unlockWithPasscode(Password, passcode_key):
print("- Error: could not unlock keybag, bad password?")
return False
keybag.printClassKeys()
## Decrypt metadata DB
ManifestKeyG = ManifestKey[4:]
with open(dbPath, 'rb') as db:
encrypted_db = db.read()
manifest_class = struct.unpack('<l', ManifestKey[:4])[0]
key = keybag.unwrapKeyForClass(manifest_class, ManifestKeyG)
decrypted_manifest = AESdecryptCBC(encrypted_db, key)
print("+ Storing decrypted manifest to \"%s\" " % dbDecryptedPath)
with open(dbDecryptedPath, 'wb') as f:
f.write(decrypted_manifest)
# decrypt them files
print("+ Decrypting all files")
try:
conn = sqlite3.connect(dbDecryptedPath)
c = conn.cursor()
# get all files
files = c.execute('SELECT fileID, relativePath, domain, file from Files WHERE flags IS 1').fetchall()
for item in files:
fileID, relativePath, domain, file_bplist = item
plist = plistlib.loads(file_bplist)
FileData = plist['$objects'][plist['$top']['root']]
FileSize = FileData['Size']
EncryptionKey = plist['$objects'][FileData['EncryptionKey']]['NS.data'][4:]
ProtectionClass = FileData['ProtectionClass']
# decrypt this file
EncryptedFilePath = pathConvert(os.path.join(BackupPath, fileID[:2], fileID))
DecryptedFilePath = pathConvert(os.path.join(BackupPath, fileID[:2], fileID + DECYRPTED_PREFIX))
with open(EncryptedFilePath, 'rb') as infile:
data = infile.read()
key = keybag.unwrapKeyForClass(ProtectionClass, EncryptionKey)
decrypted_data = AESdecryptCBC(data, key) #[:FileSize] # skip the padding
# now decrypted_data should be padded to FileSize however if we do that
# some sqlite databases (ie. notes) will be damaged, ugh dont skip the pad for now
#if len(decrypted_data) != FileSize:
#print("Size mismatch len=%d vs FileSize=%d" % (len(decrypted_data), FileSize))
#decrypted_data = AESdecryptCBC(data, key)[:FileSize]
decrypted_data = removePadding(decrypted_data)
# write decrypted file
with open(DecryptedFilePath, 'wb') as outfile:
outfile.write(decrypted_data)
#print("EncryptedFilePath = %s / RelativePath = %s / EncryptionKey = %s / ProtectionClass = %d" % (EncryptedFilePath, relativePath, EncryptionKey, ProtectionClass))
#print("Decrypted to = %s - filesize: %d" % (DecryptedFilePath, os.path.getsize(DecryptedFilePath)))
#pprint(FileData)
#sys.exit(0)
except:
print('! Error: opening backup database - path = \"%s\"' % dbPath)
print('! Error: please make sure this DB is not encrypted')
PrintException()
return False
print("Done")
except:
print('! Error: opening Manifest.plist - path = \"%s\"' % ManifestPlistPath)
PrintException()
return False
return True
#
#
# END OF ENCRYPTION/DECRYPTION SUPPORT
#
#
def PrintException():
if DEBUG_MODE == 0:
return 0
exc_type, exc_obj, tb = sys.exc_info()
f = tb.tb_frame
lineno = tb.tb_lineno
filename = f.f_code.co_filename
linecache.checkcache(filename)
line = linecache.getline(filename, lineno, f.f_globals)
print('- Error: EXCEPTION IN ({}, LINE {} "{}"): {}'.format(filename, lineno, line.strip(), exc_obj))
def isset(var):
try: var
except: return False
else: return True
def get_date(mdate):
# convert apple's "reference date" to unix timestamp
# (seconds between Jan 1 1970 and Jan 1 2001)
# http://stackoverflow.com/questions/6998541
try:
mdate = int(mdate) + 978307200
mdatetime = datetime.fromtimestamp(mdate)
mdatetime = mdatetime.strftime("%Y-%m-%d %H:%M:%S")
except Exception as e:
print('- Error: unable to decode date: {}'.format(e))
print('- Error: problematic timestamp mdate=%s' % mdate)
PrintException()
return "0000-00-00 00:00:00"
return mdatetime
def sanitize_filename(f):
invalid_chars = "?*/\\:\"<>|"
for char in invalid_chars:
f = f.replace(char, "-")
return f
def sanitize_filename2(f):
invalid_chars = "?*:\"<>|"
if (len(f) < 8):
return f
f_part = f[:8]
ff = f[8:]
for char in invalid_chars:
ff = ff.replace(char, "-")
ff = ff.replace("\\\\", "-")
ff = f_part + ff
#print("before = %s after=%s" % (f, ff))
return ff
# taken from https://www.alfredforum.com/topic/11716-search-appleicloud-notes/page/2/
def extractNoteBody(data):
try:
# Strip weird characters, title & weird header artifacts,
# and replace line breaks with spaces
data = zlib.decompress(data, 16+zlib.MAX_WBITS)
data = data.decode('unicode_escape', errors="ignore").encode('utf-8', errors="ignore")
data = data.decode().split('\x1a\x10', 1)[0]
# Reference: https://github.com/threeplanetssoftware/apple_cloud_notes_parser
# Find magic hex and remove it
index = data.index('\x08\x00\x10\x00\x1a')
index = data.index('\x12', index)
# Read from the next byte after magic index
data = data[index+1:]
#data = unicode(data, "utf8", errors="ignore")
data = data.encode("utf8", errors="ignore")
return re.sub('^.*\n|\n', ' ', data.decode())
except Exception as e:
print('- Error: Note body could not be extracted: {}'.format(e))
PrintException()
return 'Note body could not be extracted: {}'.format(e)
def isBackup(BackupPath):
'''
Check if path contains backup
(files below should be always available in the correct backup directory)
'''
if os.path.isdir(BackupPath):
content = os.listdir(BackupPath)
return ('Manifest.db' in content and 'Info.plist' in content) or ('Status.plist' in content and 'Snapshot' in content)
return False
def pathConvert(path):
path = str(path)
if path.find('\\\\') == -1:
path = PBEGIN + path
# path = "\\\\?\\C:\\out\\AppDomain-im.vector.app\\Library\\Preferences\\1https:\\\\dupa"
path = path.replace('sceneID:', 'sceneID_BAD1_') # replace bad chars
path = sanitize_filename2(path)
#sys.exit(0)
path = Path(path) # conver to OS format
return path
# Get full path for selected database file
def pathDBOut(Conn, OutPath, FileName):
FileIDHash = hashlib.sha1(str(FileName).encode('utf-8')).hexdigest()
c = Conn.cursor()
file = c.execute('SELECT domain, relativePath from Files WHERE (flags IS 1) AND (fileID == "' + FileIDHash + '")').fetchone()
if file == None:
print("! Error: unable to find %s in db" % FileName)
return False
#out = OutPath + '\\' + file[0] + '\\' + file[1]
out = os.path.join(OutPath, file[0])
out = os.path.join(out, file[1])
out = pathConvert(out)
#print(out)
return out
def sha256sum(filename):
h = hashlib.sha256()
b = bytearray(128*1024)
mv = memoryview(b)
with open(filename, 'rb', buffering=0) as f:
for n in iter(lambda : f.readinto(mv), 0):
h.update(mv[:n])
return h.hexdigest()
def extract(Conn, BackupPath, OutPath, outJSON, isEncrypted):
c = Conn.cursor()
print('+ Getting information about directories')
all_dirs = c.execute('SELECT * FROM Files WHERE flags IS 2').fetchall()
for id_, domain, file, flag, f in all_dirs:
d1 = pathConvert(os.path.join(OutPath, domain))
d2 = pathConvert(os.path.join(OutPath, domain, file))
# print('d1 = %s' % d1)
# print('d2 = %s' % d2)
try:
if not os.path.isdir(d1):
os.makedirs(d1)
if not os.path.isdir(d2):
os.makedirs(d2)
except OSError as err:
print('! Error: during directory creation ' + str(err))
#sys.exit(0)
print('+ Directories created')
all_files = c.execute('SELECT * FROM Files WHERE flags IS 1').fetchall()
total_files = float(len(all_files))
counter = 1
print('+ Detected %d files' % total_files)
# extract them
item = {}
f_out = open(outJSON, 'w')
db_name = ' \n { \t"fileinfo_' + DB_VAR_MARKER + '": [\n'
f_out.write(db_name)
for id_, domain, file, flag, f in all_files:
if flag == 1:
path_split = os.path.split(file)
sub_dir = id_[:2]
#print('PathSplit=%s sub_dir=%s file=%s id=%s' % (path_split, sub_dir, file, id_))
path_src = pathConvert(os.path.join(BackupPath, sub_dir, id_))
path_dest = pathConvert(os.path.join(OutPath, domain, file))
if isEncrypted == True:
path_src = pathConvert(os.path.join(BackupPath, sub_dir, id_ + DECYRPTED_PREFIX))
#print('PathSrc=%s PathDest=%s ' % (path_src, path_dest))
#sys.exit(0)
try:
pl = plistlib.loads(f)
plx = pl.get('$objects')[1]
#print(plx)
_creationTime = null
_accessTime = null
_modTime = null
if ('Birth' in plx): _creationTime = plx['LastModified']
if ('LastStatusChange' in plx): _accessTime = plx['LastStatusChange']
if ('LastModified' in plx): _modTime = plx['LastModified']
#print('+ Copying (%d/%d) \"%s\" to \"%s\" ' % (counter, total_files, file, path_dest))
#
# get details about the file
# id_, domain, name, path, sha256, size, created, modified, accessed
#
_name = os.path.basename(path_src)
_sha256 = sha256sum(path_src)
_size = os.path.getsize(path_src)
_creationTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(_creationTime))
_accessTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(_accessTime))
_modTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(_modTime))
item = { 'id' : id_,
'name' : _name,
'domain' : domain,
'path' : file,