def main(argv): p = optparse.OptionParser() p.set_usage("""Usage: %prog [options] userdata.plist [password]""") p.add_option("-v", "--verbose", action="store_true", help="Verbose output.") options, argv = p.parse_args(argv) if len(argv) not in (2, 3): print >>sys.stderr, p.get_usage() return 1 # Read the userdata.plist. plist = argv[1] plist_data = NSData.dataWithContentsOfFile_(plist) if not plist_data: print >>sys.stderr, "Couldn't read %s" % plist return 1 user_plist, plist_format, error = \ NSPropertyListSerialization.propertyListFromData_mutabilityOption_format_errorDescription_( plist_data, NSPropertyListMutableContainers, None, None) if error: print >>sys.stderr, "Can't read %s: %s" % (plist, error) return 1 # Use password on commandline, or ask if one isn't provided. try: password = argv[2] except IndexError: while True: password = getpass.getpass() verify_password = getpass.getpass("Password again: ") if password == verify_password: break else: print "Passwords don't match!" # Hash password with all available methods. hashed_passwords = dict() for k, m in hash_methods.items(): hashed_pwd = m(password) pwd_data = NSData.alloc().initWithBytes_length_(hashed_pwd, len(hashed_pwd)) hashed_passwords[k] = pwd_data # Serialize hashed passwords to a binary plist. serialized_passwords = serialize_hash_dict(hashed_passwords) if not serialized_passwords: return 2 # Write back userdata.plist with ShadowHashData. user_plist["ShadowHashData"] = list() user_plist["ShadowHashData"].append(serialized_passwords) plist_data, error = \ NSPropertyListSerialization.dataFromPropertyList_format_errorDescription_( user_plist, plist_format, None) plist_data.writeToFile_atomically_(argv[1], True) return 0
def bin2str(token_bplist, account_bplist=None): # Convert the decrypted binary plist to an NSData object that can be read. bin_list = NSData.dataWithBytes_length_(token_bplist, len(token_bplist)) # Convert the binary NSData object into a dictionary object. token_plist = NSPropertyListSerialization.propertyListWithData_options_format_error_( bin_list, 0, None, None)[0] # Accounts DB cache if "$objects" in token_plist: # Because it is accounts db cache, we should also have been passed # account_bplist. bin_list = NSData.dataWithBytes_length_(account_bplist, len(account_bplist)) dsid_plist = NSPropertyListSerialization.propertyListWithData_options_format_error_( bin_list, 0, None, None)[0] for obj in dsid_plist["$objects"]: if "{}".format(obj).startswith("urn:ds:"): dsid = obj.replace("urn:ds:", "") token_dict = {"dsid": dsid} # Do some parsing to get the data out because it is not stored # in a format that is easy to process with stdlibs token_l = [ x.strip().replace(",", "") for x in "{}".format(token_plist["$objects"]).splitlines() ] pos_start = token_l.index("mmeBTMMInfiniteToken") pos_end = (token_l.index("cloudKitToken") - pos_start + 1) * 2 token_short = token_l[pos_start:pos_start + pos_end] zipped = zip(token_short[:len(token_short) / 2], token_short[len(token_short) / 2:]) for token_type, token_value in zipped: # Attempt to get generation time # this parsing is a little hacky, but it seems to be the best way # to handle all different kinds of iCloud tokens (new and old) gen_time = get_generation_time(token_value) token_dict[token_type] = (token_value, gen_time) return token_dict else: return token_plist
async def write_gatt_char(self, _uuid: str, data: bytearray, response: bool = False) -> None: """Perform a write operation of the specified GATT characteristic. Args: _uuid (str or UUID): The uuid of the characteristics to write to. data (bytes or bytearray): The data to send. response (bool): If write-with-response operation should be done. Defaults to `False`. """ _uuid = await self.get_appropriate_uuid(_uuid) characteristic = self.services.get_characteristic(_uuid) if not characteristic: raise BleakError("Characteristic {} was not found!".format(_uuid)) value = NSData.alloc().initWithBytes_length_(data, len(data)) success = await cbapp.central_manager_delegate.connected_peripheral_delegate.writeCharacteristic_value_( characteristic.obj, value) if success: logger.debug("Write Characteristic {0} : {1}".format(_uuid, data)) else: raise BleakError( "Could not write value {0} to characteristic {1}: {2}".format( data, characteristic.uuid, success))
def _readPlist(filepath): """ Read a .plist file from filepath. Return the unpacked root object (which is usually a dictionary). If the file doesn't exist, this returns None """ if not os.path.isfile(filepath): log.debug('Tried to read non-existent property list at path: {0}'.format(filepath)) return None plistData = NSData.dataWithContentsOfFile_(filepath) dataObject, plistFormat, error = \ NSPropertyListSerialization.propertyListFromData_mutabilityOption_format_errorDescription_( plistData, NSPropertyListMutableContainers, None, None) if error: error = error.encode('ascii', 'ignore') errmsg = "%s in file %s" % (error, filepath) import traceback log.debug(errmsg) log.debug(traceback.format_exc()) raise NSPropertyListSerializationException(errmsg) else: return dataObject
def _readPlist(filepath): """ Read a .plist file from filepath. Return the unpacked root object (which is usually a dictionary). If the file doesn't exist, this returns None """ if not os.path.isfile(filepath): log.debug( 'Tried to read non-existent property list at path: {0}'.format( filepath)) return None plistData = NSData.dataWithContentsOfFile_(filepath) dataObject, plistFormat, error = \ NSPropertyListSerialization.propertyListFromData_mutabilityOption_format_errorDescription_( plistData, NSPropertyListMutableContainers, None, None) if error: error = error.encode('ascii', 'ignore') errmsg = "%s in file %s" % (error, filepath) import traceback log.debug(errmsg) log.debug(traceback.format_exc()) raise NSPropertyListSerializationException(errmsg) else: return dataObject
def _read_plist(filepath): """ Read a .plist file from filepath. Return the unpacked root object (which is usually a dictionary). If the file doesn't exist, this returns None """ if not os.path.isfile(filepath): log.debug( 'Tried to read non-existent property list at path: {0}'.format( filepath)) return None plistData = NSData.dataWithContentsOfFile_(filepath) dataObject, plistFormat, error = \ NSPropertyListSerialization.propertyListFromData_mutabilityOption_format_errorDescription_( plistData, NSPropertyListMutableContainers, None, None) if error: error = error.encode('ascii', 'ignore') raise salt.exceptions.SaltInvocationError( 'Error decoding Property List : {}'.format(error)) else: return dataObject
def read_file(self, path): """Replace internal XML dict with data from plist at path. Args: path: String path to a plist file. Raises: PlistParseError: Error in reading plist file. """ # pylint: disable=unused-variable try: info, pformat, error = ( NSPropertyListSerialization. propertyListWithData_options_format_error_( NSData.dataWithContentsOfFile_(os.path.expanduser(path)), NSPropertyListMutableContainersAndLeaves, None, None)) # pylint: enable=unused-variable if info is None: if error is None: error = "Invalid plist file." raise PlistParseError("Can't read %s: %s" % (path, error)) except ValueError: print(("Can't read %s" % (path))) sys.exit() return info
async def write_gatt_descriptor(self, handle: int, data: bytearray) -> None: """Perform a write operation on the specified GATT descriptor. Args: handle (int): The handle of the descriptor to read from. data (bytes or bytearray): The data to send. """ manager = self._device_info.manager().delegate() descriptor = self.services.get_descriptor(handle) if not descriptor: raise BleakError("Descriptor {} was not found!".format(handle)) value = NSData.alloc().initWithBytes_length_(data, len(data)) success = await manager.connected_peripheral_delegate.writeDescriptor_value_( descriptor.obj, value ) if success: logger.debug("Write Descriptor {0} : {1}".format(handle, data)) else: raise BleakError( "Could not write value {0} to descriptor {1}: {2}".format( data, descriptor.uuid, success ) )
def writeBytes_(self, data): # NSLog(u'Writing bytes: %s', data) try: self.remoteFileHandle.writeData_( NSData.dataWithBytes_length_(data, len(data))) except objc.error: self.close()
def nsdata(s): """Return an NSData instance for string `s`.""" if isinstance(s, unicode): s = s.encode('utf-8') else: s = str(s) return NSData.dataWithBytes_length_(s, len(s))
def nsdata(obj): """Convert ``object`` to `NSData`.""" if isinstance(obj, unicode): s = obj.encode('utf-8') else: s = str(obj) return NSData.dataWithBytes_length_(s, len(s))
def value(self, data): if not self.properties["write"]: return # data needs to be byte array if not isinstance(data, bytearray): raise TypeError("data needs to be a bytearray") rawdata = NSData.dataWithBytes_length_(data, len(data)) self.service.peripheral.writeValueForCharacteristic(rawdata, self.instance)
def value_async_nr(self, data): if not self.properties["write"]: return # data needs to be byte array if not isinstance(data, bytearray) and not isinstance(data, bytes): raise TypeError("data needs to be a bytearray or bytes") rawdata = NSData.dataWithBytes_length_(data, len(data)) self.service.peripheral.writeValueForCharacteristicAsync( rawdata, self.instance, withResponse=False)
def _valueToNSObject(value, nstype): '''Convert a string with a type specifier to a native Objective-C NSObject (serializable).''' return { 'string': lambda v: NSString.stringWithUTF8String_(v), 'int': lambda v: NSNumber.numberWithInt_(v), 'float': lambda v: NSNumber.numberWithFloat_(v), 'bool': lambda v: True if v == 'true' else False, 'data': lambda v: NSData.initWithBytes_length_(v, len(v)) }[nstype](value)
def readPlist(filepath): """Read a .plist file from filepath. Return the unpacked root object (which is usually a dictionary).""" try: data = NSData.dataWithContentsOfFile_(filepath) except NSPropertyListSerializationException, error: # insert filepath info into error message errmsg = u"%s in %s" % (error, filepath) raise NSPropertyListSerializationException(errmsg)
def readPlist(filepath): '''Read a .plist file from filepath. Return the unpacked root object (which is usually a dictionary).''' try: data = NSData.dataWithContentsOfFile_(filepath) except NSPropertyListSerializationException, error: # insert filepath info into error message errmsg = (u'%s in %s' % (error, filepath)) raise NSPropertyListSerializationException(errmsg)
def readPlist(path): plistData = NSData.dataWithContentsOfFile_(path) dataObject, plistFormat, error = \ NSPropertyListSerialization.propertyListFromData_mutabilityOption_format_errorDescription_( plistData, NSPropertyListMutableContainers, None, None) if error: errmsg = "%s in file %s" % (repr(error), repr(path)) raise NSPropertyListSerializationException(errmsg) else: return dataObject
def decode_bdisk(key): """Return the relative path of file referenced by key """ decodedBytes = base64.b64decode(key) nsData = NSData.dataWithBytes_length_(decodedBytes, len(decodedBytes)) plist, fmt, error = NSPropertyListSerialization.propertyListFromData_mutabilityOption_format_errorDescription_( nsData, 0, None, None) if plist is None: return "Missed" else: return plist['relativePath']
def _init_from_file(self, file): #ns_image = NSImage.alloc().initWithContentsOfFile_(file) #if not ns_image: ns_data = NSData.dataWithContentsOfFile_(file) if not ns_data: raise EnvironmentError("Unable to read image file: %s" % file) ns_rep = NSBitmapImageRep.imageRepWithData_(ns_data) if not ns_rep: raise ValueError("Unrecognised image file type: %s" % file) ns_rep.setSize_((ns_rep.pixelsWide(), ns_rep.pixelsHigh())) self._init_from_ns_rep(ns_rep)
def readPlist(filepath): '''Read a .plist file from filepath. Return the unpacked root object (which is usually a dictionary).''' plistData = NSData.dataWithContentsOfFile_(filepath) (dataObject, plistFormat, error) = ( NSPropertyListSerialization.propertyListWithData_options_format_error_( plistData, NSPropertyListMutableContainersAndLeaves, None, None)) if error: errmsg = u"%s in file %s" % (error, filepath) raise NSPropertyListSerializationException(errmsg) else: return dataObject
def read_bundle_info(self, path): """Read Contents/Info.plist inside a bundle.""" #pylint: disable=no-self-use plistpath = os.path.join(path, "Contents", "Info.plist") info, _, error = ( NSPropertyListSerialization. propertyListFromData_mutabilityOption_format_errorDescription_( NSData.dataWithContentsOfFile_(plistpath), NSPropertyListMutableContainers, None, None)) if error: raise ProcessorError("Can't read %s: %s" % (plistpath, error)) return info
def readPlist(self, filepath): """ Read a .plist file from filepath. Return the unpacked root object (which is usually a dictionary). """ plistData = NSData.dataWithContentsOfFile_(filepath) dataObject, plistFormat, error = \ NSPropertyListSerialization.propertyListFromData_mutabilityOption_format_errorDescription_( plistData, NSPropertyListMutableContainers, None, None) if error: errmsg = "%s in file %s" % (error, filepath) raise ProcessorError(errmsg) else: return dataObject
def readPlist(filepath): """ Read a .plist file from filepath. Return the unpacked root object (which is usually a dictionary). """ plistData = NSData.dataWithContentsOfFile_(filepath) dataObject, plistFormat, error = \ NSPropertyListSerialization.propertyListFromData_mutabilityOption_format_errorDescription_( plistData, NSPropertyListMutableContainers, None, None) if error: errmsg = "%s in file %s" % (error, filepath) raise NSPropertyListSerializationException(errmsg) else: return dataObject
def readPlist(filepath): plistData = NSData.dataWithContentsOfFile_(filepath) dataObject, dummy_plistFormat, error = ( NSPropertyListSerialization. propertyListFromData_mutabilityOption_format_errorDescription_( plistData, NSPropertyListMutableContainers, None, None)) if dataObject is None: if error: error = error.encode('ascii', 'ignore') else: error = "Unknown error" errmsg = "{0} in file {1}".format(error, filepath) raise NSPropertyListSerializationException(errmsg) else: return dataObject
def read_bundle_info(self, path): """Read Contents/Info.plist inside a bundle.""" plistpath = os.path.join(path, "Contents", "Info.plist") info, format, error = \ NSPropertyListSerialization.propertyListFromData_mutabilityOption_format_errorDescription_( NSData.dataWithContentsOfFile_(plistpath), NSPropertyListMutableContainers, None, None ) if error: raise ProcessorError("Can't read %s: %s" % (plistpath, error)) return info
def read_recipe(self, path): """Read a recipe into a dict.""" path = os.path.expanduser(path) if not (os.path.isfile(path)): raise Exception("File does not exist: %s" % path) info, pformat, error = \ NSPropertyListSerialization.propertyListWithData_options_format_error_( NSData.dataWithContentsOfFile_(path), NSPropertyListMutableContainers, None, None ) if error: raise Exception("Can't read %s: %s" % (path, error)) self._xml = info
def addToWf(wf, buffer, icon): for filename in buffer: filename = filename.strip(u"\r\n") plist_data = NSData.dataWithContentsOfFile_(filename) (dataObject, plistFormat, error) = ( NSPropertyListSerialization. propertyListWithData_options_format_error_( plist_data, NSPropertyListMutableContainersAndLeaves, None, None)) wf.add_item(title=dataObject["Name"], subtitle=dataObject["URL"], arg=dataObject["URL"], valid=True, icon=icon)
def readPlist(filepath): """ Read a .plist file from filepath. Return the unpacked root object (which is usually a dictionary). """ plistData = NSData.dataWithContentsOfFile_(filepath) dataObject, dummy_plistFormat, error = ( NSPropertyListSerialization. propertyListFromData_mutabilityOption_format_errorDescription_( plistData, NSPropertyListMutableContainers, None, None)) if error: error = error.encode('ascii', 'ignore') errmsg = "%s in file %s" % (error, filepath) raise NSPropertyListSerializationException(errmsg) else: return dataObject
def getStoredHeaders(self): '''Returns any stored headers for self.destination_path''' # try to read stored headers try: stored_plist_bytestr = xattr.getxattr(self.destination_path, self.GURL_XATTR) except (KeyError, IOError): return {} data = NSData.dataWithBytes_length_(stored_plist_bytestr, len(stored_plist_bytestr)) dataObject, _plistFormat, error = ( NSPropertyListSerialization. propertyListFromData_mutabilityOption_format_errorDescription_( data, NSPropertyListMutableContainersAndLeaves, None, None)) if error: return {} return dataObject
def load_favservers(sfl_path): if os.path.isfile(sfl_path): # File exists, use it sfl_decoded = NSKeyedUnarchiver.unarchiveObjectWithData_( NSData.dataWithContentsOfFile_(sfl_path)) else: # File doesn't exist, make a blank template sfl_decoded = { u'items': [], u'version': 1L, u'properties': { "com.apple.LSSharedFileList.ForceTemplateIcons": False, }, } mutable_favs = dict(sfl_decoded) mutable_favs['items'] = list(mutable_favs['items']) return mutable_favs
def __ns_data_from_array(a): from Foundation import NSData a = np.asarray(a).flatten() if a.dtype == np.uint8 or a.dtype == np.int8: datasize = 1 elif a.dtype == np.uint16 or a.dtype == np.int16: datasize = 2 elif a.dtype == np.float32: datasize = 4 else: assert 0, "unhandled data type %s" % (a.dtype) buf = buffer(a) return datasize, NSData.dataWithBytes_length_(buf, len(buf) * datasize)
def read_bundle_info(self, path): """Read Contents/Info.plist inside a bundle.""" plistpath = os.path.join(path, "Contents", "Info.plist") if not (os.path.isfile(plistpath)): raise ProcessorError("File does not exist: %s" % plistpath) info, format, error = \ NSPropertyListSerialization.propertyListFromData_mutabilityOption_format_errorDescription_( NSData.dataWithContentsOfFile_(plistpath), NSPropertyListMutableContainers, None, None ) if error: raise ProcessorError("Can't read %s: %s" % (plistpath, error)) return info
async def write_gatt_char( self, char_specifier: Union[BleakGATTCharacteristic, int, str, uuid.UUID], data: bytearray, response: bool = False, ) -> None: """Perform a write operation of the specified GATT characteristic. Args: char_specifier (BleakGATTCharacteristic, int, str or UUID): The characteristic to write to, specified by either integer handle, UUID or directly by the BleakGATTCharacteristic object representing it. data (bytes or bytearray): The data to send. response (bool): If write-with-response operation should be done. Defaults to `False`. """ manager = self._central_manager_delegate if not isinstance(char_specifier, BleakGATTCharacteristic): characteristic = self.services.get_characteristic(char_specifier) else: characteristic = char_specifier if not characteristic: raise BleakError("Characteristic {} was not found!".format(char_specifier)) value = NSData.alloc().initWithBytes_length_(data, len(data)) success = ( await manager.connected_peripheral_delegate.writeCharacteristic_value_type_( characteristic.obj, value, CBCharacteristicWriteWithResponse if response else CBCharacteristicWriteWithoutResponse, ) ) if success: logger.debug( "Write Characteristic {0} : {1}".format(characteristic.uuid, data) ) else: raise BleakError( "Could not write value {0} to characteristic {1}: {2}".format( data, characteristic.uuid, success ) )
def readPlistFromString(data): '''Read a plist data from a (byte)string. Return the root object.''' plistData = NSData.dataWithBytes_length_(data, len(data)) if not plistData: raise NSPropertyListSerializationException( "Could not convert string to NSData") dataObject, dummy_plistFormat, error = ( NSPropertyListSerialization. propertyListFromData_mutabilityOption_format_errorDescription_( plistData, NSPropertyListMutableContainers, None, None)) if dataObject is None: if error: error = error.encode('ascii', 'ignore') else: error = "Unknown error" raise NSPropertyListSerializationException(error) else: return dataObject
def read(plist_path: str) -> Dict: """Read a plist file and return its contents as a dictionary.""" exc.raise_if_falsy(plist_path=plist_path) data, error = NSData.dataWithContentsOfFile_options_error_( plist_path, 0, objc.nil) if not data: msg = 'Failed to load plist file at path: {}'.format(plist_path) _raise_ioerror_from_nserror(error, msg) contents, dummy, error = NSPropertyListSerialization.propertyListWithData_options_format_error_( data, NSPropertyListMutableContainersAndLeaves, objc.nil, objc.nil) if not contents: msg = 'Failed to deserialize plist at path: {}'.format(plist_path) _raise_ioerror_from_nserror(error, msg) return contents
def read_bundle_info(self, path): """Read Contents/Info.plist inside a bundle.""" # pylint: disable=no-self-use plistpath = os.path.join(path, "Contents", "Info.plist") # pylint: disable=line-too-long info, _, error = NSPropertyListSerialization.propertyListFromData_mutabilityOption_format_errorDescription_( NSData.dataWithContentsOfFile_(plistpath), NSPropertyListMutableContainers, None, None, ) # pylint: enable=line-too-long if error: raise ProcessorError("Can't read %s: %s" % (plistpath, error)) return info
def pdf2tiff(pdfPath, pageNum=0, resolution=72.0): "Convert one page of a PDF to TIFF at a specific res. in DPI." tiffPath = "%s-%d.tiff" % (splitext(pdfPath)[0], pageNum) pdfData = NSData.dataWithContentsOfFile_(pdfPath) pdfRep = NSPDFImageRep.imageRepWithData_(pdfData) pageCount = pdfRep.pageCount() if pageNum > pageCount-1: return pdfRep.setCurrentPage_(pageNum) pdfImage = NSImage.alloc().init() pdfImage.addRepresentation_(pdfRep) originalSize = pdfImage.size() width, height = originalSize pdfImage.setScalesWhenResized_(YES) rf = resolution / 72.0 pdfImage.setSize_((width*rf, height*rf)) tiffData = pdfImage.TIFFRepresentation() tiffData.writeToFile_atomically_(tiffPath, YES)
def read_plist(filepath): ''' Read a .plist file from filepath. Return the unpacked root object (which is usually a dictionary). ''' plist_data = NSData.dataWithContentsOfFile_(filepath) data_object, dummy_plist_format, error = ( NSPropertyListSerialization.propertyListFromData_mutabilityOption_format_errorDescription_( plist_data, NSPropertyListMutableContainers, None, None)) if data_object is None: if error: error = error.encode('ascii', 'ignore') else: error = "Unknown error" errmsg = "%s in file %s" % (error, filepath) raise NSPropertyListSerializationException(errmsg) # pylint: disable=E0602 else: return data_object
def pdf2tiff(pdfPath, pageNum=0, resolution=72.0): "Convert one page of a PDF to TIFF at a specific res. in DPI." tiffPath = "%s-%d.tiff" % (splitext(pdfPath)[0], pageNum) pdfData = NSData.dataWithContentsOfFile_(pdfPath) pdfRep = NSPDFImageRep.imageRepWithData_(pdfData) pageCount = pdfRep.pageCount() if pageNum > pageCount - 1: return pdfRep.setCurrentPage_(pageNum) pdfImage = NSImage.alloc().init() pdfImage.addRepresentation_(pdfRep) originalSize = pdfImage.size() width, height = originalSize pdfImage.setScalesWhenResized_(YES) rf = resolution / 72.0 pdfImage.setSize_((width * rf, height * rf)) tiffData = pdfImage.TIFFRepresentation() tiffData.writeToFile_atomically_(tiffPath, YES)
def start(self): '''Start the connection''' if not self.destination_path: self.log('No output file specified.') self.done = True return url = NSURL.URLWithString_(self.url) request = ( NSMutableURLRequest.requestWithURL_cachePolicy_timeoutInterval_( url, NSURLRequestReloadIgnoringLocalCacheData, self.connection_timeout)) if self.post_data: request.setHTTPMethod_('POST') data_unicode = unicode(self.post_data) data = NSData.dataWithBytes_length_( NSString.stringWithString_(data_unicode).UTF8String(), len(data_unicode.encode('utf-8'))) request.setHTTPBody_(data) if self.additional_headers: for header, value in self.additional_headers.items(): request.setValue_forHTTPHeaderField_(value, header) # does the file already exist? See if we can resume a partial download if os.path.isfile(self.destination_path): stored_data = self.get_stored_headers() if (self.can_resume and 'expected-length' in stored_data and ('last-modified' in stored_data or 'etag' in stored_data)): # we have a partial file and we're allowed to resume self.resume = True local_filesize = os.path.getsize(self.destination_path) byte_range = 'bytes=%s-' % local_filesize request.setValue_forHTTPHeaderField_(byte_range, 'Range') if self.download_only_if_changed and not self.resume: stored_data = self.cache_data or self.get_stored_headers() if 'last-modified' in stored_data: request.setValue_forHTTPHeaderField_( stored_data['last-modified'], 'if-modified-since') if 'etag' in stored_data: request.setValue_forHTTPHeaderField_(stored_data['etag'], 'if-none-match') self.connection = NSURLConnection.alloc().initWithRequest_delegate_( request, self)
def convertIconToPNG(icon_path, destination_path, desired_pixel_height=350): '''Converts an icns file to a png file, choosing the representation closest to (but >= if possible) the desired_pixel_height. Returns True if successful, False otherwise''' if os.path.exists(icon_path): image_data = NSData.dataWithContentsOfFile_(icon_path) bitmap_reps = NSBitmapImageRep.imageRepsWithData_(image_data) chosen_rep = None for bitmap_rep in bitmap_reps: if not chosen_rep: chosen_rep = bitmap_rep elif (bitmap_rep.pixelsHigh() >= desired_pixel_height and bitmap_rep.pixelsHigh() < chosen_rep.pixelsHigh()): chosen_rep = bitmap_rep if chosen_rep: png_data = chosen_rep.representationUsingType_properties_( NSPNGFileType, None) png_data.writeToFile_atomically_(destination_path, False) return True return False
def start(self): '''Start the connection''' if not self.destination_path: self.log('No output file specified.') self.done = True return url = NSURL.URLWithString_(self.url) request = ( NSMutableURLRequest.requestWithURL_cachePolicy_timeoutInterval_( url, NSURLRequestReloadIgnoringLocalCacheData, self.connection_timeout)) if self.post_data: request.setHTTPMethod_('POST') data_unicode = unicode(self.post_data) data = NSData.dataWithBytes_length_(NSString.stringWithString_(data_unicode).UTF8String(), len(data_unicode.encode('utf-8'))) request.setHTTPBody_(data) if self.additional_headers: for header, value in self.additional_headers.items(): request.setValue_forHTTPHeaderField_(value, header) # does the file already exist? See if we can resume a partial download if os.path.isfile(self.destination_path): stored_data = self.get_stored_headers() if (self.can_resume and 'expected-length' in stored_data and ('last-modified' in stored_data or 'etag' in stored_data)): # we have a partial file and we're allowed to resume self.resume = True local_filesize = os.path.getsize(self.destination_path) byte_range = 'bytes=%s-' % local_filesize request.setValue_forHTTPHeaderField_(byte_range, 'Range') if self.download_only_if_changed and not self.resume: stored_data = self.cache_data or self.get_stored_headers() if 'last-modified' in stored_data: request.setValue_forHTTPHeaderField_( stored_data['last-modified'], 'if-modified-since') if 'etag' in stored_data: request.setValue_forHTTPHeaderField_( stored_data['etag'], 'if-none-match') self.connection = NSURLConnection.alloc().initWithRequest_delegate_( request, self)
def read_file(self, path): """Replace internal XML dict with data from plist at path. Args: path: String path to a plist file. Raises: PlistParseError: Error in reading plist file. """ # pylint: disable=unused-variable info, pformat, error = ( NSPropertyListSerialization.propertyListWithData_options_format_error_( NSData.dataWithContentsOfFile_(os.path.expanduser(path)), NSPropertyListMutableContainersAndLeaves, None, None )) # pylint: enable=unused-variable if info is None: if error is None: error = "Invalid plist file." raise PlistParseError("Can't read %s: %s" % (path, error)) return info
def _read_plist(filepath): """ Read a .plist file from filepath. Return the unpacked root object (which is usually a dictionary). If the file doesn't exist, this returns None """ if not os.path.isfile(filepath): log.debug('Tried to read non-existent property list at path: {0}'.format(filepath)) return None plistData = NSData.dataWithContentsOfFile_(filepath) dataObject, plistFormat, error = \ NSPropertyListSerialization.propertyListFromData_mutabilityOption_format_errorDescription_( plistData, NSPropertyListMutableContainers, None, None) if error: error = error.encode('ascii', 'ignore') raise salt.exceptions.SaltInvocationError( 'Error decoding Property List : {}'.format(error) ) else: return dataObject
def get_input(): try: while True: line = sys.stdin.readline() if not line: break if line == '': continue print "info:Read %s" % line sys.stdout.flush() cfg = None try: cfg = json.loads(line) except: pass if cfg == None: print "info:Unable to parse line" sys.stdout.flush() continue if cfg.has_key("Action"): print "info:Running %s" % cfg["Action"] sys.stdout.flush() if cfg["Action"] == "setmenu": menu = cfg["Menu"] if lookup.has_key(menu["Key"]): lookup[menu["Key"]].title = menu["Text"] if menu.has_key("Enabled") and not menu["Enabled"]: lookup[menu["Key"]].set_callback(None) else: lookup[menu["Key"]].set_callback(item_clicked) app.menu.update([]) else: print "warn:Key not found %s" % cfg["Action"] sys.stdout.flush() elif cfg["Action"] == "setmenus": app.menu.clear() app.menu = parsemenus(cfg) print "info:Updated menus" sys.stdout.flush() elif cfg["Action"] == "seticon": try: raw = base64.b64decode(cfg["Image"]) data = NSData.dataWithBytes_length_(raw, len(raw)) img = NSImage.alloc().initWithData_(data) img.setScalesWhenResized_(True) img.setSize_((21, 21)) app.icon = img print "info:Image updated" sys.stdout.flush() except: print "warn:Failed to set image" sys.stdout.flush() elif cfg["Action"] == "shutdown": break elif cfg["Action"] == "notification": if rumps_NOTIFICATIONS: rumps.notification(cfg["Title"], '', cfg["Message"]) finally: rumps.quit_application() print "info:Shutdown" sys.stdout.flush() print "info:Stdin close" sys.stdout.flush() sys.stdin.close()
def main(): parser = argparse.ArgumentParser(description='Sign or encrypt mobileconfig profiles, using either a cert + key file, or a keychain certificate.') parser.add_argument('sign', choices=('sign', 'encrypt', 'both'), help='Choose to sign, encrypt, or do both on a profile.') key_group = parser.add_argument_group('Keychain arguments', description='Use these if you wish to sign with a Keychain certificate.') key_group.add_argument('-k', '--keychain', help='Name of keychain to search for cert. Defaults to login.keychain', default='login.keychain') key_group.add_argument('-n', '--name', help='Common name of certificate to use from keychain.', required=True) parser.add_argument('infile', help='Path to input .mobileconfig file') parser.add_argument('outfile', help='Path to output .mobileconfig file. Defaults to outputting into the same directory.') args = parser.parse_args() if args.sign == 'encrypt' or args.sign == 'both': if args.sign == 'both': outputFile = args.outfile + '_unsigned' else: outputFile = args.outfile # encrypt the profile only, do not sign # Encrypting a profile: # 1. Extract payload content into its own file # 2. Serial that file as its own plist # 3. CMS-envelope that content (using openssl for now) # 4. Remove "PayloadContent" key and replace with "EncryptedPayloadContent" key # 5. Replace the PayloadContent <array> with <data> tags instead # Step 1: Extract payload content into its own file myProfile = readPlist(args.infile) payloadContent = myProfile['PayloadContent'] # Step 2: Serialize that file into its own plist (pContentFile, pContentPath) = tempfile.mkstemp() #print "pContentPath: %s" % pContentPath writePlist(payloadContent, pContentPath) # Step 3: Use openssl to encrypt that content # First, we need to extract the certificate we want to use from the keychain security_cmd = ['/usr/bin/security', 'find-certificate', '-c', args.name, '-p' ] if args.keychain: security_cmd += [args.keychain] proc = subprocess.Popen(security_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (sout, serr) = proc.communicate() if serr: print >> sys.stderr, "Error: %s" % serr sys.exit(1) # Now write the certificate to a temp file (certfile, certpath) = tempfile.mkstemp('.der') #print "Certpath: %s" % certpath try: with open(certpath, 'wb') as f: f.write(sout) except IOError: print >> sys.stderr, "Could not write to file!" sys.exit(1) # Now use openssl to encrypt the payload content using that certificate (encPContentfile, encPContentPath) = tempfile.mkstemp('.plist') #print "encPContentPath: %s" % encPContentPath enc_cmd = ['/usr/bin/openssl', 'smime', '-encrypt', '-aes256', '-outform', 'der', '-in', pContentPath, '-out', encPContentPath] enc_cmd += [certpath] proc = subprocess.Popen(enc_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (encout, encerr) = proc.communicate() if encerr: print >> sys.stderr, "Error: %s" % encerr sys.exit(1) # openssl smime -encrypt produces no output if successful # Step 4: Add the new encrypted payload content back into the plist with open(encPContentPath, 'rb') as f: binaryEncPayload = f.read() del myProfile['PayloadContent'] wrapped_data = NSData.dataWithBytes_length_(binaryEncPayload, len(binaryEncPayload)) myProfile['EncryptedPayloadContent'] = wrapped_data # Step 5: Replace the plist with the new content plistData, error = NSPropertyListSerialization.dataFromPropertyList_format_errorDescription_(myProfile, NSPropertyListXMLFormat_v1_0, None) plistData.writeToFile_atomically_(outputFile, True) # Now clean up after ourselves os.remove(pContentPath) os.remove(certpath) os.remove(encPContentPath) if args.sign == 'sign' or args.sign == 'both': # Keychain check: if not args.name: print >> sys.stderr, 'Error: A certificate common name is required to sign profiles with the Keychain.' sys.exit(22) if args.sign == 'both': # If we already encrypted it, then the correct file is already in outputFile inputFile = outputFile else: inputFile = args.infile cmd = ['/usr/bin/security', 'cms', '-S', '-N', args.name, '-i', inputFile, '-o', args.outfile ] proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (sout, serr) = proc.communicate() if serr: print >> sys.stderr, 'Error: %s' % serr sys.exit(1) if args.sign == 'both': os.remove(outputFile)
def main(): parser = argparse.ArgumentParser(description='Sign or encrypt mobileconfig profiles, using either a cert + key file, or a keychain certificate.') parser.add_argument('sign', choices=('sign', 'encrypt', 'both'), help='Choose to sign, encrypt, or do both on a profile.') key_group = parser.add_argument_group('Keychain arguments', description='Use these if you wish to sign with a Keychain certificate.') key_group.add_argument('-k', '--keychain', help='Name of keychain to search for cert. Defaults to login.keychain', default='login.keychain') key_group.add_argument('-n', '--name', help='Common name of certificate to use from keychain.', required=True) parser.add_argument('infile', help='Path to input .mobileconfig file') parser.add_argument('outfile', help='Path to output .mobileconfig file. Defaults to outputting into the same directory.') args = parser.parse_args() print "f**k yeah" if args.sign == 'encrypt' or args.sign == 'both': # encrypt the profile only, do not sign # Encrypting a profile: # 1. Extract payload content into its own file # 2. Serial that file as its own plist # 3. CMS-envelope that content (using openssl for now) # 4. Remove "PayloadContent" key and replace with "EncryptedPayloadContent" key # 5. Replace the PayloadContent <array> with <data> tags instead # Step 1: Extract payload content into its own file myProfile = plistlib.readPlist(args.infile) payloadContent = myProfile['PayloadContent'] # Step 2: Serialize that file into its own plist (pContentFile, pContentPath) = tempfile.mkstemp() plistlib.writePlist(payloadContent, pContentPath) # Step 3: Use openssl to encrypt that content # First, we need to extract the certificate we want to use from the keychain security_cmd = ['/usr/bin/security', 'find-certificate', '-c', args.name, '-p' ] if args.keychain: security_cmd += [args.keychain] print security_cmd proc = subprocess.Popen(security_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (sout, serr) = proc.communicate() if serr: print >> sys.stderr, "Error: %s" % serr sys.exit(1) # Now write the certificate to a temp file (certfile, certpath) = tempfile.mkstemp('.pem') try: with open(certpath, 'wb') as f: f.write(sout) except IOError: print >> sys.stderr, "Could not write to file!" sys.exit(1) # Now use openssl to encrypt the payload content using that certificate (encPContentfile, encPContentPath) = tempfile.mkstemp('.plist') enc_cmd = ['/usr/bin/openssl', 'smime', '-encrypt', '-aes256', '-outform', 'pem', '-in', pContentPath, '-out', encPContentPath] enc_cmd += [certpath] proc = subprocess.Popen(enc_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (encout, encerr) = proc.communicate() if encerr: print >> sys.stderr, "Error: %s" % encerr sys.exit(1) # openssl smime -encrypt produces no output if successful # Step 4: Add the new encrypted payload content back into the plist with open(encPContentPath, 'rb') as f: content = f.readlines() content = content[1:-1] #this is to skip the ---BEGIN PKCS7--- and ----END PKCS7---- lines encPayload = "" for line in content: encPayload += ''.join(line.rstrip()) # to get rid of Python's \n everywhere del myProfile['PayloadContent'] binaryEncPayload = base64.b64decode(encPayload) wrapped_data = NSData.dataWithBytes_length_(binaryEncPayload, len(binaryEncPayload)) myProfile['EncryptedPayloadContent'] = wrapped_data plistData, error = NSPropertyListSerialization.dataFromPropertyList_format_errorDescription_(myProfile, NSPropertyListXMLFormat_v1_0, None) plistData.writeToFile_atomically_(args.outfile, True) # Step 5: Use plistlib.Data to properly encode the content # myProfile['EncryptedPayloadContent'] = plistlib.Data(encPayload) # now save the profile # plistlib.writePlist(myProfile, args.outfile) # Now clean up after ourselves if args.sign == 'sign' or args.sign == 'both': # sign the profile only # Keychain check: if not args.name: print >> sys.stderr, 'Error: A certificate common name is required to sign profiles with the Keychain.' sys.exit(22) cmd = ['/usr/bin/security', 'cms', '-S', '-N', args.name, '-i', args.infile, '-o', args.outfile ] proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (sout, serr) = proc.communicate() if serr: print >> sys.stderr, 'Error: %s' % serr sys.exit(1)
def parse_plist(info_plist_string): # Use PyObjC, pre-installed in Apple's Python dist. data = NSData.dataWithBytes_length_(info_plist_string, len(info_plist_string)) return NSPropertyListSerialization.propertyListWithData_options_format_error_(data, 0, None, None)
# https://developer.apple.com/library/mac/documentation/cocoa/conceptual/PropertyLists/Introduction/Introduction.html from Foundation import NSData from Foundation import NSPropertyListSerialization from Foundation import NSPropertyListMutableContainersAndLeaves filename = "/Library/Preferences/com.apple.loginwindow.plist" plist_data = NSData.dataWithContentsOfFile_(filename) (dataObject, plistFormat, error) = ( NSPropertyListSerialization.propertyListWithData_options_format_error_( plist_data, NSPropertyListMutableContainersAndLeaves, None, None)) print dataObject
def set_clipboard(self, data): ns_data = NSData.dataWithBytes_length_(data, len(data)) pb = self._ns_pasteboard pb.clearContents() pb.setData_forType_(ns_data, NSStringPboardType)
def pageCount(pdfPath): "Return the number of pages for some PDF file." data = NSData.dataWithContentsOfFile_(pdfPath) img = NSPDFImageRep.imageRepWithData_(data) return img.pageCount()
def convertStringsFile(src, dest): dir = os.path.dirname(dest) if not os.path.exists(dir): try: os.makedirs(dir) except OSError: # can't create directory to hold .po file return # Parse the binary plist .strings file: parser = NSPropertyListSerialization.propertyListFromData_mutabilityOption_format_errorDescription_ data = NSData.dataWithContentsOfMappedFile_(src) strings, format, error = parser(data, NSPropertyListImmutable, None, None) if error: raise ParseError(error) # The format of GNUtext MO files is described here: # http://www.gnu.org/software/autoconf/manual/gettext/MO-Files.html strings = dict(strings) originals = strings.keys() originals.sort() descriptors = [] keys = '' values = '' for original in originals: translation = strings[original] origStr = original.encode("UTF-8") transStr = translation.encode("UTF-8") descriptors.append((len(keys), len(origStr), len(values), len(transStr))) keys += origStr + '\0' # <NUL> terminated values += transStr + '\0' # The header is 28 bytes, each descriptor is 8 bytes, with two descriptors # per string (one pointing at original, one pointing at translation) keysOffset = 28 + len(originals) * 2 * 8 valuesOffset = keysOffset + len(keys) keyDescriptors = [] valueDescriptors = [] for origOffset, origLen, transOffset, transLen in descriptors: keyDescriptors.append(origLen) keyDescriptors.append(keysOffset + origOffset) valueDescriptors.append(transLen) valueDescriptors.append(valuesOffset + transOffset) result = struct.pack( "Iiiiiii", 0x950412DEL, # magic number 0, # file format revision len(originals), # number of strings 28, # offset of table with original strings 28 + len(originals) * 8, # offset of table with translation strings 0, # size of hashing table 0 # offset of hashing table ) result += array.array("i", keyDescriptors).tostring() result += array.array("i", valueDescriptors).tostring() result += keys result += values with open(dest, "wb") as outFile: outFile.write(result)
def get_input(): try: while True: line = sys.stdin.readline() if not line: break if line == '': continue print "info:Read %s" % line sys.stdout.flush() cfg = None try: cfg = json.loads(line) except: pass if cfg == None: print "info:Unable to parse line" sys.stdout.flush() continue if cfg.has_key("Action"): print "info:Running %s" % cfg["Action"] sys.stdout.flush() if cfg["Action"] == "setmenu": menu = cfg["Menu"] if lookup.has_key(menu["Key"]): lookup[menu["Key"]].title = menu["Text"] if menu.has_key("Enabled") and not menu["Enabled"]: lookup[menu["Key"]].set_callback(None) else: lookup[menu["Key"]].set_callback(item_clicked) app.menu.update([]) else: print "warn:Key not found %s" % cfg["Action"] sys.stdout.flush() elif cfg["Action"] == "setmenus": app.menu.clear() app.menu = parsemenus(cfg) print "info:Updated menus" sys.stdout.flush() elif cfg["Action"] == "seticon": try: raw = base64.b64decode(cfg["Image"]) data = NSData.dataWithBytes_length_(raw, len(raw)) img = NSImage.alloc().initWithData_(data) img.setScalesWhenResized_(True) img.setSize_((18, 18)) img.setTemplate_(True) app.icon = img print "info:Image updated" sys.stdout.flush() except: print "warn:Failed to set image" sys.stdout.flush() elif cfg["Action"] == "setappicon": try: raw = base64.b64decode(cfg["Image"]) data = NSData.dataWithBytes_length_(raw, len(raw)) img = NSImage.alloc().initWithData_(data) #img.setScalesWhenResized_(True) #img.setSize_((21, 21)) NSApplication.sharedApplication().setApplicationIconImage_(img) print "info:AppImage updated" sys.stdout.flush() except: print "warn:Failed to set image" sys.stdout.flush() elif cfg["Action"] == "shutdown": break elif cfg["Action"] == "foreground": transform_app_type(True) elif cfg["Action"] == "background": transform_app_type(False) elif cfg["Action"] == "notification": if rumps._NOTIFICATIONS: title = cfg["Title"] message = cfg["Message"] subtitle = '' playSound = True image = None if cfg.has_key("SubTitle"): subtitle = cfg["SubTitle"] if cfg.has_key("PlaySound"): playSound = cfg["PlaySound"] if cfg.has_key("Image"): try: raw = base64.b64decode(cfg["Image"]) data = NSData.dataWithBytes_length_(raw, len(raw)) image = NSImage.alloc().initWithData_(data) except: print "warn:Failed to decode image" sys.stdout.flush() rumps.notification(cfg["Title"], subtitle, cfg["Message"], sound=playSound, image=image) finally: try: traceback.print_exc() except: pass rumps.quit_application() print "info:Shutdown" sys.stdout.flush() print "info:Stdin close" sys.stdout.flush() sys.stdin.close()