def scan(self): """ Walk entire directory, compile mapping path relative to source_dir -> digest and other data """ file_entries = {} # rule_debug_fmt = "rule: {0}, path: {1}, relative_path: {2}" for root, dirs, filenames in os.walk(self.app_dir): # log.debug("root: {0}".format(root)) for filename in filenames: rule, path, relative_path = self.get_rule_and_paths( root, filename) # log.debug(rule_debug_fmt.format(rule, path, relative_path)) # specifically ignore the CodeResources symlink in base directory if it exists (iOS 11+ fix) if relative_path == "CodeResources" and os.path.islink(path): continue if rule.is_exclusion(): continue if rule.is_omitted() and self.respect_omissions is True: continue if self.app_path == path: continue # in the case of symlinks, we don't calculate the hash but rather add a key for it being a symlink if os.path.islink(path): # omit symlinks from files, leave in files2 if not self.respect_omissions: continue val = {'symlink': os.readlink(path)} else: # the Data element in plists is base64-encoded val = {'hash': plistlib.Data(get_hash_binary(path))} if self.include_sha256: val['hash2'] = plistlib.Data( get_hash_binary(path, 'sha256')) if rule.is_optional(): val['optional'] = True if len(val) == 1 and 'hash' in val: file_entries[relative_path] = val['hash'] else: file_entries[relative_path] = val for dirname in dirs: rule, path, relative_path = self.get_rule_and_paths( root, dirname) if rule.is_nested() and '.' not in path: dirs.remove(dirname) continue if relative_path == OUTPUT_DIRECTORY: dirs.remove(dirname) return file_entries
def pair(self): self.DevicePublicKey = self.getValue("", "DevicePublicKey") if self.DevicePublicKey == '': return print "Got device public key" print "Creating host key & certificate" certPem, privateKeyPem, DeviceCertificate = ca_do_everything( self.DevicePublicKey) pair_record = { "DevicePublicKey": plistlib.Data(self.DevicePublicKey), "DeviceCertificate": plistlib.Data(DeviceCertificate), "HostCertificate": plistlib.Data(certPem), "HostID": self.hostID, "RootCertificate": plistlib.Data(certPem), "SystemBUID": "30142955-444094379208051516" } Pair = {"Request": "Pair", "PairRecord": pair_record} self.c.sendPlist(Pair) Pair = self.c.recvPlist() if Pair and Pair.get("Result") == "Success" or Pair.has_key( "EscrowBag"): #print "Pairing OK" pair_record["HostPrivateKey"] = plistlib.Data(privateKeyPem) if Pair.has_key("EscrowBag"): pair_record["EscrowBag"] = Pair["EscrowBag"] writeHomeFile(HOMEFOLDER, "%s.plist" % self.identifier, plistlib.writePlistToString(pair_record)) return True print "Pairing error", Pair return False
def pair(self): print "Creating host key & certificate" hostCertificate, hostPrivateKey, deviceCertificate = generateCertificates( self.devicePublicKey) pair_record = { 'DevicePublicKey': plistlib.Data(self.devicePublicKey), 'DeviceCertificate': plistlib.Data(deviceCertificate), 'HostCertificate': plistlib.Data(hostCertificate), 'HostPrivateKey': plistlib.Data(hostPrivateKey), 'HostID': self.hostID, 'RootCertificate': plistlib.Data(hostCertificate), 'SystemBUID': '30142955-444094379208051516' } Pair = self.service.sendRequest({ 'Request': 'Pair', 'PairRecord': pair_record }) if self.osVersion[0] == '7' and Pair.get( 'Error') == 'PasswordProtected': raise NotTrustedError if Pair and Pair.get('Result') == 'Success' or 'EscrowBag' in Pair: if 'EscrowBag' in Pair: pair_record['EscrowBag'] = Pair['EscrowBag'] writeHomeFile(HOMEFOLDER, '%s.plist' % self.udid, plistlib.writePlistToString(pair_record)) else: raise PairingError
def main(): with open('Ubuntu-R.ttf', 'r') as f: ur = f.read() with open('Ubuntu-RI.ttf', 'r') as f: uri = f.read() # Create the configuration profile: unique_id = uuid.uuid4().urn[9:].upper() config = {'PayloadContent': [{ 'Font': plistlib.Data(ur), 'PayloadIdentifier': 'org.scj643.font.' + uuid1, 'PayloadOrganization': 'scj643', 'PayloadType': 'com.apple.font', 'PayloadUUID': uuid1, 'PayloadVersion': 1}, {'Font': plistlib.Data(uri), 'PayloadIdentifier': 'org.scj643.font.' + uuid1, 'PayloadOrganization': 'scj643', 'PayloadType': 'com.apple.font', 'PayloadUUID': uuid2, 'PayloadVersion': 1} ], 'PayloadDescription': 'Ubuntu Font', 'PayloadDisplayName': 'Ubuntu Font', 'PayloadIdentifier': 'org.scj643.font.' + uuid1, 'PayloadOrganization': 'scj643', 'PayloadRemovalDisallowed': False, 'PayloadType': 'Configuration', 'PayloadUUID': unique_id, 'PayloadVersion': 1} run_server(config)
def create_info_plist(self): root_node = self.lockdown.allValues info = {"BuildVersion": root_node.get("BuildVersion") or "", "DeviceName": root_node.get("DeviceName") or "", "Display Name": root_node.get("DeviceName") or "", "GUID": "---", "ProductType": root_node.get("ProductType") or "", "ProductVersion": root_node.get("ProductVersion") or "", "Serial Number": root_node.get("SerialNumber") or "", "Unique Identifier": self.udid.upper(), "Target Identifier": self.udid, "Target Type": "Device", "iTunes Version": "10.0.1" } info["ICCID"] = root_node.get("IntegratedCircuitCardIdentity") or "" info["IMEI"] = root_node.get("InternationalMobileEquipmentIdentity") or "" info["Last Backup Date"] = datetime.datetime.now() afc = AFCClient(self.lockdown) iTunesFilesDict = {} iTunesFiles = afc.read_directory("/iTunes_Control/iTunes/") for i in iTunesFiles: data = afc.get_file_contents("/iTunes_Control/iTunes/" + i) if data: iTunesFilesDict[i] = plistlib.Data(data) info["iTunesFiles"] = iTunesFilesDict iBooksData2 = afc.get_file_contents("/Books/iBooksData2.plist") if iBooksData2: info["iBooks Data 2"] = plistlib.Data(iBooksData2) info["iTunes Settings"] = self.lockdown.getValue("com.apple.iTunes") self.logger.info("Creating: %s", os.path.join(self.udid,"Info.plist")) self.write_file(os.path.join(self.udid,"Info.plist"), plistlib.writePlistToString(info))
def pair(self): self.DevicePublicKey = self.getValue("", "DevicePublicKey") if self.DevicePublicKey == '': print "Unable to retreive DevicePublicKey" return False print "Creating host key & certificate" certPem, privateKeyPem, DeviceCertificate = ca_do_everything(self.DevicePublicKey) pair_record = {"DevicePublicKey": plistlib.Data(self.DevicePublicKey), "DeviceCertificate": plistlib.Data(DeviceCertificate), "HostCertificate": plistlib.Data(certPem), "HostID": self.hostID, "RootCertificate": plistlib.Data(certPem), "SystemBUID": "30142955-444094379208051516" } pair = {"Label": self.label, "Request": "Pair", "PairRecord": pair_record} self.c.sendPlist(pair) pair = self.c.recvPlist() if pair and pair.get("Result") == "Success" or pair.has_key("EscrowBag"): pair_record["HostPrivateKey"] = plistlib.Data(privateKeyPem) pair_record["EscrowBag"] = pair.get("EscrowBag") writeHomeFile(HOMEFOLDER, "%s.plist" % self.identifier, plistlib.writePlistToString(pair_record)) self.paired = True return True elif pair and pair.get("Error") == "PasswordProtected": self.c.close() raise NotTrustedError else: print pair.get("Error") self.c.close() raise PairingError
def __init__(self, *args, **kwargs): super(io_dict_plist_test_case, self).__init__(*args, **kwargs) if six.PY2: self._dict = dict( aString='Doodah', aList=['A', 'B', 12, 32.1, [1, 2, 3]], aFloat=0.1, anInt=728, aDict=dict( anotherString='<hello & hi there!>', aThirdString=u'M\xe4ssig, Ma\xdf', aTrueValue=True, aFalseValue=False, ), someData=plistlib.Data('<binary gunk>'), someMoreData=plistlib.Data('<lots of binary gunk>' * 10), aDate=dt.datetime(1985, 4, 3, 23, 55) # dt.datetime.fromtimestamp(481413300), ) else: self._dict = dict( aString='Doodah', aList=['A', 'B', 12, 32.1, [1, 2, 3]], aFloat=0.1, anInt=728, aDict=dict( anotherString='<hello & hi there!>', aThirdString='M\xe4ssig, Ma\xdf', aTrueValue=True, aFalseValue=False, ), someData=bytes('<binary gunk>', encoding='utf-8'), someMoreData=bytes('<lots of binary gunk>' * 10, encoding='utf-8'), aDate=dt.datetime(1985, 4, 3, 23, 55) # dt.datetime.fromtimestamp(481413300), ) # self._dict = { # 'aString': 'Doodah', # 'aList': ['A', 'B', 12, 32.1, [1, 2, 3]], # 'aFloat': 0.1, # 'anInt': 728, # 'aDict': { # 'anotherString': '<hello & hi there!>', # 'aThirdString': 'M\xe4ssig, Ma\xdf', # 'aTrueValue': True, # 'aFalseValue': False, # }, # 'someData': b'<binary gunk>', # 'someMoreData': b'<lots of binary gunk>' * 10, # 'aDate': dt.datetime.fromtimestamp(481406100), # } self._plist = """
def create_info_plist(self): root_node = self.lockdown.getValue() info = { "BuildVersion": root_node["BuildVersion"], "DeviceName": root_node["DeviceName"], "Display Name": root_node["DeviceName"], "GUID": "---", "ProductType": root_node["ProductType"], "ProductVersion": root_node["ProductVersion"], "Serial Number": root_node["SerialNumber"], "Unique Identifier": self.udid.upper(), "Target Identifier": self.udid, "Target Type": "Device", "iTunes Version": "10.0.1" } if root_node.has_key("IntegratedCircuitCardIdentity"): info["ICCID"] = root_node["IntegratedCircuitCardIdentity"] if root_node.has_key("InternationalMobileEquipmentIdentity"): info["IMEI"] = root_node["InternationalMobileEquipmentIdentity"] info["Last Backup Date"] = datetime.datetime.now() iTunesFiles = [ "ApertureAlbumPrefs", "IC-Info.sidb", "IC-Info.sidv", "PhotosFolderAlbums", "PhotosFolderName", "PhotosFolderPrefs", "iPhotoAlbumPrefs", "iTunesApplicationIDs", "iTunesPrefs", "iTunesPrefs.plist" ] afc = AFCClient(self.lockdown) iTunesFilesDict = {} iTunesFiles = afc.read_directory("/iTunes_Control/iTunes/") #print iTunesFiles for i in iTunesFiles: data = afc.get_file_contents("/iTunes_Control/iTunes/" + i) if data: iTunesFilesDict[i] = plistlib.Data(data) info["iTunesFiles"] = iTunesFilesDict iBooksData2 = afc.get_file_contents("/Books/iBooksData2.plist") if iBooksData2: info["iBooks Data 2"] = plistlib.Data(iBooksData2) #pprint(info) print self.lockdown.getValue("com.apple.iTunes") info["iTunes Settings"] = self.lockdown.getValue("com.apple.iTunes") #self.backupPath = self.udid #if not os.path.isdir(self.backupPath): # os.makedirs(self.backupPath) #print info #raw_input() print "Creating %s" % os.path.join(self.udid, "Info.plist") self.write_file(os.path.join(self.udid, "Info.plist"), plistlib.writePlistToString(info))
def InstallProfile(self, s): #s = plistlib.writePlistToString(payload) self.service.sendPlist({ "RequestType": "InstallProfile", "Payload": plistlib.Data(s) }) return self.service.recvPlist()
def test_io_deprecated(self): pl_in = { 'key': 42, 'sub': { 'key': 9, 'alt': 'value', 'data': b'buffer' } } pl_out = plistlib._InternalDict({ 'key': 42, 'sub': plistlib._InternalDict({ 'key': 9, 'alt': 'value', 'data': plistlib.Data(b'buffer') }) }) self.addCleanup(support.unlink, support.TESTFN) with self.assertWarns(DeprecationWarning): plistlib.writePlist(pl_in, support.TESTFN) with self.assertWarns(DeprecationWarning): pl2 = plistlib.readPlist(support.TESTFN) self.assertEqual(pl_out, pl2) os.unlink(support.TESTFN) with open(support.TESTFN, 'wb') as fp: with self.assertWarns(DeprecationWarning): plistlib.writePlist(pl_in, fp) with open(support.TESTFN, 'rb') as fp: with self.assertWarns(DeprecationWarning): pl2 = plistlib.readPlist(fp) self.assertEqual(pl_out, pl2)
def decrypt_directory(indir, outdir, re_encrypt=False): '''Decrypt the OmniFocus data in indir, writing the result to outdir. Prompts for a passphrase.''' files = posix.listdir(indir) indir = os.path.abspath(indir) if outdir: outdir = os.path.abspath(outdir) if metadata_filename not in files: raise EnvironmentError('Expected to find %r in %r' % (metadata_filename, indir)) encryptionMetadata = DocumentKey.parse_metadata( open(os.path.join(indir, metadata_filename), 'rb')) metadataKey = DocumentKey.use_passphrase( encryptionMetadata, getpass.getpass(prompt="Passphrase: ")) docKey = DocumentKey(encryptionMetadata.get('key').data, unwrapping_key=metadataKey) for secret in docKey.secrets: secret.print() workdir = outdir if outdir is not None: posix.mkdir(outdir) if re_encrypt: workdir = tempfile.mkdtemp() basename = os.path.basename(indir) for dirpath, dirnames, filenames in os.walk(indir): for datafile in filenames: inpath = os.path.join(dirpath, datafile) if workdir is not None: outpath = inpath.replace(indir, workdir) if datafile == metadata_filename: continue display = "%s/%s" % (os.path.basename(dirpath), datafile) if os.path.basename( dirpath) != basename else datafile if outdir is not None: print('Decrypting %r' % (display, )) if not os.path.exists(os.path.split(outpath)[0]): os.makedirs(os.path.split(outpath)[0]) with open(os.path.join(indir, inpath), "rb") as infp, \ open(os.path.join(workdir, outpath), "wb") as outfp: docKey.decrypt_file(datafile, infp, outfp) else: print('Reading %r' % (display, )) with open(os.path.join(indir, inpath), "rb") as infp: docKey.decrypt_file(datafile, infp, None) if re_encrypt and outdir is not None: print() print("Re-Encrypt the database\n") newKey = docKey.get_key_of_type(ActiveAES_CTR_HMAC, True) encryptionMetadata['key'] = plistlib.Data( docKey.wrapped_secrets(metadataKey)) encrypt_directory(encryptionMetadata, docKey, workdir, outdir) # We've created a tempdirectory lets clean it up import shutil shutil.rmtree(workdir)
def aes(self, data, keyMask, mode): return self.send_req({"Request":"AES", "input": plistlib.Data(data), "keyMask": keyMask, "mode": mode, "bits": 128 })
def webclip(self, url, label, fullscreen=None, ident=uid(), icon=None, precomposed=True, removable=True, **kwargs): ident = 'webclip.' + ident returns = { 'PayloadType': 'com.apple.webClip.managed', 'URL': url, 'Label': label, 'IsRemovable': removable } if icon and imgsupport: if type(icon) == str: img = Image.open(icon) else: img = icon data_buffer = BytesIO() img.save(data_buffer, 'PNG') icon_data = data_buffer.getvalue() returns['Icon'] = plistlib.Data(icon_data) returns['Precomposed'] = typehandle(precomposed, 'precomposed', rtype=bool) returns['FullScreen'] = typehandle(fullscreen, 'fullscreen', rtype=bool) returns = self.common(returns, ident, kwargs) striped = strip(returns) self.profile += [striped]
def test_bytes_deprecated(self): pl = { 'key': 42, 'sub': { 'key': 9, 'alt': 'value', 'data': b'buffer', } } with self.assertWarns(DeprecationWarning): data = plistlib.writePlistToBytes(pl) with self.assertWarns(DeprecationWarning): pl2 = plistlib.readPlistFromBytes(data) self.assertIsInstance(pl2, dict) self.assertEqual( pl2, dict(key=42, sub=dict( key=9, alt='value', data=plistlib.Data(b'buffer'), ))) with self.assertWarns(DeprecationWarning): data2 = plistlib.writePlistToBytes(pl2) self.assertEqual(data, data2)
def main(): console.alert( 'Shortcut Generator', "This script adds a shortcut icon to running the MetreiOS app on your homepage. Your default browser MUST be Safari", 'Continue') # Fetch config json root_dir = os.path.abspath(os.path.expanduser('~Documents/' + 'MetreiOS')) with open('../metre_ios_install_config.json') as f: configs = json.load(f) currentversion = configs['git_repo'] label = 'MetreiOS' url = 'pythonista3://MetreiOS' + '/' + currentversion + '/MainMetre.py?action=run' img = Image.open( BytesIO( urllib.request.urlopen( "https://drive.google.com/uc?export=view&id=1--lLdK8dHtBOBwsZyFu0g3TRIjhA_0XK" ).read())) console.show_activity('Preparing Configuration profile...') data_buffer = BytesIO() img.save(data_buffer, 'PNG') icon_data = data_buffer.getvalue() unique_id = uuid.uuid4().urn[9:].upper() config = { 'PayloadContent': [{ 'FullScreen': True, 'Icon': plistlib.Data(icon_data), 'IsRemovable': True, 'Label': label, 'PayloadDescription': 'Configures Web Clip', 'PayloadDisplayName': label, 'PayloadIdentifier': 'com.omz-software.shortcut.' + unique_id, 'PayloadOrganization': 'omz:software', 'PayloadType': 'com.apple.webClip.managed', 'PayloadUUID': unique_id, 'PayloadVersion': 1, 'Precomposed': True, 'URL': url }], 'PayloadDescription': label, 'PayloadDisplayName': label + ' (Shortcut)', 'PayloadIdentifier': 'com.omz-software.shortcut.' + unique_id, 'PayloadOrganization': 'omz:software', 'PayloadRemovalDisallowed': False, 'PayloadType': 'Configuration', 'PayloadUUID': unique_id, 'PayloadVersion': 1 } console.hide_activity() run_server(config)
def RemoveProfile(self, ident): profiles = self.GetProfileList() if not profiles: return if not profiles["ProfileMetadata"].has_key(ident): self.logger.info("Trying to remove not installed profile %s", ident) return meta = profiles["ProfileMetadata"][ident] pprint(meta) data = plistlib.writePlistToString({ "PayloadType": "Configuration", "PayloadIdentifier": ident, "PayloadUUID": meta["PayloadUUID"], "PayloadVersion": meta["PayloadVersion"] }) self.service.sendPlist({ "RequestType": "RemoveProfile", "ProfileIdentifier": plistlib.Data(data) }) return self.service.recvPlist()
def _get_icon(self) -> Dict[str, Any]: # todo: change me return { 'WFWorkflowIconGlyphNumber': 59511, 'WFWorkflowIconImageData': plistlib.Data(b''), 'WFWorkflowIconStartColor': 431817727, }
def scan(self): """ Walk entire directory, compile mapping path relative to source_dir -> digest and other data """ file_entries = {} # rule_debug_fmt = "rule: {0}, path: {1}, relative_path: {2}" for root, dirs, filenames in os.walk(self.app_dir): # log.debug("root: {0}".format(root)) for filename in filenames: rule, path, relative_path = self.get_rule_and_paths(root, filename) # log.debug(rule_debug_fmt.format(rule, path, relative_path)) if rule.is_exclusion(): continue if rule.is_omitted() and self.respect_omissions is True: continue if self.app_path == path: continue # the Data element in plists is base64-encoded val = {'hash': plistlib.Data(get_hash_binary(path, 'sha1')), 'hash2': plistlib.Data(get_hash_binary(path, 'sha256'))} if rule.is_optional(): val['optional'] = True if len(val) == 1 and 'hash' in val: file_entries[relative_path] = val['hash'] else: file_entries[relative_path] = val for dirname in dirs: rule, path, relative_path = self.get_rule_and_paths(root, dirname) if rule.is_nested() and '.' not in path: dirs.remove(dirname) continue if relative_path == OUTPUT_DIRECTORY: dirs.remove(dirname) return file_entries
def main(): console.alert( 'Shortcut Generator', 'This script adds a "Webclip" shortcut to your homescreen. The shortcut can be used to open a web page in full-screen mode, or to launch a custom URL (e.g. a third-party app). You\'ll be asked for a title, a URL, and an icon (from your camera roll).', 'Continue') label = console.input_alert( 'Shortcut Title', 'Please enter a short title for the homescreen icon.', '', 'Continue') if not label: return url = console.input_alert( 'Shortcut URL', 'Please enter the full URL that the shortcut should launch.', '', 'Continue') if not url: return icon = photos.pick_image() if not icon: return console.show_activity('Preparing Configuration profile...') data_buffer = BytesIO() icon.save(data_buffer, 'PNG') icon_data = data_buffer.getvalue() unique_id = uuid.uuid4().urn[9:].upper() config = { 'PayloadContent': [{ 'FullScreen': True, 'Icon': plistlib.Data(icon_data), 'IsRemovable': True, 'Label': label, 'PayloadDescription': 'Configures Web Clip', 'PayloadDisplayName': label, 'PayloadIdentifier': 'com.omz-software.shortcut.' + unique_id, 'PayloadOrganization': 'omz:software', 'PayloadType': 'com.apple.webClip.managed', 'PayloadUUID': unique_id, 'PayloadVersion': 1, 'Precomposed': True, 'URL': url }], 'PayloadDescription': label, 'PayloadDisplayName': label + ' (Shortcut)', 'PayloadIdentifier': 'com.omz-software.shortcut.' + unique_id, 'PayloadOrganization': 'omz:software', 'PayloadRemovalDisallowed': False, 'PayloadType': 'Configuration', 'PayloadUUID': unique_id, 'PayloadVersion': 1 } console.hide_activity() run_server(config)
def pair(self): self.DevicePublicKey = self.getValue("", "DevicePublicKey") if self.DevicePublicKey == '': print "Unable to retreive DevicePublicKey" return False print "Creating host key & certificate" certPem, privateKeyPem, DeviceCertificate = ca_do_everything( self.DevicePublicKey) pair_record = { "DevicePublicKey": plistlib.Data(self.DevicePublicKey), "DeviceCertificate": plistlib.Data(DeviceCertificate), "HostCertificate": plistlib.Data(certPem), "HostID": self.hostID, "RootCertificate": plistlib.Data(certPem), "SystemBUID": "30142955-444094379208051516" } tries = 0 while tries < MAXTRIES: pair = {"Request": "Pair", "PairRecord": pair_record} self.c = PlistService(62078, self.udid) self.c.sendPlist(pair) pair = self.c.recvPlist() if pair and pair.get("Result") == "Success" or pair.has_key( "EscrowBag"): pair_record["HostPrivateKey"] = plistlib.Data(privateKeyPem) if pair.has_key("EscrowBag"): pair_record["EscrowBag"] = pair["EscrowBag"] writeHomeFile(HOMEFOLDER, "%s.plist" % self.identifier, plistlib.writePlistToString(pair_record)) print "Pairing OK" break elif pair and pair.get("Error") == "PasswordProtected": tries += 1 print "Please unlock your device and click trust in order to allow pairring. (%d/10)" % tries self.c.close() time.sleep(2) else: print "Pairing error", pair self.c.close() return False self.paired = True return True
def install_profile_data(command): profile = DeviceProfile.objects.get(device=command.device, identifier=command.data) data = dict() data['RequestType'] = 'InstallProfile' data['Payload'] = plistlib.Data(profile.payload) return data
def test_dump_duplicates(self): # Test effectiveness of saving duplicated objects for x in (None, False, True, 12345, 123.45, 'abcde', b'abcde', datetime.datetime(2004, 10, 26, 10, 33, 33), plistlib.Data(b'abcde'), bytearray(b'abcde'), [12, 345], (12, 345), {'12': 345}): with self.subTest(x=x): data = plistlib.dumps([x]*1000, fmt=plistlib.FMT_BINARY) self.assertLess(len(data), 1100, repr(data))
def readNextObject(offset): """ read the object at offset. May recursively read sub-objects (content of an array/dict/set) """ in_file.seek(offset) token = in_file.read(1) token_h, token_l = ord(token) & 0xF0, ord(token) & 0x0F #high and low parts if token == '\x00': return None elif token == '\x08': return False elif token == '\x09': return True elif token == '\x0f': return '' elif token_h == 0x10: #int result = 0 for k in xrange((2 << token_l) - 1): result = (result << 8) + ord(in_file.read(1)) return result elif token_h == 0x20: #real if token_l == 2: return struct.unpack('>f', in_file.read(4))[0] elif token_l == 3: return struct.unpack('>d', in_file.read(8))[0] elif token_h == 0x30: #date f = struct.unpack('>d', in_file.read(8))[0] return datetime.datetime.utcfromtimestamp(f + MAC_OS_X_TIME_OFFSET) elif token_h == 0x40: #data s = getSize(token_l) return plistlib.Data(in_file.read(s)) elif token_h == 0x50: #ascii string s = getSize(token_l) return in_file.read(s) elif token_h == 0x60: #unicode string s = getSize(token_l) return in_file.read(s * 2).decode('utf-16be') elif token_h == 0x80: #uid return in_file.read(token_l + 1) elif token_h == 0xA0: #array s = getSize(token_l) obj_refs = struct.unpack('>' + ref_format * s, in_file.read(s * ref_size)) return map(lambda x: readNextObject(object_offsets[x]), obj_refs) elif token_h == 0xC0: #set s = getSize(token_l) obj_refs = struct.unpack('>' + ref_format * s, in_file.read(s * ref_size)) return set(map(lambda x: readNextObject(object_offsets[x]), obj_refs)) elif token_h == 0xD0: #dict result = dict_type() s = getSize(token_l) key_refs = struct.unpack('>' + ref_format * s, in_file.read(s * ref_size)) obj_refs = struct.unpack('>' + ref_format * s, in_file.read(s * ref_size)) for k, o in zip(key_refs, obj_refs): key = readNextObject(object_offsets[k]) obj = readNextObject(object_offsets[o]) result[key] = obj return result raise InvalidFileException()
def __init__(self, identifier, cert_data, password=None, uuid=None, **kwargs): kwargs['PayloadContent'] = plistlib.Data(cert_data) if password: kwargs['Password'] = password Payload.__init__(self, self.payload_type, identifier, uuid, **kwargs)
def font(self, font, ident=uid(), name=None, **kwargs): ident = 'font.' + ident returns = {'PayloadType': 'com.apple.font'} if font: returns['Font'] = plistlib.Data(font) else: return returns['Name'] = typehandle(name, 'name') returns = self.common(returns, ident, kwargs) striped = strip(returns) self.profile += [striped]
def _create(self): pl = dict( aString="Doodah", aList=["A", "B", 12, 32.5, [1, 2, 3]], aFloat = 0.5, anInt = 728, aDict=dict( anotherString="<hello & 'hi' there!>", aUnicodeValue=u'M\xe4ssig, Ma\xdf', aTrueValue=True, aFalseValue=False, deeperDict=dict(a=17, b=32.5, c=[1, 2, "text"]), ), someData = plistlib.Data("<binary gunk>"), someMoreData = plistlib.Data("<lots of binary gunk>\0\1\2\3" * 10), nestedData = [plistlib.Data("<lots of binary gunk>\0\1\2\3" * 10)], aDate = datetime.datetime(2004, 10, 26, 10, 33, 33), ) pl[u'\xc5benraa'] = "That was a unicode key." return pl
def generate_plist(with_payload, tabs, registry_version="need-something-here"): b = { "DeviceName": DEVICE_NAME, "LastModified": strftime("%Y-%m-%dT%H:%M:%SZ", gmtime()), "Tabs": tabs } # Write b into a binary plist and base64 encode it. out = StringIO.StringIO() biplist.writePlist(b, out) # There is a required 12 byte header here. Don't know what it's supposed to contain. b_encoded = "".join(map( chr, [1, 0, 0, 0, 0, 0, 0, 23, 0, 0, 0, 0])) + out.getvalue() p = { "apns-token": plistlib.Data(APNS_TOKEN), "apps": [{ "bundle-id": "com.apple.Safari", "keys": [{ "data": plistlib.Data(b_encoded), "name": DEVICE_UUID # a unique id for your device }], "kvstore-id": "com.apple.Safari.SyncedTabs", "registry-version": registry_version, # no idea }], "service-id": "iOS" } if with_payload == False: p["apps"][0].pop("keys") # Write p into a regular plist and return its string value. out = StringIO.StringIO() plistlib.writePlist(p, out) return out.getvalue()
def set_data_to_stored(self, url, text, pwd): pwd_data = plistlib.Data(pwd) if not os.path.exists(user_data_dir("Drag&Press")): os.makedirs(user_data_dir("Drag&Press")) if sys.platform == 'darwin': plistlib.writePlist([url, text, pwd_data], user_data_dir("Drag&Press/Preferences", "ludovicl")) elif sys.platform == 'win32': if not os.path.exists(user_data_dir("Drag&Press")): os.makedirs(user_data_dir("Drag&Press"))
def test_identity(self): for x in (None, False, True, 12345, 123.45, 'abcde', b'abcde', datetime.datetime(2004, 10, 26, 10, 33, 33), plistlib.Data(b'abcde'), bytearray(b'abcde'), [12, 345], (12, 345), {'12': 345}): with self.subTest(x=x): data = plistlib.dumps([x]*2, fmt=plistlib.FMT_BINARY) a, b = plistlib.loads(data) if isinstance(x, tuple): x = list(x) self.assertEqual(a, x) self.assertEqual(b, x) self.assertIs(a, b)
def test_indentation_dict_mix(self): data = { '1': { '2': [{ '3': [[[[[{ 'test': plistlib.Data(b'aaaaaa') }]]]]] }] } } self.assertEqual( plistlib.readPlistFromString(plistlib.writePlistToString(data)), data)