PyKerberos

1.2.4 · active · verified Sat Apr 11

PyKerberos provides a high-level interface to the Kerberos GSSAPI for Python applications. It enables client and server-side authentication using Kerberos. The current version is 1.2.4, with releases primarily focused on bug fixes and Python version compatibility.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize a Kerberos client context and generate the first authentication token using `pykerberos`. It simulates the client-side of a GSSAPI negotiation flow. To run this, you'll typically need an active Kerberos ticket (e.g., obtained via `kinit`) and the correct service principal for your target service. Remember to install system Kerberos development libraries before installing pykerberos.

import kerberos
import os

try:
    # Service principal for the target service (e.g., HTTP service on a host)
    # Replace 'HTTP/server.example.com@REALM.COM' with your actual service principal.
    # For a runnable example, we use an environment variable.
    service_principal = os.environ.get('KERBEROS_SERVICE_PRINCIPAL', 'HTTP/fakeserver.example.com@FAKE.REALM')

    # Initialize a Kerberos client context
    # rc: return code (0 for success, non-zero for error)
    # vc: client context handle (opaque object)
    rc, vc = kerberos.authGSSClientInit(service_principal)

    if rc == kerberos.AUTH_GSS_COMPLETE:
        print(f"Successfully initialized Kerberos client context for {service_principal}")

        # Perform the first step of GSS-API negotiation
        # This generates a token to send to the server.
        # The input 'challenge' is empty for the first step.
        rc_step, client_token = kerberos.authGSSClientStep(vc, "")

        if rc_step == kerberos.AUTH_GSS_COMPLETE:
            print(f"Generated client token (to send to server): {client_token[:60]}...")
            print("Kerberos client authentication flow started.")
            print("Next, send this token to your server and process its response with authGSSClientStep.")
        else:
            print(f"Kerberos client step failed with return code: {rc_step}")

        # Clean up the client context when done
        kerberos.authGSSClientClean(vc)
        print("Kerberos client context cleaned up.")

    else:
        print(f"Failed to initialize Kerberos client context for {service_principal}. Return code: {rc}")
        print("Possible reasons: missing kinit ticket, incorrect service principal, or system Kerberos setup issues.")

except kerberos.GSSError as e:
    print(f"Kerberos GSSAPI Error: {e}")
    print("Make sure you have Kerberos development libraries (e.g., krb5-devel) installed and KDC is reachable.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

view raw JSON →