def _set_keychain(self): """ Lazy import to avoid conflict with pytest-xdist. """ import objc from Foundation import NSBundle Security = NSBundle.bundleWithIdentifier_('com.apple.security') S_functions = [ ('SecKeychainGetTypeID', b'I'), ('SecKeychainItemGetTypeID', b'I'), ('SecKeychainAddGenericPassword', b'i^{OpaqueSecKeychainRef=}I*I*I*o^^{OpaqueSecKeychainItemRef}'), ('SecKeychainOpen', b'i*o^^{OpaqueSecKeychainRef}'), ('SecKeychainFindGenericPassword', b'i@I*I*o^Io^^{OpaquePassBuff}o^^{OpaqueSecKeychainItemRef}'), ] objc.loadBundleFunctions(Security, globals(), S_functions) SecKeychainRef = objc.registerCFSignature('SecKeychainRef', b'^{OpaqueSecKeychainRef=}', SecKeychainGetTypeID()) SecKeychainItemRef = objc.registerCFSignature( 'SecKeychainItemRef', b'^{OpaqueSecKeychainItemRef=}', SecKeychainItemGetTypeID()) PassBuffRef = objc.createOpaquePointerType('PassBuffRef', b'^{OpaquePassBuff=}', None) # Get the login keychain result, login_keychain = SecKeychainOpen(b'login.keychain', None) self.login_keychain = login_keychain
def _set_keychain(self): """ Lazy import to avoid conflict with pytest-xdist. """ import objc from Foundation import NSBundle Security = NSBundle.bundleWithIdentifier_('com.apple.security') # https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html S_functions = [ ('SecKeychainGetTypeID', b'I'), ('SecKeychainItemGetTypeID', b'I'), ('SecKeychainAddGenericPassword', b'i^{OpaqueSecKeychainRef=}I*I*I*o^^{OpaqueSecKeychainItemRef}'), ('SecKeychainOpen', b'i*o^^{OpaqueSecKeychainRef}'), ('SecKeychainFindGenericPassword', b'i@I*I*o^Io^^{OpaquePassBuff}o^^{OpaqueSecKeychainItemRef}'), ('SecKeychainGetStatus', b'i^{OpaqueSecKeychainRef=}o^I'), ] objc.loadBundleFunctions(Security, globals(), S_functions) SecKeychainRef = objc.registerCFSignature('SecKeychainRef', b'^{OpaqueSecKeychainRef=}', SecKeychainGetTypeID()) SecKeychainItemRef = objc.registerCFSignature( 'SecKeychainItemRef', b'^{OpaqueSecKeychainItemRef=}', SecKeychainItemGetTypeID()) PassBuffRef = objc.createOpaquePointerType('PassBuffRef', b'^{OpaquePassBuff=}', None) # Get the login keychain result, login_keychain = SecKeychainOpen(b'login.keychain', None) self.login_keychain = login_keychain
def parseBridgeSupport(xmldata, globals, frameworkName, dylib_path=None, inlineTab=None): if dylib_path: lib = ctypes.cdll.LoadLibrary(dylib_path) _libraries.append(lib) objc._updatingMetadata(True) try: prs = _BridgeSupportParser(xmldata, frameworkName) globals.update(prs.values) for entry in prs.cftypes: tp = objc.registerCFSignature(*entry) globals[entry[0]] = tp for name, typestr in prs.opaque: globals[name] = objc.createOpaquePointerType(name, typestr) for name, typestr, alias in prs.structs: if alias is not None: globals[name] = alias objc.createStructAlias(name, typestr, alias) else: globals[name] = value = objc.createStructType( name, typestr, None) for name, typestr, magic in prs.constants: try: value = objc._loadConstant(name, _as_string(typestr), magic) except AttributeError: continue globals[name] = value for class_name, sel_name, is_class in prs.meta: objc.registerMetaDataForSelector( class_name, sel_name, prs.meta[(class_name, sel_name, is_class)]) if prs.functions: objc.loadBundleFunctions(None, globals, prs.functions) if inlineTab is not None: objc.loadFunctionList(inlineTab, globals, prs.functions) for name, orig in prs.func_aliases: try: globals[name] = globals[orig] except KeyError: pass finally: objc._updatingMetadata(False)
def __load_cftypes(self, cftypes): if not cftypes: return for name, type, gettypeid_func, tollfree in cftypes: if tollfree: for nm in tollfree.split(","): # pragma: no branch try: objc.lookUpClass(nm) except objc.error: pass else: tollfree = nm break try: v = objc.registerCFSignature(name, type, None, tollfree) self.__dict__[name] = v continue except objc.nosuchclass_error: pass if gettypeid_func is None: func = None else: try: func = getattr(self, gettypeid_func) except AttributeError: func = None if func is None: # GetTypeID function not found, this is either # a CFType that isn't present on the current # platform, or a CFType without a public GetTypeID # function. Proxy using the generic CFType if tollfree is None: v = objc.registerCFSignature(name, type, None, "NSCFType") self.__dict__[name] = v continue v = objc.registerCFSignature(name, type, func()) self.__dict__[name] = v
def __load_cftypes(self, cftypes): if not cftypes: return for name, type, gettypeid_func, tollfree in cftypes: if tollfree: for nm in tollfree.split(','): # pragma: no branch try: objc.lookUpClass(nm) except objc.error: pass else: tollfree = nm break try: v = objc.registerCFSignature(name, type, None, tollfree) self.__dict__[name] = v continue except objc.nosuchclass_error: pass if gettypeid_func is None: func = None else: try: func = getattr(self, gettypeid_func) except AttributeError: func = None if func is None: # GetTypeID function not found, this is either # a CFType that isn't present on the current # platform, or a CFType without a public GetTypeID # function. Proxy using the generic CFType if tollfree is None: v = objc.registerCFSignature(name, type, None, 'NSCFType') self.__dict__[name] = v continue v = objc.registerCFSignature(name, type, func()) self.__dict__[name] = v
def parseBridgeSupport(xmldata, globals, frameworkName, dylib_path=None, inlineTab=None): if dylib_path: lib = ctypes.cdll.LoadLibrary(dylib_path) _libraries.append(lib) objc._updatingMetadata(True) try: prs = _BridgeSupportParser(xmldata, frameworkName) globals.update(prs.values) for entry in prs.cftypes: tp = objc.registerCFSignature(*entry) globals[entry[0]] = tp for name, typestr in prs.opaque: globals[name] = objc.createOpaquePointerType(name, typestr) for name, typestr, alias in prs.structs: if alias is not None: globals[name] = alias objc.createStructAlias(name, typestr, alias) else: globals[name] = value = objc.createStructType(name, typestr, None) for name, typestr, magic in prs.constants: try: value = objc._loadConstant(name, _as_string(typestr), magic) except AttributeError: continue globals[name] = value for class_name, sel_name, is_class in prs.meta: objc.registerMetaDataForSelector(class_name, sel_name, prs.meta[(class_name, sel_name, is_class)]) if prs.functions: objc.loadBundleFunctions(None, globals, prs.functions) if inlineTab is not None: objc.loadFunctionList(inlineTab, globals, prs.functions) for name, orig in prs.func_aliases: try: globals[name] = globals[orig] except KeyError: pass finally: objc._updatingMetadata(False)
""" Testcases for the CoreFoundation wrappers introduced in 1.5 """ import objc from PyObjCTools.TestSupport import * import re import sys from PyObjCTest.corefoundation import * # registerCFSignature(name, encoding, typeId [, tollfreeName]) -> type CFUUIDRef = objc.registerCFSignature( "CFUUIDRef", OC_TestCoreFoundation.signatureForCFUUIDRef(), OC_TestCoreFoundation.typeidForCFUUIDRef(), ) CFDateRef = objc.registerCFSignature( "CFDateRef", OC_TestCoreFoundation.signatureForCFDateRef(), OC_TestCoreFoundation.typeidForCFDateRef(), "NSDate", ) if sys.version_info[0] == 3: unicode = str class TestCoreFoundation(TestCase): def testTollFree(self):
def main(): '''This function is very similar to our fix but instead of performing any systematic changes will read the information and report it to jamf as an extension attribute.''' eap8021x_bundle = NSBundle.bundleWithPath_( '/System/Library/PrivateFrameworks/EAP8021X.framework') # EAP Functions from @mosen's meap project (See above for link) eapol_functions = [ ('EAPOLClientConfigurationGetTypeID', 'Q'), ('EAPOLClientProfileGetTypeID', 'Q'), ('EAPOLClientItemIDGetTypeID', 'Q'), ('EAPOLClientConfigurationCreate', '^{EAPOLClientConfigurationRef=}^{__CFAllocator=}'), ('EAPOLClientProfileGetUserDefinedName', '@^{EAPOLClientProfileRef=}'), ('EAPOLClientConfigurationGetSystemProfile', '^{EAPOLClientProfileRef=}' '^{EAPOLClientConfigurationRef=}@'), ('EAPOLClientConfigurationSetSystemProfile', 'Z^{EAPOLClientConfigurationRef=}@' '^{EAPOLClientProfileRef=}'), ('EAPOLClientConfigurationSave', 'Z^{EAPOLClientConfigurationRef=}') ] objc.loadBundleFunctions(eap8021x_bundle, globals(), eapol_functions) # CF Types to be loaded also from @mosen's meap project cf_types = [ ('EAPOLClientConfigurationRef', '^{EAPOLClientConfigurationRef=}', EAPOLClientConfigurationGetTypeID()), ('EAPOLClientProfileRef', '^{EAPOLClientProfileRef=}', EAPOLClientProfileGetTypeID()), ('EAPOLClientItemIDRef', '^{EAPOLClientItemIDRef=}', EAPOLClientItemIDGetTypeID()), ] for item in cf_types: objc.registerCFSignature(*item) # Define blank list to be used to gather EAPOL information on # Ethernet interfaces interface_list = [] prefs = SCPreferencesCreate(None, "python", None) services = SCNetworkServiceCopyAll(prefs) # Poll through the interfaces and make a list of the true Ethernet # adapters on the system for interface in ethernet_services(services): interface_list.append(SCNetworkInterfaceGetBSDName(interface)) # For loop to iterate through our Ethernet adapters and determine if they # have the system profile we are looking for and apply it to any other # Ethernet interfaces that don't have it applied. Change "Ethernet(COE)" # to whatever your 802.1x profile is called in Network Preferences. # Default in jamf is sadly "Network" for ethernet in interface_list: cfg = EAPOLClientConfigurationCreate(None) look_for_cfg = EAPOLClientConfigurationGetSystemProfile(cfg, ethernet) if look_for_cfg is not None: if EAPOLClientProfileGetUserDefinedName( look_for_cfg) == 'Ethernet(COE)': for ethernet in interface_list: if EAPOLClientConfigurationGetSystemProfile( cfg, ethernet) == look_for_cfg: continue else: EAPOLClientConfigurationSetSystemProfile( cfg, ethernet, look_for_cfg) EAPOLClientConfigurationSave(cfg)
def workaround(): from Foundation import NSMutableData, NSAutoreleasePool pool = NSAutoreleasePool.alloc().init() try: rI = mod.SKIndexCreateWithMutableData(NSMutableData.data(), None, mod.kSKIndexInverted, None) indexID = mod.CFGetTypeID(rI) r = mod.SKIndexDocumentIteratorCreate(rI, None) iterID = mod.CFGetTypeID(r) del r r = mod.SKSearchGroupCreate([rI]) groupID = mod.CFGetTypeID(r) r = mod.SKSearchResultsCreateWithQuery(r, ".*", mod.kSKSearchRanked, 1, None, None) resultID = mod.CFGetTypeID(r) if mod.SKSearchGetTypeID() == 0: # Type doesn't get registered unless you try to use it. # That's no good for PyObjC, therefore forcefully create # a SKSearch object mod.SKSearchCreate(rI, "q", 0) searchref = objc.registerCFSignature("SKSearchRef", b"^{__SKSearch=}", mod.SKSearchGetTypeID()) else: searchref = mod.SKSearchRef del r del rI r = mod.SKSummaryCreateWithString("foo") summaryID = mod.CFGetTypeID(r) del r finally: del pool def SKIndexGetTypeID(): return indexID def SKIndexDocumentIteratorGetTypeID(): return iterID def SKSearchGroupGetTypeID(): return groupID def SKSearchResultsGetTypeID(): return resultID def SKSummaryGetTypeID(): return summaryID indexType = objc.registerCFSignature("SKIndexRef", b"^{__SKIndex=}", indexID) iterType = objc.registerCFSignature("SKIndexDocumentIteratorRef", b"^{__SKIndexDocumentIterator=}", iterID) groupType = objc.registerCFSignature("SKSearchGroupRef", b"^{__SKSearchGroup=}", groupID) resultType = objc.registerCFSignature("SKSearchResultsRef", b"^{__SKSearchResults=}", resultID) summaryType = objc.registerCFSignature("SKSummaryRef", b"^{__SKSummary=}", summaryID) # For some reason SKDocumentGetTypeID doesn't return the right value # when the framework loader calls it the first time around, # by this time the framework is fully initialized and we get # the correct result. SKDocumentRef = objc.registerCFSignature("SKDocumentRef", b"@", mod.SKDocumentGetTypeID()) return (SKIndexGetTypeID, indexType, SKIndexDocumentIteratorGetTypeID, iterType, SKSearchGroupGetTypeID, groupType, SKSearchResultsGetTypeID, resultType, SKSummaryGetTypeID, summaryType, iterType, SKDocumentRef, searchref)
def workaround(): from Foundation import NSMutableData, NSAutoreleasePool pool = NSAutoreleasePool.alloc().init() try: rI = mod.SKIndexCreateWithMutableData(NSMutableData.data(), None, kSKIndexInverted, None) indexID = mod.CFGetTypeID(rI) r = mod.SKIndexDocumentIteratorCreate(rI, None) iterID = mod.CFGetTypeID(r) del r r = mod.SKSearchGroupCreate([rI]) groupID = mod.CFGetTypeID(r) r = mod.SKSearchResultsCreateWithQuery(r, ".*", mod.kSKSearchRanked, 1, None, None) resultID = mod.CFGetTypeID(r) if mod.SKSearchGetTypeID() == 0: # Type doesn't get registered unless you try to use it. # That's no good for PyObjC, therefore forcefully create # a SKSearch object mod.SKSearchCreate(rI, "q", 0) searchref = objc.registerCFSignature( "SKSearchRef", b"^{__SKSearch=}", mod.SKSearchGetTypeID()) else: searchref = mod.SKSearchRef del r del rI r = mod.SKSummaryCreateWithString("foo") summaryID = mod.CFGetTypeID(r) del r finally: del pool def SKIndexGetTypeID(): return indexID def SKIndexDocumentIteratorGetTypeID(): return iterID def SKSearchGroupGetTypeID(): return groupID def SKSearchResultsGetTypeID(): return resultID def SKSummaryGetTypeID(): return summaryID indexType = objc.registerCFSignature( "SKIndexRef", b"^{__SKIndex=}", indexID) iterType = objc.registerCFSignature( "SKIndexDocumentIteratorRef", b"^{__SKIndexDocumentIterator=}", iterID) groupType = objc.registerCFSignature( "SKSearchGroupRef", b"^{__SKSearchGroup=}", groupID) resultType = objc.registerCFSignature( "SKSearchResultsRef", b"^{__SKSearchResults=}", resultID) summaryType = objc.registerCFSignature( "SKSummaryRef", b"^{__SKSummary=}", summaryID) # For some reason SKDocumentGetTypeID doesn't return the right value # when the framework loader calls it the first time around, # by this time the framework is fully initialized and we get # the correct result. mod.SKDocumentRef = objc.registerCFSignature( "SKDocumentRef", b"@", mod.SKDocumentGetTypeID()) return (SKIndexGetTypeID, indexType, SKIndexDocumentIteratorGetTypeID, iterType, SKSearchGroupGetTypeID, groupType, SKSearchResultsGetTypeID, resultType, SKSummaryGetTypeID, summaryType, iterType, SKDocumentRef, searchref)
NSURLResponseUnknownLength, NSLog, NSURLCredential, NSURLCredentialPersistenceNone, NSPropertyListSerialization, NSPropertyListMutableContainersAndLeaves, NSPropertyListXMLFormat_v1_0) from Security import (errSecSuccess, kCFBooleanTrue, kSecClass, kSecClassIdentity, kSecMatchLimit, kSecMatchLimitAll, kSecReturnRef, SecCertificateCopyData, SecIdentityCopyCertificate, SecIdentityGetTypeID, SecItemCopyMatching) from asn1crypto.x509 import Certificate, Name # patch the credentialWithIdentity:certificates:persistence: signature # see https://github.com/ronaldoussoren/pyobjc/issues/320#issuecomment-784278944 import objc objc.registerCFSignature("SecIdentityRef", b"^{__SecIdentity=}", SecIdentityGetTypeID()) objc.registerMetaDataForSelector( b'NSURLCredential', b'credentialWithIdentity:certificates:persistence:', { 'arguments': { 2: { 'null_accepted': False, 'type': b'@' }, 3: { '_template': True, 'type': b'@' }, 4: { '_template': True, 'type': b'Q' },
""" Testcases for the CoreFoundation wrappers introduced in 1.5 """ import objc from PyObjCTools.TestSupport import * import re from PyObjCTest.corefoundation import * # registerCFSignature(name, encoding, typeId [, tollfreeName]) -> type CFUUIDRef = objc.registerCFSignature( "CFUUIDRef", OC_TestCoreFoundation.signatureForCFUUIDRef(), OC_TestCoreFoundation.typeidForCFUUIDRef(), ) CFDateRef = objc.registerCFSignature( "CFDateRef", OC_TestCoreFoundation.signatureForCFDateRef(), OC_TestCoreFoundation.typeidForCFDateRef(), "NSDate", ) class TestCoreFoundation (TestCase): def testTollFree(self): obj = OC_TestCoreFoundation.today() self.assert_( CFDateRef, objc.lookUpClass("NSDate") ) self.assert_( isinstance(obj, CFDateRef) )
def parseBridgeSupport(xmldata, globals, frameworkName, dylib_path=None, inlineTab=None): if dylib_path: lib = ctypes.cdll.LoadLibrary(dylib_path) _libraries.append(lib) objc._updatingMetadata(True) try: prs = _BridgeSupportParser(xmldata, frameworkName) globals.update(prs.values) for entry in prs.cftypes: tp = objc.registerCFSignature(*entry) globals[entry[0]] = tp for name, typestr in prs.opaque: globals[name] = objc.createOpaquePointerType(name, typestr) for name, typestr, alias in prs.structs: if alias is not None: globals[name] = alias objc.createStructAlias(name, typestr, alias) else: globals[name] = value = objc.createStructType(name, typestr, None) for name, typestr, magic in prs.constants: try: value = objc._loadConstant(name, typestr, magic) except AttributeError: continue globals[name] = value for class_name, sel_name, is_class in prs.meta: objc.registerMetaDataForSelector(class_name, sel_name, prs.meta[(class_name, sel_name, is_class)]) for name, method_list in prs.informal_protocols: proto = objc.informal_protocol(name, method_list) # XXX: protocols submodule should be deprecated if "protocols" not in globals: mod_name = "%s.protocols"%(frameworkName,) m = globals["protocols"] = type(objc)(mod_name) sys.modules[mod_name] = m else: m = globals["protocols"] setattr(m, name, proto) if prs.functions: objc.loadBundleFunctions(None, globals, prs.functions) if inlineTab is not None: objc.loadFunctionList(inlineTab, globals, prs.functions) for name, orig in prs.func_aliases: try: globals[name] = globals[orig] except KeyError: pass finally: objc._updatingMetadata(False)
def parseBridgeSupport(xmldata, globals, frameworkName, dylib_path=None, inlineTab=None): if dylib_path: lib = ctypes.cdll.LoadLibrary(dylib_path) _libraries.append(lib) objc._updatingMetadata(True) try: prs = _BridgeSupportParser(xmldata, frameworkName) globals.update(prs.values) for entry in prs.cftypes: tp = objc.registerCFSignature(*entry) globals[entry[0]] = tp for name, typestr in prs.opaque: globals[name] = objc.createOpaquePointerType(name, typestr) for name, typestr, alias in prs.structs: if alias is not None: globals[name] = alias objc.createStructAlias(name, typestr, alias) else: globals[name] = value = objc.createStructType( name, typestr, None) for name, typestr, magic in prs.constants: try: value = objc._loadConstant(name, typestr, magic) except AttributeError: continue globals[name] = value for class_name, sel_name, is_class in prs.meta: objc.registerMetaDataForSelector( class_name, sel_name, prs.meta[(class_name, sel_name, is_class)]) for name, method_list in prs.informal_protocols: proto = objc.informal_protocol(name, method_list) # XXX: protocols submodule should be deprecated if "protocols" not in globals: mod_name = "%s.protocols" % (frameworkName, ) m = globals["protocols"] = type(objc)(mod_name) sys.modules[mod_name] = m else: m = globals["protocols"] setattr(m, name, proto) if prs.functions: objc.loadBundleFunctions(None, globals, prs.functions) if inlineTab is not None: objc.loadFunctionList(inlineTab, globals, prs.functions) for name, orig in prs.func_aliases: try: globals[name] = globals[orig] except KeyError: pass finally: objc._updatingMetadata(False)
Security = NSBundle.bundleWithIdentifier_('com.apple.security') S_functions = [ ('SecKeychainGetTypeID', 'I'), ('SecKeychainItemGetTypeID', 'I'), ('SecKeychainAddGenericPassword', 'i^{OpaqueSecKeychainRef=}I*I*I*o^^{OpaqueSecKeychainItemRef}'), ('SecKeychainOpen', 'i*o^^{OpaqueSecKeychainRef}'), ('SecKeychainFindGenericPassword', 'i@I*I*o^Io^^{OpaquePassBuff}o^^{OpaqueSecKeychainItemRef}'), ] objc.loadBundleFunctions(Security, globals(), S_functions) SecKeychainRef = objc.registerCFSignature('SecKeychainRef', '^{OpaqueSecKeychainRef=}', SecKeychainGetTypeID()) SecKeychainItemRef = objc.registerCFSignature('SecKeychainItemRef', '^{OpaqueSecKeychainItemRef=}', SecKeychainItemGetTypeID()) PassBuffRef = objc.createOpaquePointerType("PassBuffRef", b"^{OpaquePassBuff=}", None) def resolve_password(password_length, password_buffer): return (c_char * password_length).from_address( password_buffer.__pointer__)[:].decode('utf-8') # Get the login keychain result, login_keychain = SecKeychainOpen('login.keychain', None)