How to use the gssapi.Credentials function in gssapi

To help you get started, we’ve selected a few gssapi examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github freeipa / freeipa / ipalib / rpc.py View on Github external
# Remove any existing Cookie first
        self._remove_extra_header('Cookie')
        if use_cookie:
            session_cookie = getattr(context, 'session_cookie', None)
            if session_cookie:
                self._extra_headers.append(('Cookie', session_cookie))
                return

        # Set the remote host principal
        host = self._get_host()
        service = self.service + "@" + host.split(':')[0]

        try:
            creds = None
            if self.ccache:
                creds = gssapi.Credentials(usage='initiate',
                                           store={'ccache': self.ccache})
            name = gssapi.Name(service, gssapi.NameType.hostbased_service)
            self._sec_context = gssapi.SecurityContext(creds=creds, name=name,
                                                       flags=self.flags)
            response = self._sec_context.step()
        except gssapi.exceptions.GSSError as e:
            self._handle_exception(e, service=service)

        self._set_auth_header(response)
github jborean93 / pypsrp / pypsrp / spnego.py View on Github external
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)
github freeipa / ansible-freeipa / plugins / module_utils / ansible_freeipa_module.py View on Github external
def valid_creds(module, principal):  # noqa
    """Get valid credentials matching the princial, try GSSAPI first."""
    if "KRB5CCNAME" in os.environ:
        ccache = os.environ["KRB5CCNAME"]
        module.debug('KRB5CCNAME set to %s' % ccache)

        try:
            cred = gssapi.Credentials(usage='initiate',
                                      store={'ccache': ccache})
        except gssapi.raw.misc.GSSError as e:
            module.fail_json(msg='Failed to find default ccache: %s' % e)
        else:
            module.debug("Using principal %s" % str(cred.name))
            return True

    elif "KRB5_CLIENT_KTNAME" in os.environ:
        keytab = os.environ.get('KRB5_CLIENT_KTNAME', None)
        module.debug('KRB5_CLIENT_KTNAME set to %s' % keytab)

        ccache_name = "MEMORY:%s" % str(uuid.uuid4())
        os.environ["KRB5CCNAME"] = ccache_name

        try:
            cred = kinit_keytab(principal, keytab, ccache_name)
github freeipa / freeipa / ipaclient / install / client.py View on Github external
"One of these packages must be installed: nss_ldap or "
                "nss-pam-ldapd",
                rval=CLIENT_INSTALL_ERROR)

    if options.keytab and options.principal:
        raise ScriptError(
            "Options 'principal' and 'keytab' cannot be used together.",
            rval=CLIENT_INSTALL_ERROR)

    if options.keytab and options.force_join:
        logger.warning("Option 'force-join' has no additional effect "
                       "when used with together with option 'keytab'.")

    # Remove invalid keytab file
    try:
        gssapi.Credentials(
            store={'keytab': paths.KRB5_KEYTAB},
            usage='accept',
        )
    except gssapi.exceptions.GSSError:
        logger.debug("Deleting invalid keytab: '%s'.", paths.KRB5_KEYTAB)
        remove_file(paths.KRB5_KEYTAB)

    # Check if old certificate exist and show warning
    if (
        not options.ca_cert_file and
        get_cert_path(options.ca_cert_file) == paths.IPA_CA_CRT
    ):
        logger.warning("Using existing certificate '%s'.", paths.IPA_CA_CRT)

    if not check_ip_addresses(options):
        raise ScriptError(rval=CLIENT_INSTALL_ERROR)
github dmranck / ticketutil / TicketUtil.py View on Github external
def get_kerberos_principal():
    """
    Use gssapi to get the current kerberos principal.
    This will be used as the requester for some tools when creating tickets.
    :return: The kerberos principal.
    """
    try:
        return str(gssapi.Credentials(usage='initiate').name).lower()
    except gssapi.raw.misc.GSSError:
        return None
github jborean93 / requests-credssp / requests_credssp / spnego.py View on Github external
user = gssapi.Name(base=username,
                           name_type=name_type)
        server_name = gssapi.Name(spn,
                                  name_type=gssapi.NameType.hostbased_service)

        # acquire_cred_with_password is an expensive operation with Kerberos,
        # we will first attempt to just retrieve from the local credential
        # cache and if that fails we then acquire with the password. This is
        # only relevant to the Kerberos mech as NTLM and SPNEGO require us to
        # acquire with the password
        acquire_with_pass = True
        kerb_oid = GSSAPIContext._AUTH_MECHANISMS['kerberos']
        kerb_mech = gssapi.OID.from_int_seq(kerb_oid)
        if mech == kerb_mech:
            try:
                cred = gssapi.Credentials(name=user, usage='initiate',
                                          mechs=[mech])
                # we successfully got the Kerberos credential from the cache
                # and don't need to acquire with the password
                acquire_with_pass = False
            except gssapi.exceptions.GSSError:
                pass

        if acquire_with_pass:
            # error when trying to access the existing cache, get our own
            # credentials with the password specified
            b_password = password.encode('utf-8')
            cred = acquire_cred_with_password(user, b_password,
                                              usage='initiate',
                                              mechs=[mech])
            cred = cred.creds
github internetarchive / snakebite-py3 / snakebite / kerberos.py View on Github external
def __init__(self):
        self.credentials = gssapi.Credentials(usage='initiate')
github dmranck / ticketutil / ticketutil / ticket.py View on Github external
def _get_kerberos_principal():
    """
    Use gssapi to get the current kerberos principal.
    This will be used as the requester for some tools when creating tickets.
    :return: The kerberos principal.
    """
    try:
        return str(gssapi.Credentials(usage='initiate').name).lower()
    except gssapi.raw.misc.GSSError:
        return None
github tp4a / teleport / server / www / packages / packages-linux / x64 / ldap3 / protocol / sasl / kerberos.py View on Github external
if connection.sasl_credentials[0] is True:
                hostname = socket.gethostbyaddr(connection.socket.getpeername()[0])[0]
                target_name = gssapi.Name('ldap@' + hostname, gssapi.NameType.hostbased_service)
            else:
                target_name = gssapi.Name('ldap@' + connection.sasl_credentials[0], gssapi.NameType.hostbased_service)
        if len(connection.sasl_credentials) >= 2 and connection.sasl_credentials[1]:
            authz_id = connection.sasl_credentials[1].encode("utf-8")
        if len(connection.sasl_credentials) >= 3 and connection.sasl_credentials[2]:
            raw_creds = connection.sasl_credentials[2]
    if target_name is None:
        target_name = gssapi.Name('ldap@' + connection.server.host, gssapi.NameType.hostbased_service)

    if raw_creds is not None:
        creds = gssapi.Credentials(base=raw_creds, usage='initiate', store=connection.cred_store)
    else:
        creds = gssapi.Credentials(name=gssapi.Name(connection.user), usage='initiate', store=connection.cred_store) if connection.user else None
    ctx = gssapi.SecurityContext(name=target_name, mech=gssapi.MechType.kerberos, creds=creds)
    in_token = None
    try:
        while True:
            out_token = ctx.step(in_token)
            if out_token is None:
                out_token = ''
            result = send_sasl_negotiation(connection, controls, out_token)
            in_token = result['saslCreds']
            try:
                # This raised an exception in gssapi<1.1.2 if the context was
                # incomplete, but was fixed in
                # https://github.com/pythongssapi/python-gssapi/pull/70
                if ctx.complete:
                    break
            except gssapi.exceptions.MissingContextError:
github ronf / asyncssh / asyncssh / gss_unix.py View on Github external
def __init__(self, host, usage):
        if '@' in host:
            self._host = Name(host)
        else:
            self._host = Name('host@' + host, NameType.hostbased_service)

        if usage == 'initiate':
            self._creds = Credentials(usage=usage)
        else:
            self._creds = Credentials(name=self._host, usage=usage)

        self._mechs = [_mech_to_oid(mech) for mech in self._creds.mechs]
        self._ctx = None