def credential(jss_prefs_dict):
    credential = NSURLCredential.credentialWithUser_password_persistence_(
        jss_prefs_dict['jss_user'],
        jss_prefs_dict['jss_password'],
        NSURLCredentialPersistenceNone  # we don't expect ephemeral requests to save keychain items.
    )
    return credential
Exemplo n.º 2
0
Arquivo: gurl.py Projeto: zippyy/munki
 def handleChallenge_withCompletionHandler_(self, challenge,
                                            completionHandler):
     '''Handle an authentication challenge'''
     protectionSpace = challenge.protectionSpace()
     host = protectionSpace.host()
     realm = protectionSpace.realm()
     authenticationMethod = protectionSpace.authenticationMethod()
     self.log(
         'Authentication challenge for Host: %s Realm: %s AuthMethod: %s' %
         (host, realm, authenticationMethod))
     if challenge.previousFailureCount() > 0:
         # we have the wrong credentials. just fail
         self.log('Previous authentication attempt failed.')
         if completionHandler:
             completionHandler(
                 NSURLSessionAuthChallengeCancelAuthenticationChallenge,
                 None)
         else:
             challenge.sender().cancelAuthenticationChallenge_(challenge)
     if self.username and self.password and authenticationMethod in [
             'NSURLAuthenticationMethodDefault',
             'NSURLAuthenticationMethodHTTPBasic',
             'NSURLAuthenticationMethodHTTPDigest'
     ]:
         self.log('Will attempt to authenticate.')
         self.log('Username: %s Password: %s' %
                  (self.username, ('*' * len(self.password or ''))))
         credential = (
             NSURLCredential.credentialWithUser_password_persistence_(
                 self.username, self.password,
                 NSURLCredentialPersistenceNone))
         if completionHandler:
             completionHandler(NSURLSessionAuthChallengeUseCredential,
                               credential)
         else:
             challenge.sender().useCredential_forAuthenticationChallenge_(
                 credential, challenge)
     else:
         # fall back to system-provided default behavior
         self.log('Allowing OS to handle authentication request')
         if completionHandler:
             completionHandler(
                 NSURLSessionAuthChallengePerformDefaultHandling, None)
         else:
             if (challenge.sender().respondsToSelector_(
                     'performDefaultHandlingForAuthenticationChallenge:')):
                 self.log('Allowing OS to handle authentication request')
                 challenge.sender(
                 ).performDefaultHandlingForAuthenticationChallenge_(
                     challenge)
             else:
                 # Mac OS X 10.6 doesn't support
                 # performDefaultHandlingForAuthenticationChallenge:
                 self.log('Continuing without credential.')
                 challenge.sender(
                 ).continueWithoutCredentialForAuthenticationChallenge_(
                     challenge)
Exemplo n.º 3
0
 def handleChallenge_withCompletionHandler_(
         self, challenge, completionHandler):
     '''Handle an authentication challenge'''
     protectionSpace = challenge.protectionSpace()
     host = protectionSpace.host()
     realm = protectionSpace.realm()
     authenticationMethod = protectionSpace.authenticationMethod()
     self.log(
         'Authentication challenge for Host: %s Realm: %s AuthMethod: %s'
         % (host, realm, authenticationMethod))
     if challenge.previousFailureCount() > 0:
         # we have the wrong credentials. just fail
         self.log('Previous authentication attempt failed.')
         if completionHandler:
             completionHandler(
                 NSURLSessionAuthChallengeCancelAuthenticationChallenge,
                 None)
         else:
             challenge.sender().cancelAuthenticationChallenge_(challenge)
     if self.username and self.password and authenticationMethod in [
             'NSURLAuthenticationMethodDefault',
             'NSURLAuthenticationMethodHTTPBasic',
             'NSURLAuthenticationMethodHTTPDigest']:
         self.log('Will attempt to authenticate.')
         self.log('Username: %s Password: %s'
                  % (self.username, ('*' * len(self.password or ''))))
         credential = (
             NSURLCredential.credentialWithUser_password_persistence_(
                 self.username, self.password,
                 NSURLCredentialPersistenceNone))
         if completionHandler:
             completionHandler(
                 NSURLSessionAuthChallengeUseCredential, credential)
         else:
             challenge.sender().useCredential_forAuthenticationChallenge_(
                 credential, challenge)
     else:
         # fall back to system-provided default behavior
         self.log('Allowing OS to handle authentication request')
         if completionHandler:
             completionHandler(
                 NSURLSessionAuthChallengePerformDefaultHandling, None)
         else:
             if (challenge.sender().respondsToSelector_(
                     'performDefaultHandlingForAuthenticationChallenge:')):
                 self.log('Allowing OS to handle authentication request')
                 challenge.sender(
                     ).performDefaultHandlingForAuthenticationChallenge_(
                         challenge)
             else:
                 # Mac OS X 10.6 doesn't support
                 # performDefaultHandlingForAuthenticationChallenge:
                 self.log('Continuing without credential.')
                 challenge.sender(
                     ).continueWithoutCredentialForAuthenticationChallenge_(
                         challenge)
Exemplo n.º 4
0
 def webView_resource_didReceiveAuthenticationChallenge_fromDataSource_(self, sender, identifier, challenge, dataSource):
     self._authRequestCount += 1
     if self._authRequestCount > 2:
         BlinkLogger().log_debug(u"Could not load Blink Server Tools page: authentication failure")
         self.errorText.setHidden_(False)
         self.errorText.setStringValue_("Could not load Blink Server Tools page: authentication failure")
         self.spinWheel.stopAnimation_(None)
         self.spinWheel2.stopAnimation_(None)
         self.loadingText.setHidden_(True)
     else:
         credential = NSURLCredential.credentialWithUser_password_persistence_(self._account.id.username, self._account.server.web_password or self._account.auth.password, NSURLCredentialPersistenceForSession)
         challenge.sender().useCredential_forAuthenticationChallenge_(credential, challenge)
Exemplo n.º 5
0
    def __call__(self, r):  # type: (PreparedRequest) -> PreparedRequest
        """Instead of modifying the request object, we construct an instance of NSURLCredential to attach to ourselves.

        When the delegate detects that attribute is present, it uses it whenever a challenge comes in."""
        credential = NSURLCredential.credentialWithUser_password_persistence_(
            self.username,
            self.password,
            NSURLCredentialPersistenceNone  # we don't expect ephemeral requests to save keychain items.
        )
        self.credential = credential

        return r
Exemplo n.º 6
0
    def performServerAuthWithTrust_handler_(self, trust, completionHandler):
        SecTrustSetAnchorCertificates(trust, [self.serverCert])

        valid, error = SecTrustEvaluateWithError(trust, None)
        if not valid:
            logger.error(error)
            completionHandler(
                NSURLSessionAuthChallengeCancelAuthenticationChallenge, None)
            return

        credential = NSURLCredential.credentialForTrust_(trust)
        completionHandler(NSURLSessionAuthChallengeUseCredential, credential)
Exemplo n.º 7
0
def _build_NSURLCredential(auth):
    """
    Convert an instance of requests.auth.* into an instance of NSURLCredential.

    Args:
        auth: requests.auth.HTTPBasicAuth|requests.auth.HTTPDigestAuth
    Returns:
        NSURLCredential instance
    """
    credential = NSURLCredential.credentialWithUser_password_persistence_(
        auth.username,
        auth.password,
        NSURLCredentialPersistenceNone  # we don't expect ephemeral requests to save keychain items.
    )

    return credential
Exemplo n.º 8
0
    def URLSession_task_didReceiveChallenge_completionHandler_(
        self,
        session,  # type: NSURLSession
        task,  # type: NSURLSessionTask
        challenge,  # type: NSURLAuthenticationChallenge
        completionHandler  # type: (NSURLSessionAuthChallengeDisposition, NSURLCredential) -> Void
    ):  # type: (...) -> None
        logger.debug('URLSession_task_didReceiveChallenge_completionHandler_')
        completionHandler.__block_signature__ = objc_method_signature('v@i@')

        protectionSpace = challenge.protectionSpace()
        host = protectionSpace.host()
        realm = protectionSpace.realm()
        authenticationMethod = protectionSpace.authenticationMethod()

        logger.debug('NSURLProtectionSpace host: %s, realm: %s, method: %s',
                     host, realm, authenticationMethod)

        if authenticationMethod == 'NSURLAuthenticationMethodServerTrust' and not self.verify:
            logger.debug(
                'Trusting invalid SSL certificate because verify=False')
            trust = protectionSpace.serverTrust()
            credential = NSURLCredential.credentialForTrust_(trust)
            completionHandler(NSURLSessionAuthChallengePerformDefaultHandling,
                              credential)
        elif authenticationMethod in [
                'NSURLAuthenticationMethodDefault',
                'NSURLAuthenticationMethodHTTPBasic',
                'NSURLAuthenticationMethodHTTPDigest'
        ]:
            logger.debug('Attempting to authenticate')
            if getattr(self, 'credential', None) is not None:
                logger.debug('Using supplied NSURLCredential')
                completionHandler(NSURLSessionAuthChallengeUseCredential,
                                  self.credential)
            else:
                logger.debug(
                    'No NSURLCredential available, not authenticating.')
                completionHandler(
                    NSURLSessionAuthChallengePerformDefaultHandling, None)
        else:
            completionHandler(NSURLSessionAuthChallengePerformDefaultHandling,
                              None)
Exemplo n.º 9
0
 def webView_resource_didReceiveAuthenticationChallenge_fromDataSource_(
         self, sender, identifier, challenge, dataSource):
     self._authRequestCount += 1
     if self._authRequestCount > 2:
         BlinkLogger().log_debug(
             "Could not load Server Tools page: authentication failure")
         self.errorText.setHidden_(False)
         e = NSLocalizedString("Authentication failure", "Label")
         self.errorText.setStringValue_(
             NSLocalizedString("Could not load page: %s", "Label") % e)
         self.spinWheel.stopAnimation_(None)
         self.spinWheel2.stopAnimation_(None)
         self.loadingText.setHidden_(True)
     else:
         credential = NSURLCredential.credentialWithUser_password_persistence_(
             self._account.id.username, self._account.server.web_password
             or self._account.auth.password,
             NSURLCredentialPersistenceForSession)
         challenge.sender().useCredential_forAuthenticationChallenge_(
             credential, challenge)
Exemplo n.º 10
0
    def connection_didReceiveAuthenticationChallenge_(
            self, connection, challenge):
        '''NSURLConnection delegate method
        Sent when a connection must authenticate a challenge in order to
        download its request.
        Deprecated in 10.10'''

        # we don't actually use the connection argument, so
        # pylint: disable=W0613

        self.log('connection_didReceiveAuthenticationChallenge_')
        protectionSpace = challenge.protectionSpace()
        host = protectionSpace.host()
        realm = protectionSpace.realm()
        authenticationMethod = protectionSpace.authenticationMethod()
        self.log(
            'Authentication challenge for Host: %s Realm: %s AuthMethod: %s'
            % (host, realm, authenticationMethod))
        if challenge.previousFailureCount() > 0:
            # we have the wrong credentials. just fail
            self.log('Previous authentication attempt failed.')
            challenge.sender().cancelAuthenticationChallenge_(challenge)
        if self.username and self.password and authenticationMethod in [
                'NSURLAuthenticationMethodDefault',
                'NSURLAuthenticationMethodHTTPBasic',
                'NSURLAuthenticationMethodHTTPDigest']:
            self.log('Will attempt to authenticate.')
            self.log('Username: %s Password: %s'
                     % (self.username, ('*' * len(self.password or ''))))
            credential = (
                NSURLCredential.credentialWithUser_password_persistence_(
                    self.username, self.password,
                    NSURLCredentialPersistenceNone))
            challenge.sender().useCredential_forAuthenticationChallenge_(
                credential, challenge)
        else:
            # fall back to system-provided default behavior
            self.log('Continuing without credential.')
            challenge.sender(
                ).continueWithoutCredentialForAuthenticationChallenge_(
                    challenge)
Exemplo n.º 11
0
    def connection_willSendRequestForAuthenticationChallenge_(
            self, connection, challenge):
        '''NSURLConnection delegate method
        Tells the delegate that the connection will send a request for an
        authentication challenge.
        New in 10.7.'''

        # we don't actually use the connection argument, so
        # pylint: disable=W0613

        self.log('connection_willSendRequestForAuthenticationChallenge_')
        protectionSpace = challenge.protectionSpace()
        host = protectionSpace.host()
        realm = protectionSpace.realm()
        authenticationMethod = protectionSpace.authenticationMethod()
        self.log(
            'Authentication challenge for Host: %s Realm: %s AuthMethod: %s'
            % (host, realm, authenticationMethod))
        if challenge.previousFailureCount() > 0:
            # we have the wrong credentials. just fail
            self.log('Previous authentication attempt failed.')
            challenge.sender().cancelAuthenticationChallenge_(challenge)
        if self.username and self.password and authenticationMethod in [
                'NSURLAuthenticationMethodDefault',
                'NSURLAuthenticationMethodHTTPBasic',
                'NSURLAuthenticationMethodHTTPDigest']:
            self.log('Will attempt to authenticate.')
            self.log('Username: %s Password: %s'
                     % (self.username, ('*' * len(self.password or ''))))
            credential = (
                NSURLCredential.credentialWithUser_password_persistence_(
                    self.username, self.password,
                    NSURLCredentialPersistenceNone))
            challenge.sender().useCredential_forAuthenticationChallenge_(
                credential, challenge)
        else:
            # fall back to system-provided default behavior
            self.log('Allowing OS to handle authentication request')
            challenge.sender(
                ).performDefaultHandlingForAuthenticationChallenge_(
                    challenge)
Exemplo n.º 12
0
    def connection_didReceiveAuthenticationChallenge_(
            self, connection, challenge):
        '''NSURLConnection delegate method
        Sent when a connection must authenticate a challenge in order to
        download its request.
        Deprecated in 10.10'''

        # we don't actually use the connection argument, so
        # pylint: disable=W0613

        self.log('connection_didReceiveAuthenticationChallenge_')
        protectionSpace = challenge.protectionSpace()
        host = protectionSpace.host()
        realm = protectionSpace.realm()
        authenticationMethod = protectionSpace.authenticationMethod()
        self.log(
            'Authentication challenge for Host: %s Realm: %s AuthMethod: %s'
            % (host, realm, authenticationMethod))
        if challenge.previousFailureCount() > 0:
            # we have the wrong credentials. just fail
            self.log('Previous authentication attempt failed.')
            challenge.sender().cancelAuthenticationChallenge_(challenge)
        if self.username and self.password and authenticationMethod in [
                'NSURLAuthenticationMethodDefault',
                'NSURLAuthenticationMethodHTTPBasic',
                'NSURLAuthenticationMethodHTTPDigest']:
            self.log('Will attempt to authenticate.')
            self.log('Username: %s Password: %s'
                     % (self.username, ('*' * len(self.password or ''))))
            credential = (
                NSURLCredential.credentialWithUser_password_persistence_(
                    self.username, self.password,
                    NSURLCredentialPersistenceNone))
            challenge.sender().useCredential_forAuthenticationChallenge_(
                credential, challenge)
        else:
            # fall back to system-provided default behavior
            self.log('Continuing without credential.')
            challenge.sender(
                ).continueWithoutCredentialForAuthenticationChallenge_(
                    challenge)
Exemplo n.º 13
0
    def connection_willSendRequestForAuthenticationChallenge_(
            self, connection, challenge):
        '''NSURLConnection delegate method
        Tells the delegate that the connection will send a request for an
        authentication challenge.
        New in 10.7.'''

        # we don't actually use the connection argument, so
        # pylint: disable=W0613

        self.log('connection_willSendRequestForAuthenticationChallenge_')
        protectionSpace = challenge.protectionSpace()
        host = protectionSpace.host()
        realm = protectionSpace.realm()
        authenticationMethod = protectionSpace.authenticationMethod()
        self.log(
            'Authentication challenge for Host: %s Realm: %s AuthMethod: %s'
            % (host, realm, authenticationMethod))
        if challenge.previousFailureCount() > 0:
            # we have the wrong credentials. just fail
            self.log('Previous authentication attempt failed.')
            challenge.sender().cancelAuthenticationChallenge_(challenge)
        if self.username and self.password and authenticationMethod in [
                'NSURLAuthenticationMethodDefault',
                'NSURLAuthenticationMethodHTTPBasic',
                'NSURLAuthenticationMethodHTTPDigest']:
            self.log('Will attempt to authenticate.')
            self.log('Username: %s Password: %s'
                     % (self.username, ('*' * len(self.password or ''))))
            credential = (
                NSURLCredential.credentialWithUser_password_persistence_(
                    self.username, self.password,
                    NSURLCredentialPersistenceNone))
            challenge.sender().useCredential_forAuthenticationChallenge_(
                credential, challenge)
        else:
            # fall back to system-provided default behavior
            self.log('Allowing OS to handle authentication request')
            challenge.sender(
                ).performDefaultHandlingForAuthenticationChallenge_(
                    challenge)
Exemplo n.º 14
0
Arquivo: gurl.py Projeto: munki/munki
    def handleChallenge_withCompletionHandler_(self, challenge,
                                               completionHandler):
        '''Handle an authentication challenge'''
        protectionSpace = challenge.protectionSpace()
        host = protectionSpace.host()
        realm = protectionSpace.realm()
        authenticationMethod = protectionSpace.authenticationMethod()
        self.log(
            'Authentication challenge for Host: %s Realm: %s AuthMethod: %s' %
            (host, realm, authenticationMethod))
        if challenge.previousFailureCount() > 0:
            # we have the wrong credentials. just fail
            self.log('Previous authentication attempt failed.')
            if completionHandler:
                completionHandler(
                    NSURLSessionAuthChallengeCancelAuthenticationChallenge,
                    None)
            else:
                challenge.sender().cancelAuthenticationChallenge_(challenge)
        if self.username and self.password and authenticationMethod in [
                'NSURLAuthenticationMethodDefault',
                'NSURLAuthenticationMethodHTTPBasic',
                'NSURLAuthenticationMethodHTTPDigest'
        ]:
            self.log('Will attempt to authenticate.')
            self.log('Username: %s Password: %s' %
                     (self.username, ('*' * len(self.password or ''))))
            credential = (
                NSURLCredential.credentialWithUser_password_persistence_(
                    self.username, self.password,
                    NSURLCredentialPersistenceNone))
            if completionHandler:
                completionHandler(NSURLSessionAuthChallengeUseCredential,
                                  credential)
            else:
                challenge.sender().useCredential_forAuthenticationChallenge_(
                    credential, challenge)
        elif authenticationMethod == 'NSURLAuthenticationMethodClientCertificate':
            self.log('Client certificate required')

            # get issuers info from the response
            expected_issuer_dicts = []
            for dn in protectionSpace.distinguishedNames():
                raw = dn.bytes().tobytes()
                name = Name.load(raw)
                expected_issuer_dicts.append(dict(name.native))
                self.log('Accepted certificate-issuing authority: %s' %
                         name.human_friendly)
            if not expected_issuer_dicts:
                self.log("The server didn't sent the list of "
                         "acceptable certificate-issuing authorities")
                if completionHandler:
                    completionHandler(
                        NSURLSessionAuthChallengeCancelAuthenticationChallenge,
                        None)
                else:
                    challenge.sender().cancelAuthenticationChallenge_(
                        challenge)

            # search for a matching identity
            status, identity_refs = SecItemCopyMatching(
                {
                    kSecClass: kSecClassIdentity,
                    kSecReturnRef: kCFBooleanTrue,
                    kSecMatchLimit: kSecMatchLimitAll
                }, None)
            if status != errSecSuccess:
                self.log('Could not list keychain certificates')
                if completionHandler:
                    completionHandler(
                        NSURLSessionAuthChallengeCancelAuthenticationChallenge,
                        None)
                else:
                    challenge.sender().cancelAuthenticationChallenge_(
                        challenge)
            for identity_ref in identity_refs:
                status, cert_ref = SecIdentityCopyCertificate(
                    identity_ref, None)
                if status != errSecSuccess:
                    continue
                cert_data = SecCertificateCopyData(cert_ref)
                cert = Certificate.load(cert_data.bytes().tobytes())
                issuer_dict = dict(cert.native["tbs_certificate"]["issuer"])
                if issuer_dict in expected_issuer_dicts:
                    self.log("Found matching identity")
                    break
            else:
                self.log('Could not find matching identity')
                if completionHandler:
                    completionHandler(
                        NSURLSessionAuthChallengeCancelAuthenticationChallenge,
                        None)
                else:
                    challenge.sender().cancelAuthenticationChallenge_(
                        challenge)

            self.log("Will attempt to authenticate")
            credential = NSURLCredential.alloc(
            ).initWithIdentity_certificates_persistence_(
                identity_ref, None, NSURLCredentialPersistenceForSession)
            if completionHandler:
                completionHandler(NSURLSessionAuthChallengeUseCredential,
                                  credential)
            else:
                challenge.sender().useCredential_forAuthenticationChallenge_(
                    credential, challenge)
        else:
            # fall back to system-provided default behavior
            self.log('Allowing OS to handle authentication request')
            if completionHandler:
                completionHandler(
                    NSURLSessionAuthChallengePerformDefaultHandling, None)
            else:
                if (challenge.sender().respondsToSelector_(
                        'performDefaultHandlingForAuthenticationChallenge:')):
                    self.log('Allowing OS to handle authentication request')
                    challenge.sender(
                    ).performDefaultHandlingForAuthenticationChallenge_(
                        challenge)
                else:
                    # Mac OS X 10.6 doesn't support
                    # performDefaultHandlingForAuthenticationChallenge:
                    self.log('Continuing without credential.')
                    challenge.sender(
                    ).continueWithoutCredentialForAuthenticationChallenge_(
                        challenge)