當前位置: 首頁>>代碼示例>>Python>>正文


Python gssapi.Name方法代碼示例

本文整理匯總了Python中gssapi.Name方法的典型用法代碼示例。如果您正苦於以下問題:Python gssapi.Name方法的具體用法?Python gssapi.Name怎麽用?Python gssapi.Name使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在gssapi的用法示例。


在下文中一共展示了gssapi.Name方法的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: authenticator_gssapi

# 需要導入模塊: import gssapi [as 別名]
# 或者: from gssapi import Name [as 別名]
def authenticator_gssapi(self):
        name = gssapi.Name(self._principal,
                           name_type=gssapi.NameType.hostbased_service)
        cname = name.canonicalize(gssapi.MechType.kerberos)

        client_ctx = gssapi.SecurityContext(name=cname, usage='initiate')

        server_token = None
        while not client_ctx.complete:
            client_token = client_ctx.step(server_token)
            client_token = client_token or b''

            server_token = yield client_token, True

        msg = client_ctx.unwrap(server_token).message

        qop = struct.pack('b', SASL_QOP_AUTH & msg[0])
        msg = qop + msg[1:]
        msg = client_ctx.wrap(msg + self._principal.encode(), False).message

        yield (msg, False) 
開發者ID:robinhood,項目名稱:aiokafka,代碼行數:23,代碼來源:conn.py

示例2: get

# 需要導入模塊: import gssapi [as 別名]
# 或者: from gssapi import Name [as 別名]
def get(self, path):
        """ Perform a GET request with GSSAPI authentication """
        # Generate token
        service_name = gssapi.Name('HTTP@{0}'.format(self.url.netloc),
                                   gssapi.NameType.hostbased_service)
        ctx = gssapi.SecurityContext(usage="initiate", name=service_name)
        data = b64encode(ctx.step()).decode()

        # Make the connection
        connection = http.client.HTTPSConnection(self.url.netloc, 443)
        log.debug("GET {0}".format(path))
        connection.putrequest("GET", path)
        connection.putheader("Authorization", "Negotiate {0}".format(data))
        connection.putheader("Referer", self.url_string)
        connection.endheaders()

        # Perform the request, convert response into lines
        response = connection.getresponse()
        if response.status != 200:
            raise ReportError(
                "Failed to fetch tickets: {0}".format(response.status))
        lines = response.read().decode("utf8").strip().split("\n")[1:]
        log.debug("Tickets fetched:")
        log.debug(pretty(lines))
        return lines 
開發者ID:psss,項目名稱:did,代碼行數:27,代碼來源:rt.py

示例3: __init__

# 需要導入模塊: import gssapi [as 別名]
# 或者: from gssapi import Name [as 別名]
def __init__(self, username, password, server):
        log.info("Setting up GSSAPI Security Context for Kerberos auth")
        self.creds = self._acquire_creds(username, password)

        server_spn = "cifs@%s" % server
        log.debug("GSSAPI Server SPN Target: %s" % server_spn)
        server_name = gssapi.Name(base=server_spn,
                                  name_type=gssapi.NameType.hostbased_service)
        self.context = gssapi.SecurityContext(name=server_name,
                                              creds=self.creds,
                                              usage='initiate') 
開發者ID:jborean93,項目名稱:smbprotocol,代碼行數:13,代碼來源:session.py

示例4: __init__

# 需要導入模塊: import gssapi [as 別名]
# 或者: from gssapi import Name [as 別名]
def __init__(self, stream, server_name,
                 flags=(gssapi.RequirementFlag.mutual_authentication |
                        gssapi.RequirementFlag.confidentiality |
                        gssapi.RequirementFlag.integrity)):
        self._inner = NegotiateStream(stream)
        if isinstance(server_name, str):
            server_name = gssapi.Name(server_name, name_type=gssapi.NameType.hostbased_service)
        self.server_name = server_name
        self.flags = flags
        self.client_ctx = None
        self._readcache = b'' 
開發者ID:ernw,項目名稱:net.tcp-proxy,代碼行數:13,代碼來源:gssapi.py

示例5: gssapi_name

# 需要導入模塊: import gssapi [as 別名]
# 或者: from gssapi import Name [as 別名]
def gssapi_name(s):
    return gssapi.Name(s, gssapi.NameType.hostbased_service) 
開發者ID:pythongssapi,項目名稱:requests-gssapi,代碼行數:4,代碼來源:test_requests_gssapi.py

示例6: generate_request_header

# 需要導入模塊: import gssapi [as 別名]
# 或者: from gssapi import Name [as 別名]
def generate_request_header(self, response, host, is_preemptive=False):
        # This method needs to be shimmed because `host` isn't exposed to
        # __init__() and we need to derive things from it.  Also, __init__()
        # can't fail, in the strictest compatability sense.
        try:
            if self.principal is not None:
                gss_stage = "acquiring credentials"
                name = gssapi.Name(
                    self.principal, gssapi.NameType.hostbased_service)
                self.creds = gssapi.Credentials(name=name, usage="initiate")

            # contexts still need to be stored by host, but hostname_override
            # allows use of an arbitrary hostname for the GSSAPI exchange (eg,
            # in cases of aliased hosts, internal vs external, CNAMEs w/
            # name-based HTTP hosting)
            if self.service is not None:
                gss_stage = "initiating context"
                kerb_host = host
                if self.hostname_override:
                    kerb_host = self.hostname_override

                kerb_spn = "{0}@{1}".format(self.service, kerb_host)
                self.target_name = gssapi.Name(
                    kerb_spn, gssapi.NameType.hostbased_service)

            return HTTPSPNEGOAuth.generate_request_header(self, response,
                                                          host, is_preemptive)
        except gssapi.exceptions.GSSError as error:
            msg = error.gen_message()
            log.exception(
                "generate_request_header(): {0} failed:".format(gss_stage))
            log.exception(msg)
            raise SPNEGOExchangeError("%s failed: %s" % (gss_stage, msg)) 
開發者ID:pythongssapi,項目名稱:requests-gssapi,代碼行數:35,代碼來源:compat.py

示例7: _acquire_creds

# 需要導入模塊: import gssapi [as 別名]
# 或者: from gssapi import Name [as 別名]
def _acquire_creds(self, username, password):
        # 3 use cases with Kerberos Auth
        #   1. Both the user and pass is supplied so we want to create a new
        #      ticket with the pass
        #   2. Only the user is supplied so we will attempt to get the cred
        #      from the existing store
        #   3. The user is not supplied so we will attempt to get the default
        #      cred from the existing store
        log.info("GSSAPI: Acquiring credentials handle")
        if username and password:
            log.debug("GSSAPI: Acquiring credentials handle for user %s with "
                      "password" % username)
            user = gssapi.Name(base=username,
                               name_type=gssapi.NameType.user)
            bpass = password.encode('utf-8')
            try:
                creds = gssapi.raw.acquire_cred_with_password(user, bpass,
                                                              usage='initiate')
            except AttributeError:
                raise SMBAuthenticationError("Cannot get GSSAPI credential "
                                             "with password as the necessary "
                                             "GSSAPI extensions are not "
                                             "available")
            except gssapi.exceptions.GSSError as er:
                raise SMBAuthenticationError("Failed to acquire GSSAPI "
                                             "credential with password: %s"
                                             % str(er))
            # acquire_cred_with_password returns a wrapper, we want the creds
            # object inside this wrapper
            creds = creds.creds
        elif username:
            log.debug("GSSAPI: Acquiring credentials handle for user %s from "
                      "existing cache" % username)
            user = gssapi.Name(base=username,
                               name_type=gssapi.NameType.user)

            try:
                creds = gssapi.Credentials(name=user, usage='initiate')
            except gssapi.exceptions.MissingCredentialsError as er:
                raise SMBAuthenticationError("Failed to acquire GSSAPI "
                                             "credential for user %s from the "
                                             "exisiting cache: %s"
                                             % (str(user), str(er)))
        else:
            log.debug("GSSAPI: Acquiring credentials handle for default user "
                      "in cache")
            try:
                creds = gssapi.Credentials(name=None, usage='initiate')
            except gssapi.exceptions.GSSError as er:
                raise SMBAuthenticationError("Failed to acquire default "
                                             "GSSAPI credential from the "
                                             "existing cache: %s" % str(er))
            user = creds.name

        log.info("GSSAPI: Acquired credentials for user %s" % str(user))
        return creds 
開發者ID:jborean93,項目名稱:smbprotocol,代碼行數:58,代碼來源:session.py

示例8: _get_security_context

# 需要導入模塊: import gssapi [as 別名]
# 或者: from gssapi import Name [as 別名]
def _get_security_context(name_type, mech, spn, username, password,
                              delegate, wrap_required, channel_bindings=None):
        if username is not None:
            username = gssapi.Name(base=username, name_type=name_type)

        server_name = gssapi.Name(spn,
                                  name_type=gssapi.NameType.hostbased_service)

        # first try and get the cred from the existing cache, if that fails
        # then get a new ticket with the password (if specified). The cache
        # can only be used for Kerberos, NTLM/SPNEGO must have acquire the
        # cred with a pass
        cred = None
        kerb_oid = GSSAPIContext._AUTH_PROVIDERS['kerberos']
        kerb_mech = gssapi.OID.from_int_seq(kerb_oid)
        if mech == kerb_mech:
            try:
                cred = gssapi.Credentials(name=username, usage='initiate',
                                          mechs=[mech])
                # raises ExpiredCredentialsError if it has expired
                cred.lifetime
            except gssapi.raw.GSSError:
                # we can't acquire the cred if no password was supplied
                if password is None:
                    raise
                cred = None
        elif username is None or password is None:
            raise ValueError("Can only use implicit credentials with kerberos "
                             "authentication")

        if cred is None:
            # error when trying to access the existing cache, get our own
            # credentials with the password specified
            b_password = to_bytes(password)
            cred = gssapi.raw.acquire_cred_with_password(username, b_password,
                                                         usage='initiate',
                                                         mechs=[mech])
            cred = cred.creds

        flags = gssapi.RequirementFlag.mutual_authentication | \
            gssapi.RequirementFlag.out_of_sequence_detection
        if delegate:
            flags |= gssapi.RequirementFlag.delegate_to_peer
        if wrap_required:
            flags |= gssapi.RequirementFlag.confidentiality

        context = gssapi.SecurityContext(name=server_name,
                                         creds=cred,
                                         usage='initiate',
                                         mech=mech,
                                         flags=flags,
                                         channel_bindings=channel_bindings)

        return context 
開發者ID:jborean93,項目名稱:pypsrp,代碼行數:56,代碼來源:spnego.py

示例9: ssh_init_sec_context

# 需要導入模塊: import gssapi [as 別名]
# 或者: from gssapi import Name [as 別名]
def ssh_init_sec_context(self, target, desired_mech=None,
                             username=None, recv_token=None):
        """
        Initialize a GSS-API context.

        :param str username: The name of the user who attempts to login
        :param str target: The hostname of the target to connect to
        :param str desired_mech: The negotiated GSS-API mechanism
                                 ("pseudo negotiated" mechanism, because we
                                 support just the krb5 mechanism :-))
        :param str recv_token: The GSS-API token received from the Server
        :raise SSHException: Is raised if the desired mechanism of the client
                             is not supported
        :return: A ``String`` if the GSS-API has returned a token or ``None`` if
                 no token was returned
        :rtype: String or None
        """
        self._username = username
        self._gss_host = target
        targ_name = gssapi.Name("host@" + self._gss_host,
                                gssapi.C_NT_HOSTBASED_SERVICE)
        ctx = gssapi.Context()
        ctx.flags = self._gss_flags
        if desired_mech is None:
            krb5_mech = gssapi.OID.mech_from_string(self._krb5_mech)
        else:
            mech, __ = decoder.decode(desired_mech)
            if mech.__str__() != self._krb5_mech:
                raise SSHException("Unsupported mechanism OID.")
            else:
                krb5_mech = gssapi.OID.mech_from_string(self._krb5_mech)
        token = None
        try:
            if recv_token is None:
                self._gss_ctxt = gssapi.InitContext(peer_name=targ_name,
                                                    mech_type=krb5_mech,
                                                    req_flags=ctx.flags)
                token = self._gss_ctxt.step(token)
            else:
                token = self._gss_ctxt.step(recv_token)
        except gssapi.GSSException:
            raise gssapi.GSSException("{0} Target: {1}".format(sys.exc_info()[1],
                                                               self._gss_host))
        self._gss_ctxt_status = self._gss_ctxt.established
        return token 
開發者ID:iopsgroup,項目名稱:imoocc,代碼行數:47,代碼來源:ssh_gss.py

示例10: generate_request_header

# 需要導入模塊: import gssapi [as 別名]
# 或者: from gssapi import Name [as 別名]
def generate_request_header(self, response, host, is_preemptive=False):
        """
        Generates the GSSAPI authentication token

        If any GSSAPI step fails, raise SPNEGOExchangeError
        with failure detail.

        """

        gssflags = [gssapi.RequirementFlag.out_of_sequence_detection]
        if self.delegate:
            gssflags.append(gssapi.RequirementFlag.delegate_to_peer)
        if self.mutual_authentication != DISABLED:
            gssflags.append(gssapi.RequirementFlag.mutual_authentication)

        try:
            gss_stage = "initiating context"
            name = self.target_name
            if type(name) != gssapi.Name:
                if '@' not in name:
                    name = "%s@%s" % (name, host)

                name = gssapi.Name(name, gssapi.NameType.hostbased_service)
            self.context[host] = gssapi.SecurityContext(
                usage="initiate", flags=gssflags, name=name,
                creds=self.creds, mech=self.mech)

            gss_stage = "stepping context"
            if is_preemptive:
                gss_response = self.context[host].step()
            else:
                gss_response = self.context[host].step(
                    _negotiate_value(response))

            return "Negotiate {0}".format(b64encode(gss_response).decode())

        except gssapi.exceptions.GSSError as error:
            msg = error.gen_message()
            log.exception(
                "generate_request_header(): {0} failed:".format(gss_stage))
            log.exception(msg)
            raise SPNEGOExchangeError("%s failed: %s" % (gss_stage, msg)) 
開發者ID:pythongssapi,項目名稱:requests-gssapi,代碼行數:44,代碼來源:gssapi_.py


注:本文中的gssapi.Name方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。