### Client Constructor with DisablePAFXFAST Setting Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/client.md Example of creating a new client instance with the DisablePAFXFAST option enabled. This setting is required for some Active Directory installations. ```go cl := client.NewWithPassword("user", "REALM.COM", "pass", cfg, client.DisablePAFXFAST(true)) ``` -------------------------------- ### Create New Authenticator Example Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/types.md Example demonstrating how to create a new authenticator using NewAuthenticator. It specifies the realm and principal name. ```go auth, _ := types.NewAuthenticator("EXAMPLE.COM", types.NewPrincipalName(nametype.KRB_NT_PRINCIPAL, "user")) ``` -------------------------------- ### Low-Level SPNEGO Client and Server Example Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/gssapi.md This example shows how to initialize a SPNEGO client to acquire credentials and generate an initial token, and then how to initialize a SPNEGO server to accept and verify the client's token. Ensure your Kerberos configuration and keytab are correctly set up. ```go package main import ( "fmt" "log" "github.com/jcmturner/gokrb5/v8/client" "github.com/jcmturner/gokrb5/v8/config" "github.com/jcmturner/gokrb5/v8/gssapi" "github.com/jcmturner/gokrb5/v8/keytab" "github.com/jcmturner/gokrb5/v8/service" "github.com/jcmturner/gokrb5/v8/spnego" ) func main() { cfg, _ := config.Load("/etc/krb5.conf") // Client side cl := client.NewWithPassword("user", "REALM.COM", "pass", cfg) spnegoMech := spnego.SPNEGOClient(cl, "HTTP/host.example.com") // Acquire credentials err := spnegoMech.AcquireCred() if err != nil { log.Fatal(err) } // Generate initial token clientToken, err := spnegoMech.InitSecContext() if err != nil { log.Fatal(err) } clientTokenBytes, _ := clientToken.Marshal() fmt.Printf("Client token size: %d bytes\n", len(clientTokenBytes)) // Server side kt, _ := keytab.Load("/etc/krb5.keytab") serverMech := spnego.SPNEGOService(kt) // Receive and verify client token var serverToken gssapi.ContextToken = &spnego.SPNEGOToken{} serverToken.Unmarshal(clientTokenBytes) ok, ctx, status := serverMech.AcceptSecContext(serverToken) if ok { fmt.Println("Client authenticated successfully") fmt.Printf("Status: %s\n", status.Message) } else { fmt.Printf("Authentication failed: %s\n", status.Message) } } ``` -------------------------------- ### Kerberos Client Configuration Example Source: https://github.com/jcmturner/gokrb5/blob/master/v8/USAGE.md Example configuration for the client's krb5.conf file, specifying KDC and kpasswd server details for a realm. ```ini REALM.COM = { kdc = 127.0.0.1:88 kpasswd_server = 127.0.0.1:464 default_domain = realm.com } ``` -------------------------------- ### ChangePasswd Example Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/client.md Example demonstrating how to use the ChangePasswd method to change a user's password and handle potential errors. ```go ok, err := cl.ChangePasswd("newpassword123") if err != nil { log.Fatal(err) } if !ok { log.Fatal("Password change failed") } ``` -------------------------------- ### krb5.conf Format Example Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/config.md Illustrates the structure and common settings within a krb5.conf file, including default realm, KDC, and realm-specific configurations. ```ini [libdefaults] default_realm = EXAMPLE.COM dns_lookup_kdc = true ticket_lifetime = 24h clock_skew = 300 [realms] EXAMPLE.COM = { kdc = kdc1.example.com:88 kdc = kdc2.example.com:88 admin_server = admin.example.com:749 kpasswd_server = admin.example.com:464 default_domain = example.com } [domain_realm] .example.com = EXAMPLE.COM example.com = EXAMPLE.COM ``` -------------------------------- ### Example: Compare OID with Kerberos 5 Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/gssapi.md Demonstrates how to use the Equal method to check if an OID represents the Kerberos 5 mechanism. ```go if oid.Equal(gssapi.OIDKRB5.OID()) { fmt.Println("Mechanism is Kerberos 5") } ``` -------------------------------- ### PrincipalNameString Example Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/types.md Shows how to get the string representation of a principal name. The output will be the joined components of the NameString field. ```go pn := types.NewPrincipalName(nametype.KRB_NT_PRINCIPAL, "jdoe") fmt.Println(pn.PrincipalNameString()) // Output: "jdoe" ``` -------------------------------- ### Example SID String Conversion Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/pac.md Demonstrates converting a SID to its string representation and printing it. ```go domainSID := pac.KerbValidationInfo.LogonDomainID.String() fmt.Println("Domain SID:", domainSID) ``` -------------------------------- ### Example: Create and Marshal APReq Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/messages.md Demonstrates creating an AP_REQ message using `NewAPReq` and then marshaling it into bytes for network transmission. ```go apReq, err := messages.NewAPReq(ticket, sessionKey, authenticator) if err != nil { log.Fatal(err) } // Marshal to bytes for transmission apReqBytes, _ := apReq.Marshal() ``` -------------------------------- ### Create New Config Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/config.md Initializes a new Config struct with default libdefaults applied. Use this when starting with a fresh configuration. ```go cfg := config.New() ``` -------------------------------- ### Example: Print OID String Representation Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/gssapi.md Shows how to obtain and print the string representation of the SPNEGO OID. ```go fmt.Println(gssapi.OIDSPNEGO.OID().String()) // Output: 1.3.6.1.5.5.2 ``` -------------------------------- ### Key Derivation and Encryption Example Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/crypto.md Demonstrates how to derive a key from a password using specific parameters and then use that key to encrypt and decrypt data. Ensure the correct encryption type ID is used for key derivation. ```go package main import ( "log" "github.com/jcmturner/gokrb5/v8/crypto" "github.com/jcmturner/gokrb5/v8/types" "github.com/jcmturner/gokrb5/v8/iana/nametype" ) func main() { // Create principal principal := types.NewPrincipalName(nametype.KRB_NT_PRINCIPAL, "user") // Derive key from password key, iterations, err := crypto.GetKeyFromPassword( "password123", principal, "EXAMPLE.COM", 18, // AES256 types.PADataSequence{}, ) if err != nil { log.Fatal(err) } fmt.Printf("Key derived in %d iterations\n", iterations) // Encrypt data plaintext := []byte("sensitive data") ciphertext, err := crypto.Encrypt( key, plaintext, []byte{0, 0, 0, 1}, 18, ) if err != nil { log.Fatal(err) } // Decrypt data decrypted, err := crypto.Decrypt( key, ciphertext, []byte{0, 0, 0, 1}, 18, ) if err != nil { log.Fatal(err) } fmt.Printf("Decrypted: %s\n", string(decrypted)) } ``` -------------------------------- ### Generate Sequence Number and Subkey Example Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/types.md Example of calling GenerateSeqNumberAndSubKey to create a sequence number and subkey for an authenticator, specifying AES256 with a 32-byte key. ```go auth.GenerateSeqNumberAndSubKey(18, 32) // AES256, 32 bytes ``` -------------------------------- ### GetPACType Example Usage Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/messages.md Example demonstrating how to use the GetPACType method to check for a PAC and retrieve group SIDs if present and valid. ```go if hasPAC, pac, err := ticket.GetPACType(keytab, principal, logger); hasPAC && err == nil { groupSIDs := pac.KerbValidationInfo.GetGroupMembershipSIDs() fmt.Println("User groups:", groupSIDs) } ``` -------------------------------- ### Example: Verify APReq Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/messages.md Shows how to verify an AP_REQ using the `Verify` method. It checks the request against a keytab with a specified maximum clock skew and prints whether the AP_REQ is valid. ```go ok, err := apReq.Verify(keytab, 5*time.Minute, nil, types.PrincipalName{}) if err != nil { log.Fatal(err) } if ok { fmt.Println("AP_REQ is valid") } ``` -------------------------------- ### Complete HTTP Service with SPNEGO Authentication Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/spnego.md Demonstrates a full HTTP service setup with SPNEGO authentication. It loads a keytab, creates a logger, defines an application handler, and wraps it with SPNEGO authentication. Ensure the keytab file exists at the specified path and the service is configured correctly in Kerberos. ```go package main import ( "fmt" "log" "net/http" "os" "github.com/jcmturner/goidentity/v6" "github.com/jcmturner/gokrb5/v8/credentials" "github.com/jcmturner/gokrb5/v8/keytab" "github.com/jcmturner/gokrb5/v8/service" "github.com/jcmturner/gokrb5/v8/spnego" ) func main() { // Load service keytab kt, err := keytab.Load("/etc/krb5.keytab") if err != nil { log.Fatal(err) } // Create logger logger := log.New(os.Stderr, "GOKRB5: ", log.Ldate|log.Ltime) // Application handler appHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { creds := goidentity.FromHTTPRequestContext(r) if creds != nil && creds.Authenticated() { fmt.Fprintf(w, "Hello, %s!\n", creds.DisplayName()) } else { w.WriteHeader(http.StatusUnauthorized) fmt.Fprint(w, "Not authenticated") } }) // Wrap with SPNEGO authentication handler := spnego.SPNEGOKRB5Authenticate( appHandler, kt, service.Logger(logger), ) http.Handle("/", handler) log.Fatal(http.ListenAndServe(":8080", nil)) } ``` -------------------------------- ### Get Realm Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/credentials.md Retrieves the realm associated with the credentials. ```go func (c *Credentials) Realm() string ``` -------------------------------- ### Client HTTP Request with SPNEGO Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/OVERVIEW.md Example of creating a client, logging in, and making an authenticated HTTP request using SPNEGO. Requires a Kerberos configuration file and credentials. ```go cfg, _ := config.Load("/etc/krb5.conf") cl := client.NewWithPassword("user", "REALM.COM", "pass", cfg) cl.Login() spnegoCl := spnego.NewClient(cl, nil, "HTTP/host.example.com") resp, _ := spnegoCl.Get("http://host.example.com/api") ``` -------------------------------- ### Example RIDGroup Iteration Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/pac.md Iterates through a list of group RIDs and prints each one. ```go for _, group := range pac.KerbValidationInfo.GroupIDs { fmt.Printf("Group RID: %d\n", group.RID) } ``` -------------------------------- ### PrincipalName Examples Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/types.md Demonstrates creating different types of Kerberos principal names using the NewPrincipalName function. Includes user, service, and TGT principals. ```go // User principal user := types.NewPrincipalName(nametype.KRB_NT_PRINCIPAL, "jdoe") // Service principal service := types.NewPrincipalName(nametype.KRB_NT_SRV_INST, "HTTP", "host.example.com") // TGT principal tgt := types.NewPrincipalName(nametype.KRB_NT_SRV_INST, "krbtgt", "EXAMPLE.COM") ``` -------------------------------- ### Service Handler with SPNEGO Authentication Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/OVERVIEW.md Example of setting up a service handler that authenticates incoming requests using SPNEGO and Kerberos. This requires a keytab file. ```go kt, _ := keytab.Load("/etc/krb5.keytab") handler := spnego.SPNEGOKRB5Authenticate( myAppHandler, kt, ) http.Handle("/api", handler) http.ListenAndServe(":8080", nil) ``` -------------------------------- ### Client.Get Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/spnego.md Executes an HTTP GET request with SPNEGO authentication. ```APIDOC ## Client.Get ### Description HTTP GET request with SPNEGO authentication. ### Method ```go func (c *Client) Get(url string) (*http.Response, error) ``` ### Parameters #### Path Parameters - **url** (string) - Required - URL to fetch ### Returns - (*http.Response, error) ### Example ```go resp, err := spnegoCl.Get("http://host.example.com/") ``` ``` -------------------------------- ### Get Keytab from Credentials Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/credentials.md Retrieve the keytab object from the credentials. ```go func (c *Credentials) Keytab() *keytab.Keytab ``` -------------------------------- ### Get Realm (Domain) Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/credentials.md Retrieves the realm (domain) associated with the credentials. ```go func (c *Credentials) Domain() string ``` -------------------------------- ### Create and Format Error in Go Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/errors.md Example of creating a new Krberror with a specific error type and message, then printing its formatted string representation. ```go err := krberror.New(krberror.NetworkingError, "KDC unreachable") fmt.Println(err.Error()) ``` -------------------------------- ### Commit Message Format Example Source: https://github.com/jcmturner/gokrb5/blob/master/CONTRIBUTING.md Follow this format for commit messages to ensure clarity and adherence to project standards. It includes a short summary and a more detailed explanation referencing related issues. ```git update to the godoc comments for the function Blah The godoc comments to function subpkg.Blah have been updated to make it clearer as to what the function is for. ``` -------------------------------- ### Working with Kerberos Credentials Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/credentials.md Demonstrates creating credentials using a keytab file and loading credentials from a ccache file. Ensure the keytab and ccache files exist at the specified paths. ```go package main import ( "log" "github.com/jcmturner/gokrb5/v8/credentials" "github.com/jcmturner/gokrb5/v8/keytab" ) func main() { // Create credentials with keytab kt, _ := keytab.Load("/etc/krb5.keytab") creds := credentials.New("user", "EXAMPLE.COM").WithKeytab(kt) // Check credentials if creds.HasKeytab() { fmt.Println("User:", creds.UserName()) fmt.Println("Realm:", creds.Domain()) } // Load from cache ccache, err := credentials.LoadCCache("/tmp/krb5cc_1000") if err != nil { log.Fatal(err) } clientCreds := ccache.GetClientCredentials() fmt.Println("Cached user:", clientCreds.UserName()) } ``` -------------------------------- ### HTTP GET Request with SPNEGO Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/spnego.md Perform an HTTP GET request with SPNEGO authentication. ```go resp, err := spnegoCl.Get("http://host.example.com/") ``` -------------------------------- ### Get OID String Representation Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/gssapi.md Method to get the string representation of an ASN.1 Object Identifier. This is helpful for debugging or logging. ```go func (oid asn1.ObjectIdentifier) String() string ``` -------------------------------- ### Create Gokrb5 Configuration from String Source: https://github.com/jcmturner/gokrb5/blob/master/USAGE.md Create a krb5 configuration instance by parsing a string. The string must contain appropriate newline separations. ```go import "gopkg.in/jcmturner/gokrb5.v7/config" cfg, err := config.NewConfigFromString(krb5Str) //String must have appropriate newline separations ``` -------------------------------- ### Create Service Settings Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/service.md Create service settings with optional configuration functions. Requires a keytab and can be configured with options like logger, max clock skew, and client address. ```go kt, _ := keytab.Load("/etc/krb5.keytab") logger := log.New(os.Stderr, "SERVICE: ", log.Ldate|log.Ltime) settings := service.NewSettings(kt, service.Logger(logger), service.MaxClockSkew(5 * time.Minute), ) ``` -------------------------------- ### Get Username Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/credentials.md Retrieves the username associated with the credentials. ```go func (c *Credentials) UserName() string ``` -------------------------------- ### Get Authentication Time Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/credentials.md Retrieves the time at which authentication occurred. ```go func (c *Credentials) AuthTime() time.Time ``` -------------------------------- ### Create Kerberos Client with Keytab Source: https://github.com/jcmturner/gokrb5/blob/master/USAGE.md Instantiate a Kerberos client using a username, realm, and keytab. A configuration object is required, and optional settings can be provided. ```go import "gopkg.in/jcmturner/gokrb5.v7/client" cl := client.NewClientWithKeytab("username", "REALM.COM", kt, cfg) ``` -------------------------------- ### Get Attributes Map Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/credentials.md Retrieves the map of all attributes associated with the credentials. ```go func (c *Credentials) Attributes() map[string]interface{} ``` -------------------------------- ### Load and Use Service Keytab for Authentication Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/keytab.md Loads a service keytab file and initializes service settings for verifying client credentials. Ensure the keytab file exists at the specified path. ```go package main import ( "log" "github.com/jcmturner/gokrb5/v8/keytab" "github.com/jcmturner/gokrb5/v8/service" ) func main() { // Load service keytab kt, err := keytab.Load("/etc/krb5.keytab") if err != nil { log.Fatal(err) } // Use with service to verify client credentials settings := service.NewSettings(kt) // When handling AP_REQ from client: // ok, creds, err := service.VerifyAPREQ(&APReq, settings) } ``` -------------------------------- ### Get Credential Expiration Time Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/credentials.md Retrieves the expiration time of the credentials. ```go func (c *Credentials) ValidUntil() time.Time ``` -------------------------------- ### Create Gokrb5 Configuration from Reader Source: https://github.com/jcmturner/gokrb5/blob/master/USAGE.md Create a krb5 configuration instance from an io.Reader. ```go import "gopkg.in/jcmturner/gokrb5.v7/config" cfg, err := config.NewConfigFromReader(reader) ``` -------------------------------- ### Create Gokrb5 Configuration from Scanner Source: https://github.com/jcmturner/gokrb5/blob/master/USAGE.md Create a krb5 configuration instance from a bufio.Scanner. ```go import "gopkg.in/jcmturner/gokrb5.v7/config" cfg, err := config.NewConfigFromScanner(scanner) ``` -------------------------------- ### AllowedEnctypes Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/config.md Get a list of encryption types that are permitted by the current configuration. ```APIDOC ## AllowedEnctypes ### Description Get list of encryption types permitted by config. ### Method Signature ```go func (c *Config) AllowedEnctypes() []int32 ``` ### Returns - **[]int32**: Slice of allowed encryption type IDs ### Example ```go allowed := cfg.AllowedEnctypes() ``` ``` -------------------------------- ### Get SPNEGO OID Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/spnego.md Retrieves the GSS-API Object Identifier (OID) for SPNEGO. ```go func (s *SPNEGO) OID() asn1.ObjectIdentifier ``` -------------------------------- ### Get Parsed Principal Name Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/credentials.md Retrieves the parsed principal name from the credentials. ```go func (c *Credentials) CName() types.PrincipalName ``` -------------------------------- ### Create Kerberos Client with Password or Keytab Source: https://github.com/jcmturner/gokrb5/blob/master/v8/USAGE.md Instantiate a new Kerberos client using either a password or a keytab. A configuration object is required, and optional settings can be provided. ```go import "github.com/jcmturner/gokrb5/v8/client" cl := client.NewWithPassword("username", "REALM.COM", "password", cfg) cl := client.NewWithKeytab("username", "REALM.COM", kt, cfg) ``` -------------------------------- ### Get Client Credentials from CCache Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/credentials.md Extracts the client credentials from a loaded CCache object. ```go func (c *CCache) GetClientCredentials() *Credentials ``` -------------------------------- ### Create krb5 Configuration from String Source: https://github.com/jcmturner/gokrb5/blob/master/v8/USAGE.md Create Kerberos configuration from a string. The string must contain appropriate newline separations for the configuration format. ```go cfg, err := config.NewFromString(krb5Str) //String must have appropriate newline separations ``` -------------------------------- ### New Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/config.md Creates a new, empty Config struct with default LibDefaults applied. ```APIDOC ## New ### Description Create a new empty Config with default LibDefaults. ### Signature ```go func New() *Config ``` ### Returns Pointer to new Config struct with defaults applied ### Example ```go cfg := config.New() ``` ``` -------------------------------- ### Get All Ticket Entries from CCache Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/credentials.md Retrieves all ticket entries stored within a CCache object. ```go func (c *CCache) GetEntries() []CacheEntry ``` -------------------------------- ### Create Client with Keytab Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/client.md Creates a new Kerberos client authenticated using a keytab file. Requires username, realm, a loaded keytab, and Kerberos configuration. Optional settings can be provided. ```go func NewWithKeytab(username, realm string, kt *keytab.Keytab, krb5conf *config.Config, settings ...func(*Settings)) *Client ``` ```go kt, _ := keytab.Load("/etc/krb5.keytab") cfg, _ := config.Load("/etc/krb5.conf") cl := client.NewWithKeytab("jdoe", "EXAMPLE.COM", kt, cfg) ``` -------------------------------- ### Generic Service Authentication with AP_REQ Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/service.md Demonstrates how to load a service keytab, create service settings, receive and verify an AP_REQ message from a client, and access authenticated client credentials. This is useful for custom protocols or non-HTTP services. ```go package main import ( "encoding/base64" "fmt" "log" "github.com/jcmturner/gokrb5/v8/keytab" "github.com/jcmturner/gokrb5/v8/messages" "github.com/jcmturner/gokrb5/v8/service" ) func main() { // Load service keytab kt, err := keytab.Load("/etc/krb5.keytab") if err != nil { log.Fatal(err) } // Create service settings settings := service.NewSettings(kt) // Receive AP_REQ from client (base64 encoded in Authorization header) // Example: "Authorization: Negotiate YIIFczCCBW+gAwIBAa..." apReqB64 := "YIIFczCCBW+gAwIBAa..." // From HTTP header apReqBytes, _ := base64.StdEncoding.DecodeString(apReqB64) // Unmarshal AP_REQ var apReq messages.APReq apReq.Unmarshal(apReqBytes) // Verify AP_REQ ok, creds, err := service.VerifyAPREQ(&apReq, settings) if err != nil { log.Printf("Verification error: %v", err) return } if !ok { log.Printf("Invalid AP_REQ") return } // Access client information fmt.Printf("Authenticated user: %s@%s\n", creds.UserName(), creds.Domain()) } ``` -------------------------------- ### Get Password from Credentials Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/credentials.md Retrieve the password string from the credentials. Returns an empty string if no password is set. ```go func (c *Credentials) Password() string ``` -------------------------------- ### Create krb5 Configuration from Scanner Source: https://github.com/jcmturner/gokrb5/blob/master/v8/USAGE.md Create Kerberos configuration from a bufio.Scanner. This allows for line-by-line processing of configuration data. ```go cfg, err := config.NewFromScanner(scanner) ``` -------------------------------- ### Get Display Name Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/credentials.md Retrieves the display name, which may be the user's full name if from Active Directory. ```go func (c *Credentials) DisplayName() string ``` -------------------------------- ### Create Kerberos Client with Password Source: https://github.com/jcmturner/gokrb5/blob/master/USAGE.md Instantiate a Kerberos client using a username, realm, and password. A configuration object is required, and optional settings can be provided. ```go import "gopkg.in/jcmturner/gokrb5.v7/client" cl := client.NewClientWithPassword("username", "REALM.COM", "password", cfg) ``` -------------------------------- ### Load Keytab File Source: https://github.com/jcmturner/gokrb5/blob/master/v8/USAGE.md Load a standard keytab file from a specified file path. Ensure the file exists and has the correct format. ```go import "github.com/jcmturner/gokrb5/v8/keytab" ktFromFile, err := keytab.Load("/path/to/file.keytab") ``` -------------------------------- ### Load Config from File Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/config.md Loads and parses a krb5.conf file from the specified filesystem path. Handles file not found, read errors, and parsing errors for invalid formats. ```go cfg, err := config.Load("/etc/krb5.conf") if err != nil { log.Fatal(err) } ``` -------------------------------- ### Get Attribute by Key Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/credentials.md Retrieves an attribute by its string key. Returns the attribute's value and a boolean indicating if the key was found. ```go func (c *Credentials) GetAttribute(key string) (interface{}, bool) ``` -------------------------------- ### Create Kerberos Principal Names Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/types.md Demonstrates creating user, service, and TGT principal names using `types.NewPrincipalName`. Ensure the correct `nametype` and name components are provided. ```go package main import ( "fmt" "github.com/jcmturner/gokrb5/v8/types" "github.com/jcmturner/gokrb5/v8/iana/nametype" ) func main() { // User principal user := types.NewPrincipalName( nametype.KRB_NT_PRINCIPAL, "jdoe", ) fmt.Println("User:", user.PrincipalNameString()) // Service principal with instance service := types.NewPrincipalName( nametype.KRB_NT_SRV_INST, "HTTP", "host.example.com", ) fmt.Println("Service:", service.PrincipalNameString()) // TGT principal tgt := types.NewPrincipalName( nametype.KRB_NT_SRV_INST, "krbtgt", "EXAMPLE.COM", ) fmt.Println("TGT:", tgt.PrincipalNameString()) } ``` -------------------------------- ### New Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/credentials.md Create a new Credentials instance for a principal. This function initializes a Credentials struct with the provided username and realm. ```APIDOC ## New ### Description Create a new Credentials instance for a principal. ### Method `func New(username, realm string) *Credentials` ### Parameters #### Path Parameters - **username** (string) - Required - User's principal name - **realm** (string) - Required - Kerberos realm ### Returns Pointer to new Credentials struct ### Example ```go creds := credentials.New("jdoe", "EXAMPLE.COM") ``` ``` -------------------------------- ### Get SPNEGO Mechanism OID Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/gssapi.md Retrieves the Object Identifier for the SPNEGO security mechanism. Use this OID when initializing SPNEGO-based security contexts. ```go spnegoOID := gssapi.OIDSPNEGO.OID() ``` -------------------------------- ### Import Paths for gokrb5 v8 Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/README.md Demonstrates the absolute import paths for various gokrb5 modules using v8. ```go import "github.com/jcmturner/gokrb5/v8/client" import "github.com/jcmturner/gokrb5/v8/config" import "github.com/jcmturner/gokrb5/v8/keytab" import "github.com/jcmturner/gokrb5/v8/spnego" ``` -------------------------------- ### Get Group Membership SIDs Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/pac.md Retrieves all Security Identifiers (SIDs) for groups a user is a member of. Returns a slice of strings, where each string is a group SID. ```go func (ki *KerbValidationInfo) GetGroupMembershipSIDs() []string ``` ```go groupSIDs := pac.KerbValidationInfo.GetGroupMembershipSIDs() for _, sid := range groupSIDs { fmt.Printf("User is member of: %s\n", sid) } ``` -------------------------------- ### Create krb5 Configuration from Reader Source: https://github.com/jcmturner/gokrb5/blob/master/v8/USAGE.md Create Kerberos configuration from an io.Reader. This is useful for dynamic configuration sources. ```go cfg, err := config.NewFromReader(reader) ``` -------------------------------- ### Client Diagnostics Source: https://github.com/jcmturner/gokrb5/blob/master/v8/USAGE.md Investigate client configuration issues by checking required enctypes, keytab availability, and KDC resolvability. Configuration details are written to the provided io.Writer. ```go cl.Diagnostics(writer) ``` -------------------------------- ### Get Checksum Type Handler Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/crypto.md Obtain a checksum type handler by its ID using GetChecksumtype. This function allows access to specific checksum algorithms like HMAC-SHA1-96-AES256. ```Go cs, err := crypto.GetChecksumtype(16) // HMAC-SHA1-96-AES256 ``` -------------------------------- ### Load krb5 Configuration Source: https://github.com/jcmturner/gokrb5/blob/master/v8/USAGE.md Load Kerberos configuration from a file path. Ensure the file exists and is accessible. ```go import "github.com/jcmturner/gokrb5/v8/config" cfg, err := config.Load("/path/to/config/file") ``` -------------------------------- ### Check Client Configuration Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/client.md Verifies if the client has all necessary configuration values for proper operation. Returns an error detailing any missing configuration. ```go if ok, err := cl.IsConfigured(); !ok { log.Fatal("Client not configured:", err) } ``` -------------------------------- ### Get Encryption Type Handler Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/crypto.md Retrieve an encryption type handler using its ID with GetEtype. This is useful for obtaining details about supported encryption algorithms, such as key size. ```Go et, err := crypto.GetEtype(18) // AES256 if err != nil { log.Fatal(err) } fmt.Printf("Key size: %d bytes\n", et.GetKeyByteSize()) ``` -------------------------------- ### Create New Credentials Instance Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/credentials.md Creates a new Credentials instance for a given username and realm. Use this to initialize a Credentials struct with basic principal information. ```go func New(username, realm string) *Credentials ``` ```go creds := credentials.New("jdoe", "EXAMPLE.COM") ``` -------------------------------- ### Verify Token and Get Status Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/gssapi.md Verifies the integrity and validity of a token, returning a boolean status and detailed status information. Useful for checking token authenticity before proceeding. ```go ok, status := token.Verify() if !ok { fmt.Printf("Verification failed: %s\n", status.Message) } ``` -------------------------------- ### Initialize Service Settings for AP_REQ Validation Source: https://github.com/jcmturner/gokrb5/blob/master/USAGE.md Initialize the service settings with a keytab for validating client AP_REQ. Optional settings can also be provided. ```go import "gopkg.in/jcmturner/gokrb5.v7/service" s := service.NewSettings(&kt) // kt is a keytab and optional settings can also be provided. ``` -------------------------------- ### AllowedEnctypes: Get Permitted Encryption Types Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/config.md Retrieves a slice of integer IDs representing the encryption types permitted by the current configuration. Use this to ensure compatibility with allowed algorithms. ```go func (c *Config) AllowedEnctypes() []int32 ``` ```go allowed := cfg.AllowedEnctypes() ``` -------------------------------- ### Load Config from Scanner Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/config.md Parses krb5.conf content line by line using a bufio.Scanner. This is efficient for large files as it processes input incrementally. ```go file, _ := os.Open("/etc/krb5.conf") defer file.Close() scanner := bufio.NewScanner(file) cfg, err := config.NewFromScanner(scanner) ``` -------------------------------- ### HTTP Authorization Handler with PAC Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/pac.md An example HTTP handler that uses PAC information to authorize requests. It checks for authentication and specific group membership (admin group SID). ```go package main import ( "fmt" "log" "net/http" "encoding/json" "github.com/jcmturner/goidentity/v6" "github.com/jcmturner/gokrb5/v8/credentials" "github.com/jcmturner/gokrb5/v8/keytab" "github.com/jcmturner/gokrb5/v8/service" "github.com/jcmturner/gokrb5/v8/spnego" ) var adminGroupSID = "S-1-5-21-3623811015-3361044348-30300820-512" func authorizedHandler(w http.ResponseWriter, r *http.Request) { creds := goidentity.FromHTTPRequestContext(r) if creds == nil || !creds.Authenticated() { w.WriteHeader(http.StatusUnauthorized) fmt.Fprint(w, "Not authenticated") return } // Check AD group membership adCredsJSON, ok := creds.Attributes()[credentials.AttributeKeyADCredentials] if !ok { w.WriteHeader(http.StatusForbidden) fmt.Fprint(w, "AD credentials not available") return } var adCreds credentials.ADCredentials json.Unmarshal([]byte(adCredsJSON), &adCreds) // Check if user is in admin group isAdmin := false for _, sid := range adCreds.GroupMembershipSIDs { if sid == adminGroupSID { isAdmin = true break } } if !isAdmin { w.WriteHeader(http.StatusForbidden) fmt.Fprint(w, "Insufficient privileges") return } // User is authenticated and authorized fmt.Fprintf(w, "Welcome, %s!\n", adCreds.EffectiveName) fmt.Fprintf(w, "User ID: %d\n", adCreds.UserID) } func main() { kt, _ := keytab.Load("/etc/krb5.keytab") handler := spnego.SPNEGOKRB5Authenticate( http.HandlerFunc(authorizedHandler), kt, ) http.Handle("/admin", handler) log.Fatal(http.ListenAndServe(":8080", nil)) } ``` -------------------------------- ### Load Keytab and Create Logger for SPNEGO Source: https://github.com/jcmturner/gokrb5/blob/master/USAGE.md Load the keytab file and create a logger instance required for configuring the SPNEGO/Kerberos HTTP service wrapper. ```go kt, err := keytab.Load("/path/to/file.keytab") l := log.New(os.Stderr, "GOKRB5 Service: ", log.Ldate|log.Ltime|log.Lshortfile) ``` -------------------------------- ### Load Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/config.md Loads and parses a krb5.conf file from a specified filesystem path. ```APIDOC ## Load ### Description Load and parse krb5.conf file from filesystem path. ### Signature ```go func Load(filename string) (*Config, error) ``` ### Parameters #### Path Parameters - **filename** (string) - Required - Path to krb5.conf file ### Returns - (*Config, error) ### Throws - error: File not found or read error - error: Parse error if file format invalid ### Example ```go cfg, err := config.Load("/etc/krb5.conf") if err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### Get Service Ticket Source: https://github.com/jcmturner/gokrb5/blob/master/USAGE.md Request a service ticket and session key for a given Service Principal Name (SPN). This method efficiently uses the client's cache, renewing tickets as needed. ```go tkt, key, err := cl.GetServiceTicket("HTTP/host.test.gokrb5") ``` -------------------------------- ### Load Keytab from Filesystem Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/keytab.md Loads and parses a keytab file from a specified filesystem path. Ensure the file exists and has appropriate read permissions. Handles potential errors during file access or parsing. ```go kt, err := keytab.Load("/etc/krb5.keytab") if err != nil { log.Fatal(err) } ``` -------------------------------- ### Load Gokrb5 Configuration Source: https://github.com/jcmturner/gokrb5/blob/master/USAGE.md Load krb5 configuration from a file path. Ensure the configuration file follows the standard krb5.conf format. ```go import "gopkg.in/jcmturner/gokrb5.v7/config" cfg, err := config.Load("/path/to/config/file") ``` -------------------------------- ### gokrb5 Package Structure Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/MANIFEST.md This diagram shows the directory structure of the gokrb5 project and maps each directory to its corresponding documentation file. Useful for understanding the project's organization and finding specific module documentation. ```go github.com/jcmturner/gokrb5/v8/ ├── client/ → client.md ├── service/ → service.md ├── spnego/ → spnego.md ├── config/ → config.md ├── keytab/ → keytab.md ├── credentials/ → credentials.md ├── types/ → types.md ├── messages/ → messages.md ├── crypto/ → crypto.md ├── iana/ → iana.md ├── gssapi/ → gssapi.md ├── pac/ → pac.md └── krberror/ → errors.md ``` -------------------------------- ### Print Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/client.md Writes detailed client configuration and state to an io.Writer (credentials, sessions, cache, keytab). ```APIDOC ## Print ### Description Write detailed client configuration and state to an io.Writer (credentials, sessions, cache, keytab). ### Method func (cl *Client) Print(w io.Writer) ### Parameters #### Path Parameters - **w** (io.Writer) - Required - Writer for output ### Example ```go cl.Print(os.Stdout) ``` ``` -------------------------------- ### Print Client State Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/client.md Writes detailed client configuration and state, including credentials, sessions, and cache, to a specified io.Writer. ```go cl.Print(os.Stdout) ``` -------------------------------- ### Set Display Name Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/credentials.md Sets the display name for the credentials. ```go func (c *Credentials) SetDisplayName(displayName string) ``` -------------------------------- ### Load CCache from File Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/credentials.md Loads a Kerberos credentials cache file from the specified path. Handles file not found or read errors, as well as invalid cache formats. ```go func LoadCCache(filename string) (*CCache, error) ``` ```go ccache, err := credentials.LoadCCache("/tmp/krb5cc_1000") ``` -------------------------------- ### Client Authentication with Password Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/README.md Authenticates a client using a username, realm, and password. Ensure the Kerberos configuration file is correctly loaded. ```go cfg, _ := config.Load("/etc/krb5.conf") cl := client.NewWithPassword("user", "REALM.COM", "pass", cfg) err := cl.Login() if err != nil { log.Fatal(err) } ``` -------------------------------- ### NewSettings Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/service.md Creates new service settings with optional configuration functions. It requires a keytab for the service principal and accepts various options to customize authentication behavior. ```APIDOC ## NewSettings ### Description Creates new service settings with optional configuration functions. It requires a keytab for the service principal and accepts various options to customize authentication behavior. ### Function Signature ```go func NewSettings(kt *keytab.Keytab, options ...func(*Settings)) *Settings ``` ### Parameters #### Path Parameters * **kt** (*keytab.Keytab) - Required - Service keytab containing service principal(s) #### Query Parameters * **options** (...func(*Settings)) - Optional - Optional configuration functions ### Request Example ```go kt, _ := keytab.Load("/etc/krb5.keytab") logger := log.New(os.Stderr, "SERVICE: ", log.Ldate|log.Ltime) settings := service.NewSettings(kt, service.Logger(logger), service.MaxClockSkew(5 * time.Minute), ) ``` ### Returns * **Settings** (*Settings) - The configured service settings object. ``` -------------------------------- ### Run Client Diagnostics Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/client.md Executes configuration checks and writes diagnostic information to a provided io.Writer. Validates keytab enctypes and KDC resolution. ```go err := cl.Diagnostics(os.Stderr) if err != nil { log.Fatal("Diagnostic errors:", err) } ``` -------------------------------- ### Load Keytab from File Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/keytab.md Loads and parses a keytab file from a specified filesystem path. Handles potential file access and format errors. ```APIDOC ## Load Load and parse a keytab file from filesystem path. ```go func Load(filename string) (*Keytab, error) ``` | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | filename | string | — | Path to keytab file (typically /etc/krb5.keytab) | **Returns:** (*Keytab, error) **Throws:** - error: File not found or permission denied - error: Invalid keytab format - error: Unsupported keytab version **Example:** ```go kt, err := keytab.Load("/etc/krb5.keytab") if err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### NewFromScanner Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/config.md Parses krb5.conf content from a bufio.Scanner. ```APIDOC ## NewFromScanner ### Description Parse krb5.conf from a bufio.Scanner. ### Signature ```go func NewFromScanner(s *bufio.Scanner) (*Config, error) ``` ### Parameters #### Path Parameters - **s** (*bufio.Scanner) - Required - Scanner providing config lines ### Returns - (*Config, error) ### Example ```go file, _ := os.Open("/etc/krb5.conf") defer file.Close() scanner := bufio.NewScanner(file) cfig, err := config.NewFromScanner(scanner) ``` ``` -------------------------------- ### Load Config from String Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/config.md Parses krb5.conf content directly from a string. Ensure the string uses proper newline separations. Throws a parse error for invalid formats. ```go confStr := `[libdefaults] default_realm = EXAMPLE.COM [realms] EXAMPLE.COM = { kdc = kdc.example.com:88 } ` cfg, err := config.NewFromString(confStr) ``` -------------------------------- ### NewFromReader Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/config.md Parses krb5.conf content from an io.Reader. ```APIDOC ## NewFromReader ### Description Parse krb5.conf from an io.Reader. ### Signature ```go func NewFromReader(r io.Reader) (*Config, error) ``` ### Parameters #### Path Parameters - **r** (io.Reader) - Required - Reader providing config content ### Returns - (*Config, error) ### Example ```go file, _ := os.Open("/etc/krb5.conf") defer file.Close() cfig, err := config.NewFromReader(file) ``` ``` -------------------------------- ### NewWithKeytab Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/client.md Creates a new Kerberos client authenticated using a keytab file. It manages credentials, configuration, sessions, and service ticket cache. ```APIDOC ## NewWithKeytab ### Description Creates a new Kerberos client authenticated using a keytab file. It manages credentials, configuration, sessions, and service ticket cache. ### Signature ```go func NewWithKeytab(username, realm string, kt *keytab.Keytab, krb5conf *config.Config, settings ...func(*Settings)) *Client ``` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters Table | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | username | string | — | Username for authentication | | realm | string | — | Kerberos realm | | kt | *keytab.Keytab | — | Parsed keytab file | | krb5conf | *config.Config | — | Kerberos configuration | | settings | ...func(*Settings) | — | Optional client settings functions | ### Returns Pointer to initialized Client struct ### Example ```go kt, _ := keytab.Load("/etc/krb5.keytab") cfg, _ := config.Load("/etc/krb5.conf") cl := client.NewWithKeytab("jdoe", "EXAMPLE.COM", kt, cfg) ``` ``` -------------------------------- ### Using IANA Error Codes for Client Login Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/iana.md Demonstrates how to use IANA error codes to check for specific Kerberos errors during client login. This is useful for handling pre-authentication requirements, bad passwords, or clock skew issues. ```go package main import ( "log" "github.com/jcmturner/gokrb5/v8/client" "github.com/jcmturner/gokrb5/v8/config" "github.com/jcmturner/gokrb5/v8/iana/errorcode" "github.com/jcmturner/gokrb5/v8/messages" ) func main() { cfg, _ := config.Load("/etc/krb5.conf") cl := client.NewWithPassword("user", "REALM.COM", "pass", cfg) err := cl.Login() if err != nil { // Check specific error type if krbErr, ok := err.(messages.KRBError); ok { switch krbErr.ErrorCode { case errorcode.KDC_ERR_PREAUTH_REQUIRED: log.Fatal("Pre-authentication required") case errorcode.KDC_ERR_BADPWD: log.Fatal("Bad password") case errorcode.KDC_ERR_SKEW: log.Fatal("Clock skew too great") default: log.Fatalf("KDC error: %v", krbErr.ErrorCode) } } } } ``` -------------------------------- ### HTTP Service Handler with SPNEGO Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/README.md Sets up an HTTP handler that authenticates incoming requests using SPNEGO with Kerberos. Requires a keytab file for the service. ```go kt, _ := keytab.Load("/etc/krb5.keytab") handler := spnego.SPNEGOKRB5Authenticate( appHandler, kt, service.Logger(logger), ) http.Handle("/", handler) ``` -------------------------------- ### Create New Empty Keytab Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/keytab.md Use this constructor to create a new, empty Keytab object. It returns a pointer to the newly created Keytab. ```go kt := keytab.New() ``` -------------------------------- ### Config Methods Source: https://github.com/jcmturner/gokrb5/blob/master/_autodocs/API-SUMMARY.md Methods for retrieving information from the Kerberos configuration. ```APIDOC ## GetKDCs ### Description Get KDC addresses for a given realm. ### Signature `(realm string, tcp bool) (int, []string, error)` ``` ```APIDOC ## GetRealm ### Description Lookup the realm for a given domain. ### Signature `(domain string) (string, error)` ``` ```APIDOC ## ResolveCName ### Description Canonicalize a principal name. ### Signature `(cname *types.PrincipalName) *types.PrincipalName` ```