├── README.md
├── ccl_bplist.py
├── iOS_BplistInception.py
├── parse3.py
└── run.PNG
/README.md:
--------------------------------------------------------------------------------
1 | # iOS-KnowledgeC-StructuredMetadata-Bplists
2 | Script to extract compound bplists in the iOS -> KnowledgeC.db -> structuredmetadata table.
3 |
4 | 
5 |
6 | Usage:
7 | python ios_bplistinception.py /path/to/knowledgec.db iosversion [-d false]
8 |
9 | 1. Python 3
10 | 2. The ccl_bplist module is required for the scripts to work. It can be found here: https://github.com/cclgroupltd/ccl-bplist (But a version has been inluded in this repo)
11 | 3. The parse protobuf decoder by @Nevermoe (https://github.com/nevermoe/protobuf-decoder) has been updated to run on Python3 by Craig Rowland from Sandfly Security. This is to be placed in the same directory as the main script.
12 | 3. Export a knowledgeC database from iOS, if you place it in the same directory it will run, otherwise you can run the script and point it to the right path
13 | 4. Set the correct iOS version (11 or 12 supported). The script doesn't automatically identify which version of iOS the database has been extracted from.
14 | 5. Run the script. A timestamp named folder will be created that will contain two folders. One for extracted database content (named dirty) and one for the extracted bplist contained within the extracte database content (clean.)
15 | 6. Timestamped folder will also contain a HTML report with information on the clean bplists.
16 |
17 | By default the tool will dump out the nsdata sections of the clean plists, you can turn this off with -d false, but I don't know why you would want to do that.
18 |
19 | License: free to use etc, but if you're going to incorporate this into your paid tool and weren't before you read this code or the accompanying post please let me know or give credit.
20 |
21 | ## I'd also suggest carving for plists in the database if you can. Reach out to @phillmoore if you want assistance with this. I have a script or two, but they're very rusty
22 |
--------------------------------------------------------------------------------
/ccl_bplist.py:
--------------------------------------------------------------------------------
1 | """
2 | Copyright (c) 2012-2016, CCL Forensics
3 | All rights reserved.
4 |
5 | Redistribution and use in source and binary forms, with or without
6 | modification, are permitted provided that the following conditions are met:
7 | * Redistributions of source code must retain the above copyright
8 | notice, this list of conditions and the following disclaimer.
9 | * Redistributions in binary form must reproduce the above copyright
10 | notice, this list of conditions and the following disclaimer in the
11 | documentation and/or other materials provided with the distribution.
12 | * Neither the name of the CCL Forensics nor the
13 | names of its contributors may be used to endorse or promote products
14 | derived from this software without specific prior written permission.
15 |
16 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
17 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 | DISCLAIMED. IN NO EVENT SHALL CCL FORENSICS BE LIABLE FOR ANY
20 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 | """
27 |
28 | import sys
29 | import os
30 | import struct
31 | import datetime
32 |
33 | __version__ = "0.21"
34 | __description__ = "Converts Apple binary PList files into a native Python data structure"
35 | __contact__ = "Alex Caithness"
36 |
37 | _object_converter = None
38 | def set_object_converter(function):
39 | """Sets the object converter function to be used when retrieving objects from the bplist.
40 | default is None (which will return objects in their raw form).
41 | A built in converter (ccl_bplist.NSKeyedArchiver_common_objects_convertor) which is geared
42 | toward dealling with common types in NSKeyedArchiver is available which can simplify code greatly
43 | when dealling with these types of files."""
44 | if not hasattr(function, "__call__"):
45 | raise TypeError("function is not a function")
46 | global _object_converter
47 | _object_converter = function
48 |
49 | class BplistError(Exception):
50 | pass
51 |
52 | class BplistUID:
53 | def __init__(self, value):
54 | self.value = value
55 |
56 | def __repr__(self):
57 | return "UID: {0}".format(self.value)
58 |
59 | def __str__(self):
60 | return self.__repr__()
61 |
62 | def __decode_multibyte_int(b, signed=True):
63 | if len(b) == 1:
64 | fmt = ">B" # Always unsigned?
65 | elif len(b) == 2:
66 | fmt = ">h"
67 | elif len(b) == 3:
68 | if signed:
69 | return ((b[0] << 16) | struct.unpack(">H", b[1:])[0]) - ((b[0] >> 7) * 2 * 0x800000)
70 | else:
71 | return (b[0] << 16) | struct.unpack(">H", b[1:])[0]
72 | elif len(b) == 4:
73 | fmt = ">i"
74 | elif len(b) == 8:
75 | fmt = ">q"
76 | elif len(b) == 16:
77 | # special case for BigIntegers
78 | high, low = struct.unpack(">QQ", b)
79 | result = (high << 64) | low
80 | if high & 0x8000000000000000 and signed:
81 | result -= 0x100000000000000000000000000000000
82 | return result
83 | else:
84 | raise BplistError("Cannot decode multibyte int of length {0}".format(len(b)))
85 |
86 | if signed and len(b) > 1:
87 | return struct.unpack(fmt.lower(), b)[0]
88 | else:
89 | return struct.unpack(fmt.upper(), b)[0]
90 |
91 | def __decode_float(b, signed=True):
92 | if len(b) == 4:
93 | fmt = ">f"
94 | elif len(b) == 8:
95 | fmt = ">d"
96 | else:
97 | raise BplistError("Cannot decode float of length {0}".format(len(b)))
98 |
99 | if signed:
100 | return struct.unpack(fmt.lower(), b)[0]
101 | else:
102 | return struct.unpack(fmt.upper(), b)[0]
103 |
104 | def __decode_object(f, offset, collection_offset_size, offset_table):
105 | # Move to offset and read type
106 | #print("Decoding object at offset {0}".format(offset))
107 | f.seek(offset)
108 | # A little hack to keep the script portable between py2.x and py3k
109 | if sys.version_info[0] < 3:
110 | type_byte = ord(f.read(1)[0])
111 | else:
112 | type_byte = f.read(1)[0]
113 | #print("Type byte: {0}".format(hex(type_byte)))
114 | if type_byte == 0x00: # Null 0000 0000
115 | return None
116 | elif type_byte == 0x08: # False 0000 1000
117 | return False
118 | elif type_byte == 0x09: # True 0000 1001
119 | return True
120 | elif type_byte == 0x0F: # Fill 0000 1111
121 | raise BplistError("Fill type not currently supported at offset {0}".format(f.tell())) # Not sure what to return really...
122 | elif type_byte & 0xF0 == 0x10: # Int 0001 xxxx
123 | int_length = 2 ** (type_byte & 0x0F)
124 | int_bytes = f.read(int_length)
125 | return __decode_multibyte_int(int_bytes)
126 | elif type_byte & 0xF0 == 0x20: # Float 0010 nnnn
127 | float_length = 2 ** (type_byte & 0x0F)
128 | float_bytes = f.read(float_length)
129 | return __decode_float(float_bytes)
130 | elif type_byte & 0xFF == 0x33: # Date 0011 0011
131 | date_bytes = f.read(8)
132 | date_value = __decode_float(date_bytes)
133 | try:
134 | result = datetime.datetime(2001,1,1) + datetime.timedelta(seconds = date_value)
135 | except OverflowError:
136 | result = datetime.datetime.min
137 | return result
138 | elif type_byte & 0xF0 == 0x40: # Data 0100 nnnn
139 | if type_byte & 0x0F != 0x0F:
140 | # length in 4 lsb
141 | data_length = type_byte & 0x0F
142 | else:
143 | # A little hack to keep the script portable between py2.x and py3k
144 | if sys.version_info[0] < 3:
145 | int_type_byte = ord(f.read(1)[0])
146 | else:
147 | int_type_byte = f.read(1)[0]
148 | if int_type_byte & 0xF0 != 0x10:
149 | raise BplistError("Long Data field definition not followed by int type at offset {0}".format(f.tell()))
150 | int_length = 2 ** (int_type_byte & 0x0F)
151 | int_bytes = f.read(int_length)
152 | data_length = __decode_multibyte_int(int_bytes, False)
153 | return f.read(data_length)
154 | elif type_byte & 0xF0 == 0x50: # ASCII 0101 nnnn
155 | if type_byte & 0x0F != 0x0F:
156 | # length in 4 lsb
157 | ascii_length = type_byte & 0x0F
158 | else:
159 | # A little hack to keep the script portable between py2.x and py3k
160 | if sys.version_info[0] < 3:
161 | int_type_byte = ord(f.read(1)[0])
162 | else:
163 | int_type_byte = f.read(1)[0]
164 | if int_type_byte & 0xF0 != 0x10:
165 | raise BplistError("Long ASCII field definition not followed by int type at offset {0}".format(f.tell()))
166 | int_length = 2 ** (int_type_byte & 0x0F)
167 | int_bytes = f.read(int_length)
168 | ascii_length = __decode_multibyte_int(int_bytes, False)
169 | return f.read(ascii_length).decode("ascii")
170 | elif type_byte & 0xF0 == 0x60: # UTF-16 0110 nnnn
171 | if type_byte & 0x0F != 0x0F:
172 | # length in 4 lsb
173 | utf16_length = (type_byte & 0x0F) * 2 # Length is characters - 16bit width
174 | else:
175 | # A little hack to keep the script portable between py2.x and py3k
176 | if sys.version_info[0] < 3:
177 | int_type_byte = ord(f.read(1)[0])
178 | else:
179 | int_type_byte = f.read(1)[0]
180 | if int_type_byte & 0xF0 != 0x10:
181 | raise BplistError("Long UTF-16 field definition not followed by int type at offset {0}".format(f.tell()))
182 | int_length = 2 ** (int_type_byte & 0x0F)
183 | int_bytes = f.read(int_length)
184 | utf16_length = __decode_multibyte_int(int_bytes, False) * 2
185 | return f.read(utf16_length).decode("utf_16_be")
186 | elif type_byte & 0xF0 == 0x80: # UID 1000 nnnn
187 | uid_length = (type_byte & 0x0F) + 1
188 | uid_bytes = f.read(uid_length)
189 | return BplistUID(__decode_multibyte_int(uid_bytes, signed=False))
190 | elif type_byte & 0xF0 == 0xA0: # Array 1010 nnnn
191 | if type_byte & 0x0F != 0x0F:
192 | # length in 4 lsb
193 | array_count = type_byte & 0x0F
194 | else:
195 | # A little hack to keep the script portable between py2.x and py3k
196 | if sys.version_info[0] < 3:
197 | int_type_byte = ord(f.read(1)[0])
198 | else:
199 | int_type_byte = f.read(1)[0]
200 | if int_type_byte & 0xF0 != 0x10:
201 | raise BplistError("Long Array field definition not followed by int type at offset {0}".format(f.tell()))
202 | int_length = 2 ** (int_type_byte & 0x0F)
203 | int_bytes = f.read(int_length)
204 | array_count = __decode_multibyte_int(int_bytes, signed=False)
205 | array_refs = []
206 | for i in range(array_count):
207 | array_refs.append(__decode_multibyte_int(f.read(collection_offset_size), False))
208 | return [__decode_object(f, offset_table[obj_ref], collection_offset_size, offset_table) for obj_ref in array_refs]
209 | elif type_byte & 0xF0 == 0xC0: # Set 1010 nnnn
210 | if type_byte & 0x0F != 0x0F:
211 | # length in 4 lsb
212 | set_count = type_byte & 0x0F
213 | else:
214 | # A little hack to keep the script portable between py2.x and py3k
215 | if sys.version_info[0] < 3:
216 | int_type_byte = ord(f.read(1)[0])
217 | else:
218 | int_type_byte = f.read(1)[0]
219 | if int_type_byte & 0xF0 != 0x10:
220 | raise BplistError("Long Set field definition not followed by int type at offset {0}".format(f.tell()))
221 | int_length = 2 ** (int_type_byte & 0x0F)
222 | int_bytes = f.read(int_length)
223 | set_count = __decode_multibyte_int(int_bytes, signed=False)
224 | set_refs = []
225 | for i in range(set_count):
226 | set_refs.append(__decode_multibyte_int(f.read(collection_offset_size), False))
227 | return [__decode_object(f, offset_table[obj_ref], collection_offset_size, offset_table) for obj_ref in set_refs]
228 | elif type_byte & 0xF0 == 0xD0: # Dict 1011 nnnn
229 | if type_byte & 0x0F != 0x0F:
230 | # length in 4 lsb
231 | dict_count = type_byte & 0x0F
232 | else:
233 | # A little hack to keep the script portable between py2.x and py3k
234 | if sys.version_info[0] < 3:
235 | int_type_byte = ord(f.read(1)[0])
236 | else:
237 | int_type_byte = f.read(1)[0]
238 | #print("Dictionary length int byte: {0}".format(hex(int_type_byte)))
239 | if int_type_byte & 0xF0 != 0x10:
240 | raise BplistError("Long Dict field definition not followed by int type at offset {0}".format(f.tell()))
241 | int_length = 2 ** (int_type_byte & 0x0F)
242 | int_bytes = f.read(int_length)
243 | dict_count = __decode_multibyte_int(int_bytes, signed=False)
244 | key_refs = []
245 | #print("Dictionary count: {0}".format(dict_count))
246 | for i in range(dict_count):
247 | key_refs.append(__decode_multibyte_int(f.read(collection_offset_size), False))
248 | value_refs = []
249 | for i in range(dict_count):
250 | value_refs.append(__decode_multibyte_int(f.read(collection_offset_size), False))
251 |
252 | dict_result = {}
253 | for i in range(dict_count):
254 | #print("Key ref: {0}\tVal ref: {1}".format(key_refs[i], value_refs[i]))
255 | key = __decode_object(f, offset_table[key_refs[i]], collection_offset_size, offset_table)
256 | val = __decode_object(f, offset_table[value_refs[i]], collection_offset_size, offset_table)
257 | dict_result[key] = val
258 | return dict_result
259 |
260 |
261 | def load(f):
262 | """
263 | Reads and converts a file-like object containing a binary property list.
264 | Takes a file-like object (must support reading and seeking) as an argument
265 | Returns a data structure representing the data in the property list
266 | """
267 | # Check magic number
268 | if f.read(8) != b"bplist00":
269 | raise BplistError("Bad file header")
270 |
271 | # Read trailer
272 | f.seek(-32, os.SEEK_END)
273 | trailer = f.read(32)
274 | offset_int_size, collection_offset_size, object_count, top_level_object_index, offest_table_offset = struct.unpack(">6xbbQQQ", trailer)
275 |
276 | # Read offset table
277 | f.seek(offest_table_offset)
278 | offset_table = []
279 | for i in range(object_count):
280 | offset_table.append(__decode_multibyte_int(f.read(offset_int_size), False))
281 |
282 | return __decode_object(f, offset_table[top_level_object_index], collection_offset_size, offset_table)
283 |
284 |
285 | def NSKeyedArchiver_common_objects_convertor(o):
286 | """Built in converter function (suitable for submission to set_object_converter()) which automatically
287 | converts the following common data-types found in NSKeyedArchiver:
288 | NSDictionary/NSMutableDictionary;
289 | NSArray/NSMutableArray;
290 | NSSet/NSMutableSet
291 | NSString/NSMutableString
292 | NSDate
293 | $null strings"""
294 | # Conversion: NSDictionary
295 | if is_nsmutabledictionary(o):
296 | return convert_NSMutableDictionary(o)
297 | # Conversion: NSArray
298 | elif is_nsarray(o):
299 | return convert_NSArray(o)
300 | elif is_isnsset(o):
301 | return convert_NSSet(o)
302 | # Conversion: NSString
303 | elif is_nsstring(o):
304 | return convert_NSString(o)
305 | # Conversion: NSDate
306 | elif is_nsdate(o):
307 | return convert_NSDate(o)
308 | # Conversion: "$null" string
309 | elif isinstance(o, str) and o == "$null":
310 | return None
311 | # Fallback:
312 | else:
313 | return o
314 |
315 | def NSKeyedArchiver_convert(o, object_table):
316 | if isinstance(o, list):
317 | #return NsKeyedArchiverList(o, object_table)
318 | result = NsKeyedArchiverList(o, object_table)
319 | elif isinstance(o, dict):
320 | #return NsKeyedArchiverDictionary(o, object_table)
321 | result = NsKeyedArchiverDictionary(o, object_table)
322 | elif isinstance(o, BplistUID):
323 | #return NSKeyedArchiver_convert(object_table[o.value], object_table)
324 | result = NSKeyedArchiver_convert(object_table[o.value], object_table)
325 | else:
326 | #return o
327 | result = o
328 |
329 | if _object_converter:
330 | return _object_converter(result)
331 | else:
332 | return result
333 |
334 |
335 | class NsKeyedArchiverDictionary(dict):
336 | def __init__(self, original_dict, object_table):
337 | super(NsKeyedArchiverDictionary, self).__init__(original_dict)
338 | self.object_table = object_table
339 |
340 | def __getitem__(self, index):
341 | o = super(NsKeyedArchiverDictionary, self).__getitem__(index)
342 | return NSKeyedArchiver_convert(o, self.object_table)
343 |
344 | def get(self, key, default=None):
345 | return self[key] if key in self else default
346 |
347 | def values(self):
348 | for k in self:
349 | yield self[k]
350 |
351 | def items(self):
352 | for k in self:
353 | yield k, self[k]
354 |
355 | class NsKeyedArchiverList(list):
356 | def __init__(self, original_iterable, object_table):
357 | super(NsKeyedArchiverList, self).__init__(original_iterable)
358 | self.object_table = object_table
359 |
360 | def __getitem__(self, index):
361 | o = super(NsKeyedArchiverList, self).__getitem__(index)
362 | return NSKeyedArchiver_convert(o, self.object_table)
363 |
364 | def __iter__(self):
365 | for o in super(NsKeyedArchiverList, self).__iter__():
366 | yield NSKeyedArchiver_convert(o, self.object_table)
367 |
368 |
369 | def deserialise_NsKeyedArchiver(obj, parse_whole_structure=False):
370 | """Deserialises an NSKeyedArchiver bplist rebuilding the structure.
371 | obj should usually be the top-level object returned by the load()
372 | function."""
373 |
374 | # Check that this is an archiver and version we understand
375 | if not isinstance(obj, dict):
376 | raise TypeError("obj must be a dict")
377 | if "$archiver" not in obj or obj["$archiver"] not in ("NSKeyedArchiver", "NRKeyedArchiver"):
378 | raise ValueError("obj does not contain an '$archiver' key or the '$archiver' is unrecognised")
379 | if "$version" not in obj or obj["$version"] != 100000:
380 | raise ValueError("obj does not contain a '$version' key or the '$version' is unrecognised")
381 |
382 | object_table = obj["$objects"]
383 | if "root" in obj["$top"] and not parse_whole_structure:
384 | return NSKeyedArchiver_convert(obj["$top"]["root"], object_table)
385 | else:
386 | return NSKeyedArchiver_convert(obj["$top"], object_table)
387 |
388 | # NSMutableDictionary convenience functions
389 | def is_nsmutabledictionary(obj):
390 | if not isinstance(obj, dict):
391 | return False
392 | if "$class" not in obj.keys():
393 | return False
394 | if obj["$class"].get("$classname") not in ("NSMutableDictionary", "NSDictionary"):
395 | return False
396 | if "NS.keys" not in obj.keys():
397 | return False
398 | if "NS.objects" not in obj.keys():
399 | return False
400 |
401 | return True
402 |
403 | def convert_NSMutableDictionary(obj):
404 | """Converts a NSKeyedArchiver serialised NSMutableDictionary into
405 | a straight dictionary (rather than two lists as it is serialised
406 | as)"""
407 |
408 | # The dictionary is serialised as two lists (one for keys and one
409 | # for values) which obviously removes all convenience afforded by
410 | # dictionaries. This function converts this structure to an
411 | # actual dictionary so that values can be accessed by key.
412 |
413 | if not is_nsmutabledictionary(obj):
414 | raise ValueError("obj does not have the correct structure for a NSDictionary/NSMutableDictionary serialised to a NSKeyedArchiver")
415 | keys = obj["NS.keys"]
416 | vals = obj["NS.objects"]
417 |
418 | # sense check the keys and values:
419 | if not isinstance(keys, list):
420 | raise TypeError("The 'NS.keys' value is an unexpected type (expected list; actual: {0}".format(type(keys)))
421 | if not isinstance(vals, list):
422 | raise TypeError("The 'NS.objects' value is an unexpected type (expected list; actual: {0}".format(type(vals)))
423 | if len(keys) != len(vals):
424 | raise ValueError("The length of the 'NS.keys' list ({0}) is not equal to that of the 'NS.objects ({1})".format(len(keys), len(vals)))
425 |
426 | result = {}
427 | for i,k in enumerate(keys):
428 | if k in result:
429 | raise ValueError("The 'NS.keys' list contains duplicate entries")
430 | result[k] = vals[i]
431 |
432 | return result
433 |
434 | # NSArray convenience functions
435 | def is_nsarray(obj):
436 | if not isinstance(obj, dict):
437 | return False
438 | if "$class" not in obj.keys():
439 | return False
440 | if obj["$class"].get("$classname") not in ("NSArray", "NSMutableArray"):
441 | return False
442 | if "NS.objects" not in obj.keys():
443 | return False
444 |
445 | return True
446 |
447 | def convert_NSArray(obj):
448 | if not is_nsarray(obj):
449 | raise ValueError("obj does not have the correct structure for a NSArray/NSMutableArray serialised to a NSKeyedArchiver")
450 |
451 | return obj["NS.objects"]
452 |
453 | # NSSet convenience functions
454 | def is_isnsset(obj):
455 | if not isinstance(obj, dict):
456 | return False
457 | if "$class" not in obj.keys():
458 | return False
459 | if obj["$class"].get("$classname") not in ("NSSet", "NSMutableSet"):
460 | return False
461 | if "NS.objects" not in obj.keys():
462 | return False
463 |
464 | return True
465 |
466 | def convert_NSSet(obj):
467 | if not is_isnsset(obj):
468 | raise ValueError("obj does not have the correct structure for a NSSet/NSMutableSet serialised to a NSKeyedArchiver")
469 |
470 | return list(obj["NS.objects"])
471 |
472 | # NSString convenience functions
473 | def is_nsstring(obj):
474 | if not isinstance(obj, dict):
475 | return False
476 | if "$class" not in obj.keys():
477 | return False
478 | if obj["$class"].get("$classname") not in ("NSString", "NSMutableString"):
479 | return False
480 | if "NS.string" not in obj.keys():
481 | return False
482 | return True
483 |
484 | def convert_NSString(obj):
485 | if not is_nsstring(obj):
486 | raise ValueError("obj does not have the correct structure for a NSString/NSMutableString serialised to a NSKeyedArchiver")
487 |
488 | return obj["NS.string"]
489 |
490 | # NSDate convenience functions
491 | def is_nsdate(obj):
492 | if not isinstance(obj, dict):
493 | return False
494 | if "$class" not in obj.keys():
495 | return False
496 | if obj["$class"].get("$classname") not in ("NSDate"):
497 | return False
498 | if "NS.time" not in obj.keys():
499 | return False
500 |
501 | return True
502 |
503 | def convert_NSDate(obj):
504 | if not is_nsdate(obj):
505 | raise ValueError("obj does not have the correct structure for a NSDate serialised to a NSKeyedArchiver")
506 |
507 | return datetime.datetime(2001, 1, 1) + datetime.timedelta(seconds=obj["NS.time"])
508 |
--------------------------------------------------------------------------------
/iOS_BplistInception.py:
--------------------------------------------------------------------------------
1 | import sys
2 | import ccl_bplist
3 | import plistlib
4 | import io
5 | import sqlite3
6 | import os
7 | import glob
8 | import datetime
9 | import argparse
10 | from parse3 import ParseProto
11 | import codecs
12 | import json
13 |
14 |
15 | parser = argparse.ArgumentParser()
16 |
17 | parser.add_argument("db", nargs='?', help="database")
18 | parser.add_argument('v', help="version")
19 | parser.add_argument('-d', '--dump', default=True, help="Dumps the nsdata objects from the clean plists to binary files. Not recommended to set to false")
20 | args = parser.parse_args()
21 |
22 |
23 | iOSversion = args.v
24 |
25 | supportediOS = ['11', '12']
26 |
27 | if iOSversion not in supportediOS:
28 | print ("Unsupported version")
29 | sys.exit()
30 |
31 | if args.db:
32 | database = args.db
33 | else:
34 | database = 'knowledgec.db'
35 |
36 | try:
37 | f = open(database)
38 | f.close()
39 | except IOError as e:
40 | print (database + ': No file found')
41 | sys.exit()
42 |
43 | extension = '.bplist'
44 |
45 | #create directories
46 | foldername = str(int(datetime.datetime.now().timestamp()))
47 |
48 |
49 | path = os.getcwd()
50 | try:
51 | outpath = path + "/" + foldername
52 | os.mkdir(outpath)
53 | os.mkdir(outpath+"/clean")
54 | os.mkdir(outpath+"/dirty")
55 | except OSError:
56 | print("Error making directories")
57 |
58 | #connect sqlite databases
59 | db = sqlite3.connect(database)
60 | cursor = db.cursor()
61 |
62 | #variable initializations
63 | dirtcount = 0
64 | cleancount = 0
65 | intentc = {}
66 | intentv = {}
67 |
68 | cursor.execute('''
69 | SELECT
70 | Z_PK,
71 | Z_DKINTENTMETADATAKEY__SERIALIZEDINTERACTION,
72 | Z_DKINTENTMETADATAKEY__INTENTCLASS,
73 | Z_DKINTENTMETADATAKEY__INTENTVERB
74 | FROM ZSTRUCTUREDMETADATA
75 | WHERE Z_DKINTENTMETADATAKEY__SERIALIZEDINTERACTION is not null
76 | ''')
77 |
78 | all_rows = cursor.fetchall()
79 |
80 | for row in all_rows:
81 | pkv = str(row[0])
82 | pkvplist = pkv+extension
83 | f = row[1]
84 | intentclass = str(row[2])
85 | intententverb = str(row[3])
86 | output_file = open('./'+foldername+'/dirty/D_Z_PK'+pkvplist, 'wb') #export dirty from DB
87 | output_file.write(f)
88 | output_file.close()
89 |
90 | g = open('./'+foldername+'/dirty/D_Z_PK'+pkvplist, 'rb')
91 | plistg = ccl_bplist.load(g)
92 |
93 | if (iOSversion == '11'):
94 | ns_keyed_archiver_obj = ccl_bplist.deserialise_NsKeyedArchiver(plistg)
95 | newbytearray = ns_keyed_archiver_obj
96 | if (iOSversion == '12'):
97 | ns_keyed_archiver_objg = ccl_bplist.deserialise_NsKeyedArchiver(plistg)
98 | newbytearray = (ns_keyed_archiver_objg["NS.data"])
99 |
100 | dirtcount = dirtcount+1
101 |
102 | binfile = open('./'+foldername+'/clean/C_Z_PK'+pkvplist, 'wb')
103 | binfile.write(newbytearray)
104 | binfile.close()
105 |
106 | #add to dictionaries
107 | intentc['C_Z_PK'+pkvplist] = intentclass
108 | intentv['C_Z_PK'+pkvplist] = intententverb
109 |
110 | cleancount = cleancount+1
111 |
112 | h = open('./'+foldername+'/Report.html', 'w')
113 | h.write('
')
114 | h.write('iOS ' + iOSversion + ' - KnowledgeC ZSTRUCTUREDMETADATA bplist report
')
115 | h.write ('')
116 | h.write('
')
117 |
118 | for filename in glob.glob('./'+foldername+'/clean/*'+extension):
119 | p = open(filename, 'rb')
120 | cfilename = os.path.basename(filename)
121 | plist = ccl_bplist.load(p)
122 | ns_keyed_archiver_obj = ccl_bplist.deserialise_NsKeyedArchiver(plist, parse_whole_structure=True)#deserialize clean
123 | #Get dictionary values
124 | A = intentc.get(cfilename)
125 | B = intentv.get(cfilename)
126 |
127 | if A is None:
128 | A = 'No value'
129 | if B is None:
130 | A = 'No value'
131 |
132 | #print some values from clean bplist
133 | NSdata = (ns_keyed_archiver_obj["root"]["intent"]["backingStore"]["data"]["NS.data"])
134 |
135 | parsedNSData = ""
136 | #Default true
137 | if args.dump == True:
138 | nsdata_file = './'+foldername+'/clean/'+cfilename+'_nsdata.bin'
139 | binfile = open(nsdata_file, 'wb')
140 | binfile.write(ns_keyed_archiver_obj["root"]["intent"]["backingStore"]["data"]["NS.data"])
141 | binfile.close()
142 | messages = ParseProto(nsdata_file)
143 | messages_json_dump = json.dumps(messages, indent=4, sort_keys=True, ensure_ascii=False)
144 | parsedNSData = str(messages_json_dump).encode(encoding='UTF-8',errors='ignore')
145 |
146 | NSstartDate = ccl_bplist.convert_NSDate((ns_keyed_archiver_obj["root"]["dateInterval"]["NS.startDate"]))
147 | NSendDate = ccl_bplist.convert_NSDate((ns_keyed_archiver_obj["root"]["dateInterval"]["NS.endDate"]))
148 | NSduration = ns_keyed_archiver_obj["root"]["dateInterval"]["NS.duration"]
149 | Siri = ns_keyed_archiver_obj["root"]["_donatedBySiri"]
150 |
151 | h.write(cfilename)
152 | h.write('
')
153 | h.write('Intent Class: '+str(A))
154 | h.write('
')
155 | h.write('Intent Verb: '+str(B))
156 | h.write('
')
157 | h.write('')
158 |
159 |
160 | h.write('')
161 | h.write('Data type | ')
162 | h.write('Value | ')
163 | h.write('
')
164 |
165 | #Donated by Siri
166 | h.write('')
167 | h.write('Siri | ')
168 | h.write(''+str(Siri)+' | ')
169 | h.write('
')
170 |
171 | #NSstartDate
172 | h.write('')
173 | h.write('NSstartDate | ')
174 | h.write(''+str(NSstartDate)+' Z | ')
175 | h.write('
')
176 |
177 | #NSsendDate
178 | h.write('')
179 | h.write('NSendDate | ')
180 | h.write(''+str(NSendDate)+' Z | ')
181 | h.write('
')
182 |
183 | #NSduration
184 | h.write('')
185 | h.write('NSduration | ')
186 | h.write(''+str(NSduration)+' | ')
187 | h.write('
')
188 |
189 | #NSdata
190 | h.write('')
191 | h.write('NSdata | ')
192 | h.write(''+str(NSdata)+' | ')
193 | h.write('
')
194 |
195 | #NSdata better formatting
196 | if parsedNSData:
197 | h.write('')
198 | h.write('NSdata - Protobuf Decoded | ')
199 | h.write(''+str(parsedNSData).replace('\\n', ' ')+' | ')
200 | h.write('
')
201 | else:
202 | #This will only run if -nd is used
203 | h.write('')
204 | h.write('NSdata - Protobuf | ')
205 | h.write(''+str(NSdata).replace('\\n', ' ')+' | ')
206 | h.write('
')
207 |
208 | h.write('')
209 | h.write('
')
210 |
211 | #print(NSstartDate)
212 | #print(NSendDate)
213 | #print(NSduration)
214 | #print(NSdata)
215 | #print('')
216 |
217 |
218 | print("")
219 | print("iOS - KnowledgeC ZSTRUCTUREDMETADATA bplist extractor")
220 | print("By: @phillmoore & @AlexisBrignoni")
221 | print("thinkdfir.com & abrignoni.com")
222 | print("")
223 | print("Bplists from the Z_DKINTENTMETADATAKEY__SERIALIZEDINTERACTION field.")
224 | print("Exported bplists (dirty): "+str(dirtcount))
225 | print("Exported bplists (clean): "+str(cleancount))
226 | print("")
227 | print("Triage report completed. See Reports.html.")
228 |
229 |
--------------------------------------------------------------------------------
/parse3.py:
--------------------------------------------------------------------------------
1 | # Original by @Nevermoe
2 | # https://github.com/nevermoe/protobuf-decoder
3 |
4 | # Updated by Craig Rowland at Sandfly Security to work with Python3
5 |
6 | # GNU GENERAL PUBLIC LICENSE
7 | # Version 2, June 1991
8 |
9 | # Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
10 | # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
11 | # Everyone is permitted to copy and distribute verbatim copies
12 | # of this license document, but changing it is not allowed.
13 |
14 | # Preamble
15 |
16 | # The licenses for most software are designed to take away your
17 | # freedom to share and change it. By contrast, the GNU General Public
18 | # License is intended to guarantee your freedom to share and change free
19 | # software--to make sure the software is free for all its users. This
20 | # General Public License applies to most of the Free Software
21 | # Foundation's software and to any other program whose authors commit to
22 | # using it. (Some other Free Software Foundation software is covered by
23 | # the GNU Lesser General Public License instead.) You can apply it to
24 | # your programs, too.
25 |
26 | # When we speak of free software, we are referring to freedom, not
27 | # price. Our General Public Licenses are designed to make sure that you
28 | # have the freedom to distribute copies of free software (and charge for
29 | # this service if you wish), that you receive source code or can get it
30 | # if you want it, that you can change the software or use pieces of it
31 | # in new free programs; and that you know you can do these things.
32 |
33 | # To protect your rights, we need to make restrictions that forbid
34 | # anyone to deny you these rights or to ask you to surrender the rights.
35 | # These restrictions translate to certain responsibilities for you if you
36 | # distribute copies of the software, or if you modify it.
37 |
38 | # For example, if you distribute copies of such a program, whether
39 | # gratis or for a fee, you must give the recipients all the rights that
40 | # you have. You must make sure that they, too, receive or can get the
41 | # source code. And you must show them these terms so they know their
42 | # rights.
43 |
44 | # We protect your rights with two steps: (1) copyright the software, and
45 | # (2) offer you this license which gives you legal permission to copy,
46 | # distribute and/or modify the software.
47 |
48 | # Also, for each author's protection and ours, we want to make certain
49 | # that everyone understands that there is no warranty for this free
50 | # software. If the software is modified by someone else and passed on, we
51 | # want its recipients to know that what they have is not the original, so
52 | # that any problems introduced by others will not reflect on the original
53 | # authors' reputations.
54 |
55 | # Finally, any free program is threatened constantly by software
56 | # patents. We wish to avoid the danger that redistributors of a free
57 | # program will individually obtain patent licenses, in effect making the
58 | # program proprietary. To prevent this, we have made it clear that any
59 | # patent must be licensed for everyone's free use or not licensed at all.
60 |
61 | # The precise terms and conditions for copying, distribution and
62 | # modification follow.
63 |
64 | # GNU GENERAL PUBLIC LICENSE
65 | # TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
66 |
67 | # 0. This License applies to any program or other work which contains
68 | # a notice placed by the copyright holder saying it may be distributed
69 | # under the terms of this General Public License. The "Program", below,
70 | # refers to any such program or work, and a "work based on the Program"
71 | # means either the Program or any derivative work under copyright law:
72 | # that is to say, a work containing the Program or a portion of it,
73 | # either verbatim or with modifications and/or translated into another
74 | # language. (Hereinafter, translation is included without limitation in
75 | # the term "modification".) Each licensee is addressed as "you".
76 |
77 | # Activities other than copying, distribution and modification are not
78 | # covered by this License; they are outside its scope. The act of
79 | # running the Program is not restricted, and the output from the Program
80 | # is covered only if its contents constitute a work based on the
81 | # Program (independent of having been made by running the Program).
82 | # Whether that is true depends on what the Program does.
83 |
84 | # 1. You may copy and distribute verbatim copies of the Program's
85 | # source code as you receive it, in any medium, provided that you
86 | # conspicuously and appropriately publish on each copy an appropriate
87 | # copyright notice and disclaimer of warranty; keep intact all the
88 | # notices that refer to this License and to the absence of any warranty;
89 | # and give any other recipients of the Program a copy of this License
90 | # along with the Program.
91 |
92 | # You may charge a fee for the physical act of transferring a copy, and
93 | # you may at your option offer warranty protection in exchange for a fee.
94 |
95 | # 2. You may modify your copy or copies of the Program or any portion
96 | # of it, thus forming a work based on the Program, and copy and
97 | # distribute such modifications or work under the terms of Section 1
98 | # above, provided that you also meet all of these conditions:
99 |
100 | # a) You must cause the modified files to carry prominent notices
101 | # stating that you changed the files and the date of any change.
102 |
103 | # b) You must cause any work that you distribute or publish, that in
104 | # whole or in part contains or is derived from the Program or any
105 | # part thereof, to be licensed as a whole at no charge to all third
106 | # parties under the terms of this License.
107 |
108 | # c) If the modified program normally reads commands interactively
109 | # when run, you must cause it, when started running for such
110 | # interactive use in the most ordinary way, to print or display an
111 | # announcement including an appropriate copyright notice and a
112 | # notice that there is no warranty (or else, saying that you provide
113 | # a warranty) and that users may redistribute the program under
114 | # these conditions, and telling the user how to view a copy of this
115 | # License. (Exception: if the Program itself is interactive but
116 | # does not normally print such an announcement, your work based on
117 | # the Program is not required to print an announcement.)
118 |
119 | # These requirements apply to the modified work as a whole. If
120 | # identifiable sections of that work are not derived from the Program,
121 | # and can be reasonably considered independent and separate works in
122 | # themselves, then this License, and its terms, do not apply to those
123 | # sections when you distribute them as separate works. But when you
124 | # distribute the same sections as part of a whole which is a work based
125 | # on the Program, the distribution of the whole must be on the terms of
126 | # this License, whose permissions for other licensees extend to the
127 | # entire whole, and thus to each and every part regardless of who wrote it.
128 |
129 | # Thus, it is not the intent of this section to claim rights or contest
130 | # your rights to work written entirely by you; rather, the intent is to
131 | # exercise the right to control the distribution of derivative or
132 | # collective works based on the Program.
133 |
134 | # In addition, mere aggregation of another work not based on the Program
135 | # with the Program (or with a work based on the Program) on a volume of
136 | # a storage or distribution medium does not bring the other work under
137 | # the scope of this License.
138 |
139 | # 3. You may copy and distribute the Program (or a work based on it,
140 | # under Section 2) in object code or executable form under the terms of
141 | # Sections 1 and 2 above provided that you also do one of the following:
142 |
143 | # a) Accompany it with the complete corresponding machine-readable
144 | # source code, which must be distributed under the terms of Sections
145 | # 1 and 2 above on a medium customarily used for software interchange; or,
146 |
147 | # b) Accompany it with a written offer, valid for at least three
148 | # years, to give any third party, for a charge no more than your
149 | # cost of physically performing source distribution, a complete
150 | # machine-readable copy of the corresponding source code, to be
151 | # distributed under the terms of Sections 1 and 2 above on a medium
152 | # customarily used for software interchange; or,
153 |
154 | # c) Accompany it with the information you received as to the offer
155 | # to distribute corresponding source code. (This alternative is
156 | # allowed only for noncommercial distribution and only if you
157 | # received the program in object code or executable form with such
158 | # an offer, in accord with Subsection b above.)
159 |
160 | # The source code for a work means the preferred form of the work for
161 | # making modifications to it. For an executable work, complete source
162 | # code means all the source code for all modules it contains, plus any
163 | # associated interface definition files, plus the scripts used to
164 | # control compilation and installation of the executable. However, as a
165 | # special exception, the source code distributed need not include
166 | # anything that is normally distributed (in either source or binary
167 | # form) with the major components (compiler, kernel, and so on) of the
168 | # operating system on which the executable runs, unless that component
169 | # itself accompanies the executable.
170 |
171 | # If distribution of executable or object code is made by offering
172 | # access to copy from a designated place, then offering equivalent
173 | # access to copy the source code from the same place counts as
174 | # distribution of the source code, even though third parties are not
175 | # compelled to copy the source along with the object code.
176 |
177 | # 4. You may not copy, modify, sublicense, or distribute the Program
178 | # except as expressly provided under this License. Any attempt
179 | # otherwise to copy, modify, sublicense or distribute the Program is
180 | # void, and will automatically terminate your rights under this License.
181 | # However, parties who have received copies, or rights, from you under
182 | # this License will not have their licenses terminated so long as such
183 | # parties remain in full compliance.
184 |
185 | # 5. You are not required to accept this License, since you have not
186 | # signed it. However, nothing else grants you permission to modify or
187 | # distribute the Program or its derivative works. These actions are
188 | # prohibited by law if you do not accept this License. Therefore, by
189 | # modifying or distributing the Program (or any work based on the
190 | # Program), you indicate your acceptance of this License to do so, and
191 | # all its terms and conditions for copying, distributing or modifying
192 | # the Program or works based on it.
193 |
194 | # 6. Each time you redistribute the Program (or any work based on the
195 | # Program), the recipient automatically receives a license from the
196 | # original licensor to copy, distribute or modify the Program subject to
197 | # these terms and conditions. You may not impose any further
198 | # restrictions on the recipients' exercise of the rights granted herein.
199 | # You are not responsible for enforcing compliance by third parties to
200 | # this License.
201 |
202 | # 7. If, as a consequence of a court judgment or allegation of patent
203 | # infringement or for any other reason (not limited to patent issues),
204 | # conditions are imposed on you (whether by court order, agreement or
205 | # otherwise) that contradict the conditions of this License, they do not
206 | # excuse you from the conditions of this License. If you cannot
207 | # distribute so as to satisfy simultaneously your obligations under this
208 | # License and any other pertinent obligations, then as a consequence you
209 | # may not distribute the Program at all. For example, if a patent
210 | # license would not permit royalty-free redistribution of the Program by
211 | # all those who receive copies directly or indirectly through you, then
212 | # the only way you could satisfy both it and this License would be to
213 | # refrain entirely from distribution of the Program.
214 |
215 | # If any portion of this section is held invalid or unenforceable under
216 | # any particular circumstance, the balance of the section is intended to
217 | # apply and the section as a whole is intended to apply in other
218 | # circumstances.
219 |
220 | # It is not the purpose of this section to induce you to infringe any
221 | # patents or other property right claims or to contest validity of any
222 | # such claims; this section has the sole purpose of protecting the
223 | # integrity of the free software distribution system, which is
224 | # implemented by public license practices. Many people have made
225 | # generous contributions to the wide range of software distributed
226 | # through that system in reliance on consistent application of that
227 | # system; it is up to the author/donor to decide if he or she is willing
228 | # to distribute software through any other system and a licensee cannot
229 | # impose that choice.
230 |
231 | # This section is intended to make thoroughly clear what is believed to
232 | # be a consequence of the rest of this License.
233 |
234 | # 8. If the distribution and/or use of the Program is restricted in
235 | # certain countries either by patents or by copyrighted interfaces, the
236 | # original copyright holder who places the Program under this License
237 | # may add an explicit geographical distribution limitation excluding
238 | # those countries, so that distribution is permitted only in or among
239 | # countries not thus excluded. In such case, this License incorporates
240 | # the limitation as if written in the body of this License.
241 |
242 | # 9. The Free Software Foundation may publish revised and/or new versions
243 | # of the General Public License from time to time. Such new versions will
244 | # be similar in spirit to the present version, but may differ in detail to
245 | # address new problems or concerns.
246 |
247 | # Each version is given a distinguishing version number. If the Program
248 | # specifies a version number of this License which applies to it and "any
249 | # later version", you have the option of following the terms and conditions
250 | # either of that version or of any later version published by the Free
251 | # Software Foundation. If the Program does not specify a version number of
252 | # this License, you may choose any version ever published by the Free Software
253 | # Foundation.
254 |
255 | # 10. If you wish to incorporate parts of the Program into other free
256 | # programs whose distribution conditions are different, write to the author
257 | # to ask for permission. For software which is copyrighted by the Free
258 | # Software Foundation, write to the Free Software Foundation; we sometimes
259 | # make exceptions for this. Our decision will be guided by the two goals
260 | # of preserving the free status of all derivatives of our free software and
261 | # of promoting the sharing and reuse of software generally.
262 |
263 | # NO WARRANTY
264 |
265 | # 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
266 | # FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
267 | # OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
268 | # PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
269 | # OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
270 | # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
271 | # TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
272 | # PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
273 | # REPAIR OR CORRECTION.
274 |
275 | # 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
276 | # WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
277 | # REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
278 | # INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
279 | # OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
280 | # TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
281 | # YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
282 | # PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
283 | # POSSIBILITY OF SUCH DAMAGES.
284 |
285 | # END OF TERMS AND CONDITIONS
286 |
287 | # How to Apply These Terms to Your New Programs
288 |
289 | # If you develop a new program, and you want it to be of the greatest
290 | # possible use to the public, the best way to achieve this is to make it
291 | # free software which everyone can redistribute and change under these terms.
292 |
293 | # To do so, attach the following notices to the program. It is safest
294 | # to attach them to the start of each source file to most effectively
295 | # convey the exclusion of warranty; and each file should have at least
296 | # the "copyright" line and a pointer to where the full notice is found.
297 |
298 | #
299 | # Copyright (C)
300 |
301 | # This program is free software; you can redistribute it and/or modify
302 | # it under the terms of the GNU General Public License as published by
303 | # the Free Software Foundation; either version 2 of the License, or
304 | # (at your option) any later version.
305 |
306 | # This program is distributed in the hope that it will be useful,
307 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
308 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
309 | # GNU General Public License for more details.
310 |
311 | # You should have received a copy of the GNU General Public License along
312 | # with this program; if not, write to the Free Software Foundation, Inc.,
313 | # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
314 |
315 | # Also add information on how to contact you by electronic and paper mail.
316 |
317 | # If the program is interactive, make it output a short notice like this
318 | # when it starts in an interactive mode:
319 |
320 | # Gnomovision version 69, Copyright (C) year name of author
321 | # Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
322 | # This is free software, and you are welcome to redistribute it
323 | # under certain conditions; type `show c' for details.
324 |
325 | # The hypothetical commands `show w' and `show c' should show the appropriate
326 | # parts of the General Public License. Of course, the commands you use may
327 | # be called something other than `show w' and `show c'; they could even be
328 | # mouse-clicks or menu items--whatever suits your program.
329 |
330 | # You should also get your employer (if you work as a programmer) or your
331 | # school, if any, to sign a "copyright disclaimer" for the program, if
332 | # necessary. Here is a sample; alter the names:
333 |
334 | # Yoyodyne, Inc., hereby disclaims all copyright interest in the program
335 | # `Gnomovision' (which makes passes at compilers) written by James Hacker.
336 |
337 | # , 1 April 1989
338 | # Ty Coon, President of Vice
339 |
340 | # This General Public License does not permit incorporating your program into
341 | # proprietary programs. If your program is a subroutine library, you may
342 | # consider it more useful to permit linking proprietary applications with the
343 | # library. If this is what you want to do, use the GNU Lesser General
344 | # Public License instead of this License.
345 |
346 |
347 | # -*- coding: utf-8 -*-
348 | import sys
349 | import codecs
350 | import struct
351 | import json
352 | import traceback
353 | import os
354 |
355 | strings = []
356 |
357 | def GetDynamicWireFormat(data, start, end):
358 | wire_type = data[start] & 0x7
359 | firstByte = data[start]
360 | if (firstByte & 0x80) == 0:
361 | field_number = (firstByte >> 3)
362 | return (start+1, wire_type, field_number)
363 | else:
364 | byteList = []
365 | pos = 0
366 | while True:
367 | if start+pos >= end:
368 | return (None, None, None)
369 | oneByte = data[start+pos]
370 | byteList.append(oneByte & 0x7F)
371 | pos = pos + 1
372 | if oneByte & 0x80 == 0x0:
373 | break;
374 |
375 | newStart = start + pos
376 |
377 | index = len(byteList) - 1
378 | field_number = 0
379 | while index >= 0:
380 | field_number = (field_number << 0x7) + byteList[index]
381 | index = index - 1
382 |
383 | field_number = (field_number >> 3)
384 | return (newStart, wire_type, field_number)
385 |
386 |
387 |
388 | #return (num, newStart, success)
389 | def RetrieveInt(data, start, end):
390 | pos = 0
391 | byteList = []
392 | while True:
393 | if start+pos >= end:
394 | return (None, None, False)
395 | oneByte = data[start+pos]
396 | byteList.append(oneByte & 0x7F)
397 | pos = pos + 1
398 | if oneByte & 0x80 == 0x0:
399 | break;
400 |
401 | newStart = start + pos
402 |
403 | index = len(byteList) - 1
404 | num = 0
405 | while index >= 0:
406 | num = (num << 0x7) + byteList[index]
407 | index = index - 1
408 | return (num, newStart, True)
409 |
410 |
411 | def ParseRepeatedField(data, start, end, message, depth = 0):
412 | while start < end:
413 | (num, start, success) = RetrieveInt(data, start, end)
414 | if success == False:
415 | return False
416 | message.append(num)
417 | return True
418 |
419 | def ParseData(data, start, end, messages, depth = 0):
420 | global strings
421 | #print strings
422 | ordinary = 0
423 | while start < end:
424 | (start, wire_type, field_number) = GetDynamicWireFormat(data, start, end)
425 | if start == None:
426 | return False
427 |
428 | if wire_type == 0x00:#Varint
429 | #(num, start, success) = RetrieveInt(data, start+1, end)
430 | (num, start, success) = RetrieveInt(data, start, end)
431 | if success == False:
432 | return False
433 |
434 | if depth != 0:
435 | strings.append('\t'*depth)
436 | strings.append("(%d) Varint: %d\n" % (field_number, num))
437 | messages['%02d:%02d:Varint' % (field_number,ordinary)] = num
438 | ordinary = ordinary + 1
439 |
440 | elif wire_type == 0x01:#64-bit
441 | num = 0
442 | pos = 7
443 | while pos >= 0:
444 | #if start+1+pos >= end:
445 | if start+pos >= end:
446 | return False
447 | #num = (num << 8) + ord(data[start+1+pos])
448 | num = (num << 8) + data[start+pos]
449 | pos = pos - 1
450 |
451 | #start = start + 9
452 | start = start + 8
453 | try:
454 | floatNum = struct.unpack('d',struct.pack('q',hex(num),16))
455 | floatNum = floatNum[0]
456 | except:
457 | floatNum = None
458 |
459 | if depth != 0:
460 | strings.append('\t'*depth)
461 | if floatNum != None:
462 | strings.append("(%d) 64-bit: 0x%x / %f\n" % (field_number, num, floatNum))
463 | messages['%02d:%02d:64-bit' % (field_number,ordinary)] = floatNum
464 | else:
465 | strings.append("(%d) 64-bit: 0x%x\n" % (field_number, num))
466 | messages['%02d:%02d:64-bit' % (field_number,ordinary)] = num
467 |
468 |
469 | ordinary = ordinary + 1
470 |
471 |
472 | elif wire_type == 0x02:#Length-delimited
473 | curStrIndex = len(strings)
474 | #(stringLen, start, success) = RetrieveInt(data, start+1, end)
475 | (stringLen, start, success) = RetrieveInt(data, start, end)
476 | if success == False:
477 | return False
478 | #stringLen = ord(data[start+1])
479 | if depth != 0:
480 | strings.append('\t'*depth)
481 | strings.append("(%d) embedded message:\n" % field_number)
482 | messages['%02d:%02d:embedded message' % (field_number, ordinary)] = {}
483 | if start+stringLen > end:
484 | del strings[curStrIndex + 1:] #pop failed result
485 | messages.pop('%02d:%02d:embedded message' % (field_number, ordinary), None)
486 | return False
487 |
488 | ret = ParseData(data, start, start+stringLen, messages['%02d:%02d:embedded message' % (field_number, ordinary)], depth+1)
489 | #print '%d:%d:embedded message' % (field_number, ordinary)
490 | if ret == False:
491 | del strings[curStrIndex + 1:] #pop failed result
492 | #print 'pop: %d:%d:embedded message' % (field_number, ordinary)
493 | messages.pop('%02d:%02d:embedded message' % (field_number, ordinary), None)
494 | #print messages
495 | if depth != 0:
496 | strings.append('\t'*depth)
497 |
498 | strings.append("(%d) repeated:\n" % field_number)
499 | try:
500 | # data[start:start+stringLen].decode('utf-8').encode('utf-8')
501 | strings.append("(%d) string: %s\n" % (field_number, data[start:start+stringLen].decode('utf-8')))
502 | messages['%02d:%02d:string' % (field_number, ordinary)] = data[start:start+stringLen].decode('utf-8')
503 | except:
504 | if depth != 0:
505 | strings.append('\t'*depth)
506 |
507 | strings.append("(%d) repeated:\n" % field_number)
508 | messages['%02d:%02d:repeated' % (field_number, ordinary)] = []
509 | ret = ParseRepeatedField(data, start, start+stringLen, messages['%02d:%02d:repeated' % (field_number, ordinary)], depth+1)
510 | if ret == False:
511 | del strings[curStrIndex + 1:] #pop failed result
512 | messages.pop('%02d:%02d:repeated' % (field_number, ordinary), None)
513 | #print traceback.format_exc()
514 | hexStr = ['0x%x' % x for x in data[start:start+stringLen]]
515 | hexStr = ':'.join(hexStr)
516 | strings.append("(%d) bytes: %s\n" % (field_number, hexStr))
517 | messages['%02d:%02d:bytes' % (field_number, ordinary)] = hexStr
518 |
519 | ordinary = ordinary + 1
520 | #start = start+2+stringLen
521 | start = start+stringLen
522 |
523 | elif wire_type == 0x05:#32-bit
524 | num = 0
525 | pos = 3
526 | while pos >= 0:
527 |
528 | #if start+1+pos >= end:
529 | if start+pos >= end:
530 | return False
531 | #num = (num << 8) + ord(data[start+1+pos])
532 | num = (num << 8) + data[start+pos]
533 | pos = pos - 1
534 |
535 | #start = start + 5
536 | start = start + 4
537 | try:
538 | floatNum = struct.unpack('f',struct.pack('i',hex(num)))
539 | floatNum = floatNum[0]
540 | except:
541 | floatNum = None
542 |
543 |
544 | if depth != 0:
545 | strings.append('\t'*depth)
546 | if floatNum != None:
547 | strings.append("(%d) 32-bit: 0x%x / %f\n" % (field_number, num, floatNum))
548 | messages['%02d:%02d:32-bit' % (field_number,ordinary)] = floatNum
549 | else:
550 | strings.append("(%d) 32-bit: 0x%x\n" % (field_number, num))
551 | messages['%02d:%02d:32-bit' % (field_number,ordinary)] = num
552 |
553 | ordinary = ordinary + 1
554 |
555 |
556 | else:
557 | return False
558 |
559 | return True
560 |
561 | def ParseProto(fileName):
562 | data = open(fileName, "rb").read()
563 | size = len(data)
564 |
565 | messages = {}
566 | ParseData(data, 0, size, messages)
567 |
568 | return messages
569 |
570 | def GenValueList(value):
571 | valueList = []
572 | #while value > 0:
573 | while value >= 0:
574 | oneByte = (value & 0x7F)
575 | value = (value >> 0x7)
576 | if value > 0:
577 | oneByte |= 0x80
578 | valueList.append(oneByte)
579 | if value == 0:
580 | break
581 |
582 | return valueList
583 |
584 |
585 | def WriteValue(value, output):
586 | byteWritten = 0
587 | #while value > 0:
588 | while value >= 0:
589 | oneByte = (value & 0x7F)
590 | value = (value >> 0x7)
591 | if value > 0:
592 | oneByte |= 0x80
593 | output.append(oneByte)
594 | byteWritten += 1
595 | if value == 0:
596 | break
597 |
598 | return byteWritten
599 |
600 | def WriteVarint(field_number, value, output):
601 | byteWritten = 0
602 | wireFormat = (field_number << 3) | 0x00
603 | #output.append(wireFormat)
604 | #byteWritten += 1
605 | byteWritten += WriteValue(wireFormat, output)
606 | #while value > 0:
607 | while value >= 0:
608 | oneByte = (value & 0x7F)
609 | value = (value >> 0x7)
610 | if value > 0:
611 | oneByte |= 0x80
612 | output.append(oneByte)
613 | byteWritten += 1
614 | if value == 0:
615 | break
616 |
617 | return byteWritten
618 |
619 | def Write64bitFloat(field_number, value, output):
620 | byteWritten = 0
621 | wireFormat = (field_number << 3) | 0x01
622 | #output.append(wireFormat)
623 | #byteWritten += 1
624 | byteWritten += WriteValue(wireFormat, output)
625 |
626 | bytesStr = struct.pack('d', value)
627 | n = 2
628 | bytesList = [bytesStr[i:i+n] for i in range(0, len(bytesStr), n)]
629 | #i = len(bytesList) - 1
630 | #while i >= 0:
631 | # output.append(int(bytesList[i],16))
632 | # byteWritten += 1
633 | # i -= 1
634 | for i in range(0,len(bytesList)):
635 | output.append(int(bytesList[i],16))
636 | byteWritten += 1
637 |
638 | return byteWritten
639 |
640 | def Write64bit(field_number, value, output):
641 | byteWritten = 0
642 | wireFormat = (field_number << 3) | 0x01
643 | byteWritten += WriteValue(wireFormat, output)
644 | #output.append(wireFormat)
645 | #byteWritten += 1
646 |
647 | for i in range(0,8):
648 | output.append(value & 0xFF)
649 | value = (value >> 8)
650 | byteWritten += 1
651 |
652 | return byteWritten
653 |
654 | def Write32bitFloat(field_number, value, output):
655 | byteWritten = 0
656 | wireFormat = (field_number << 3) | 0x05
657 | #output.append(wireFormat)
658 | #byteWritten += 1
659 | byteWritten += WriteValue(wireFormat, output)
660 |
661 | bytesStr = struct.pack('f', value)
662 | n = 2
663 | bytesList = [bytesStr[i:i+n] for i in range(0, len(bytesStr), n)]
664 | #i = len(bytesList) - 1
665 | #while i >= 0:
666 | # output.append(int(bytesList[i],16))
667 | # byteWritten += 1
668 | # i -= 1
669 | for i in range(0,len(bytesList)):
670 | output.append(bytesList[i])
671 | byteWritten += 1
672 |
673 |
674 | return byteWritten
675 |
676 | def Write32bit(field_number, value, output):
677 | byteWritten = 0
678 | wireFormat = (field_number << 3) | 0x05
679 | #output.append(wireFormat)
680 | #byteWritten += 1
681 | byteWritten += WriteValue(wireFormat, output)
682 |
683 | for i in range(0,4):
684 | output.append(value & 0xFF)
685 | value = (value >> 8)
686 | byteWritten += 1
687 |
688 | return byteWritten
689 |
690 | def WriteRepeatedField(message, output):
691 | byteWritten = 0
692 | for v in message:
693 | byteWritten += WriteValue(v, output)
694 | return byteWritten
695 |
696 |
697 | def ReEncode(messages, output):
698 | byteWritten = 0
699 | #for key in sorted(messages.iterkeys(), key= lambda x: int(x.split(':')[0]+x.split(':')[1])):
700 | for key in sorted(iter(messages.keys()), key= lambda x: int(x.split(':')[1])):
701 | keyList = key.split(':')
702 | field_number = int(keyList[0])
703 | wire_type = keyList[2]
704 | value = messages[key]
705 |
706 | if wire_type == 'Varint':
707 | byteWritten += WriteVarint(field_number, value, output)
708 | elif wire_type == '32-bit':
709 | if type(value) == type(float(1.0)):
710 | byteWritten += Write32bitFloat(field_number, value, output)
711 | else:
712 | byteWritten += Write32bit(field_number, value, output)
713 | elif wire_type == '64-bit':
714 | if type(value) == type(float(1.0)):
715 | byteWritten += Write64bitFloat(field_number, value, output)
716 | else:
717 | byteWritten += Write64bit(field_number, value, output)
718 | elif wire_type == 'embedded message':
719 | wireFormat = (field_number << 3) | 0x02
720 | byteWritten += WriteValue(wireFormat, output)
721 | index = len(output)
722 | tmpByteWritten = ReEncode(messages[key], output)
723 | valueList = GenValueList(tmpByteWritten)
724 | listLen = len(valueList)
725 | for i in range(0,listLen):
726 | output.insert(index, valueList[i])
727 | index += 1
728 | #output[index] = tmpByteWritten
729 | #print "output:", output
730 | byteWritten += tmpByteWritten + listLen
731 | elif wire_type == 'repeated':
732 | wireFormat = (field_number << 3) | 0x02
733 | byteWritten += WriteValue(wireFormat, output)
734 | index = len(output)
735 | tmpByteWritten = WriteRepeatedField(messages[key], output)
736 | valueList = GenValueList(tmpByteWritten)
737 | listLen = len(valueList)
738 | for i in range(0,listLen):
739 | output.insert(index, valueList[i])
740 | index += 1
741 | #output[index] = tmpByteWritten
742 | #print "output:", output
743 | byteWritten += tmpByteWritten + listLen
744 | elif wire_type == 'string':
745 | wireFormat = (field_number << 3) | 0x02
746 | byteWritten += WriteValue(wireFormat, output)
747 |
748 | # bytesStr = [int(elem.encode("hex"),16) for elem in messages[key].encode('utf-8')]
749 | bytesStr = [int(elem) for elem in messages[key].encode('utf-8')]
750 |
751 | byteWritten += WriteValue(len(bytesStr),output)
752 |
753 | output.extend(bytesStr)
754 | byteWritten += len(bytesStr)
755 | elif wire_type == 'bytes':
756 | wireFormat = (field_number << 3) | 0x02
757 | byteWritten += WriteValue(wireFormat, output)
758 |
759 | bytesStr = [int(byte,16) for byte in messages[key].split(':')]
760 | byteWritten += WriteValue(len(bytesStr),output)
761 |
762 | output.extend(bytesStr)
763 | byteWritten += len(bytesStr)
764 |
765 |
766 | return byteWritten
767 |
768 |
769 | def SaveModification(messages, fileName):
770 | output = list()
771 | ReEncode(messages, output)
772 | f = open(fileName, 'wb')
773 | f.write(bytearray(output))
774 | f.close()
775 |
776 |
777 | if __name__ == "__main__":
778 | if sys.argv[1] == "dec":
779 | messages = ParseProto('tmp.pb')
780 |
781 | f = open('tmp.json', 'wb')
782 | json.dump(messages, f, indent=4, sort_keys=True, ensure_ascii=False)
783 | f.close()
784 |
785 | #for str in strings:
786 | # try:
787 | # print str,
788 | # except:
789 | # pass
790 | f.close()
791 |
792 | elif sys.argv[1] == "enc":
793 |
794 | f = codecs.open('tmp.json', 'r', 'utf-8')
795 | messages = json.load(f, encoding='utf-8')
796 | f.close()
797 |
798 | SaveModification(messages, "tmp.pb")
799 |
800 | else:
801 | messages = ParseProto(sys.argv[1])
802 |
803 | print(json.dumps(messages, indent=4, sort_keys=True, ensure_ascii=False))
804 |
805 | # modify any field you like
806 | #messages['01:00:embedded message']['01:00:string'] = "あなた"
807 |
808 | # dump and reload the 'messages' json objects to ensure it being utf-8 encoded
809 | f = open('tmp.json', 'w', encoding='utf-8')
810 | json.dump(messages, f, indent=4, sort_keys=True, ensure_ascii=False)
811 | f.close()
812 | f = codecs.open('tmp.json', 'r', 'utf-8')
813 | messages = json.load(f, encoding='utf-8')
814 | f.close()
815 | os.remove('tmp.json')
816 |
817 | # the modification is saved in file named "modified"
818 | #SaveModification(messages, "modified")
819 |
820 |
--------------------------------------------------------------------------------
/run.PNG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abrignoni/iOS-KnowledgeC-StructuredMetadata-Bplists/9ef8a3217c484dfe0a6ce85e4a65b4bfc59f552a/run.PNG
--------------------------------------------------------------------------------