High-Level API
The high-level API contains three main classes for interacting with GSSAPI,
representing the primary abstractions that GSSAPI provides:
Name
, Credentials
, and
SecurityContext
.
Note
Classes in the high-level API inherit from the corresponding classes in the low-level API, and thus may be passed in to low-level API functions.
Warning
All methods in both the high-level and low-level APIs may throw the generic
GSSError
exception.
Main Classes
Names
- class Name(base: Name | bytes | str | None = None, name_type: OID | None = None, token: bytes | None = None, composite: bool = False)[source]
A GSSAPI Name
This class represents a GSSAPI name which may be used with and/or returned by other GSSAPI methods.
It inherits from the low-level GSSAPI
Name
class, and thus may used with both low-level and high-level API methods.This class may be pickled and unpickled, as well as copied.
The
str
andbytes
methods may be used to retrieve the text of the name.Note
Name strings will be automatically converted to and from unicode strings as appropriate. If a method is listed as returning a
str
object, it will return a unicode string.The encoding used will be python-gssapi’s current encoding, which defaults to UTF-8.
The constructor can be used to “import” a name from a human readable representation, or from a token, and can also be used to convert a low-level
gssapi.raw.names.Name
object into a high-level object.If a
Name
object from the low-level API is passed as the base argument, it will be converted into a high-level object.If the token argument is used, the name will be imported using the token. If the token was exported as a composite token, pass composite=True.
Otherwise, a new name will be created, using the base argument as the human-readable string and the name_type argument to denote the name type.
- Raises:
- display_as(name_type: OID) str [source]
Display this name as the given name type.
This method attempts to display the current
Name
using the syntax of the givenNameType
, if possible.Warning
In MIT krb5 versions below 1.13.3, this method can segfault if the name was not originally created with a name_type that was not
None
(even in cases when aname_type
is later “added”, such as viacanonicalize()
). Do not use this method unless you are sure the above conditions can never happen in your code.Warning
In addition to the above warning, current versions of MIT krb5 do not actually fully implement this method, and it may return incorrect results in the case of canonicalized names.
requires the RFC 6680 extension
- export(composite: bool = False) bytes [source]
Export this name as a token.
This method exports the name into a byte string which can then be imported by using the token argument of the constructor.
- canonicalize(mech: OID) Name [source]
Canonicalize a name with respect to a mechanism.
This method returns a new
Name
that is canonicalized according to the given mechanism.- Parameters:
- Returns:
the canonicalized name
- Return type:
- Raises:
- property is_mech_name: bool
Whether or not this name is a mechanism name (requires the RFC 6680 extension)
- property attributes: MutableMapping | None
The attributes of this name (requires the RFC 6680 extension)
The attributes are presenting in the form of a
MutableMapping
(a dict-like object).Retrieved values will always be in the form of
frozenset
.When assigning values, if iterables are used, they be considered to be the set of values for the given attribute. If a non-iterable is used, it will be considered a single value, and automatically wrapped in an iterable.
Note
String types (includes
bytes
) are not considered to be iterables in this case.
Credentials
- class Credentials(base: Creds | None = None, token: bytes | None = None, name: Name | None = None, lifetime: int | None = None, mechs: Iterable[OID] | None = None, usage: str = 'both', store: Dict[bytes | str, bytes | str] | None = None)[source]
GSSAPI Credentials
This class represents a set of GSSAPI credentials which may be used with and/or returned by other GSSAPI methods.
It inherits from the low-level GSSAPI
Creds
class, and thus may used with both low-level and high-level API methods.If your implementation of GSSAPI supports the credentials import-export extension, you may pickle and unpickle this object.
The constructor either acquires or imports a set of GSSAPI credentials.
If the base argument is used, an existing
Creds
object from the low-level API is converted into a high-level object.If the token argument is used, the credentials are imported using the token, if the credentials import-export extension is supported (requires the cred_imp_exp extension).
Otherwise, the credentials are acquired as per the
acquire()
method.- Raises:
- classmethod acquire(name: Name | None = None, lifetime: int | None = None, mechs: Iterable[OID] | None = None, usage: str = 'both', store: Dict[bytes | str, bytes | str] | None = None) AcquireCredResult [source]
Acquire GSSAPI credentials
This method acquires credentials. If the store argument is used, the credentials will be acquired from the given credential store (if supported). Otherwise, the credentials are acquired from the default store.
The credential store information is a dictionary containing mechanisms-specific keys and values pointing to a credential store or stores.
Using a non-default store requires support for the credentials store extension.
- Parameters:
name (Name) – the name associated with the credentials, or None for the default name
lifetime (int) – the desired lifetime of the credentials in seconds, or None for indefinite
mechs (list) – the desired
MechType
OIDs to be used with the credentials, or None for the default setusage (str) – the usage for the credentials – either ‘both’, ‘initiate’, or ‘accept’
store (dict) – the credential store information pointing to the credential store from which to acquire the credentials, or None for the default store (requires the cred_store extension)
- Returns:
the acquired credentials and information about them
- Return type:
- Raises:
- store(store: Dict[bytes | str, bytes | str] | None = None, usage: str = 'both', mech: OID | None = None, overwrite: bool = False, set_default: bool = False) StoreCredResult [source]
Store these credentials into the given store
This method stores the current credentials into the specified credentials store. If the default store is used, support for RFC 5588 is required. Otherwise, support for the credentials store extension is required.
requires the RFC 5588 extension or requires the cred_store extension
- Parameters:
store (dict) – the store into which to store the credentials, or None for the default store.
usage (str) – the usage to store the credentials with – either ‘both’, ‘initiate’, or ‘accept’
mech (OID) – the
MechType
to associate with the stored credentialsoverwrite (bool) – whether or not to overwrite existing credentials stored with the same name, etc
set_default (bool) – whether or not to set these credentials as the default credentials for the given store.
- Returns:
the results of the credential storing operation
- Return type:
- Raises:
- impersonate(name: Name | None = None, lifetime: int | None = None, mechs: Iterable[OID] | None = None, usage: str = 'initiate') Credentials [source]
Impersonate a name using the current credentials
This method acquires credentials by impersonating another name using the current credentials.
requires the s4u extension
- Parameters:
name (Name) – the name to impersonate
lifetime (int) – the desired lifetime of the new credentials in seconds, or None for indefinite
mechs (list) – the desired
MechType
OIDs for the new credentialsusage (str) – the desired usage for the new credentials – either ‘both’, ‘initiate’, or ‘accept’. Note that some mechanisms may only support ‘initiate’.
- Returns:
the new credentials impersonating the given name
- Return type:
- inquire(name: bool = True, lifetime: bool = True, usage: bool = True, mechs: bool = True) InquireCredResult [source]
Inspect these credentials for information
This method inspects these credentials for information about them.
- Parameters:
- Returns:
the information about the credentials, with None used when the corresponding argument was False
- Return type:
- Raises:
- inquire_by_mech(mech: OID, name: bool = True, init_lifetime: bool = True, accept_lifetime: bool = True, usage: bool = True) InquireCredByMechResult [source]
Inspect these credentials for per-mechanism information
This method inspects these credentials for per-mechanism information about them.
- Parameters:
mech (OID) – the mechanism for which to retrieve the information
name (bool) – get the name associated with the credentials
init_lifetime (bool) – get the remaining initiate lifetime for the credentials in seconds
accept_lifetime (bool) – get the remaining accept lifetime for the credentials in seconds
usage (bool) – get the usage for the credentials
- Returns:
the information about the credentials, with None used when the corresponding argument was False
- Return type:
- add(name: Name, mech: OID, usage: str = 'both', init_lifetime: int | None = None, accept_lifetime: int | None = None, impersonator: Creds | None = None, store: Dict[bytes | str, bytes | str] | None = None) Credentials [source]
Acquire more credentials to add to the current set
This method works like
acquire()
, except that it adds the acquired credentials for a single mechanism to a copy of the current set, instead of creating a new set for multiple mechanisms. Unlikeacquire()
, you cannot pass None desired name or mechanism.If the impersonator argument is used, the credentials will impersonate the given name using the impersonator credentials (requires the s4u extension).
If the store argument is used, the credentials will be acquired from the given credential store (requires the cred_store extension). Otherwise, the credentials are acquired from the default store.
The credential store information is a dictionary containing mechanisms-specific keys and values pointing to a credential store or stores.
Note that the store argument is not compatible with the impersonator argument.
- Parameters:
name (Name) – the name associated with the credentials
mech (OID) – the desired
MechType
to be used with the credentialsusage (str) – the usage for the credentials – either ‘both’, ‘initiate’, or ‘accept’
init_lifetime (int) – the desired initiate lifetime of the credentials in seconds, or None for indefinite
accept_lifetime (int) – the desired accept lifetime of the credentials in seconds, or None for indefinite
impersonator (Credentials) – the credentials to use to impersonate the given name, or None to not acquire normally (requires the s4u extension)
store (dict) – the credential store information pointing to the credential store from which to acquire the credentials, or None for the default store (requires the cred_store extension)
- Returns:
the credentials set containing the current credentials and the newly acquired ones.
- Return type:
- Raises:
- export() bytes [source]
Export these credentials into a token
This method exports the current credentials to a token that can then be imported by passing the token argument to the constructor.
This is often used to pass credentials between processes.
requires the cred_imp_exp extension
- Returns:
the exported credentials in token form
- Return type:
Security Contexts
- class SecurityContext(base: SecurityContext | None = None, token: bytes | None = None, name: Name | None = None, creds: Credentials | None = None, lifetime: int | None = None, flags: int | None = None, mech: OID | None = None, channel_bindings: ChannelBindings | None = None, usage: str | None = None)[source]
A GSSAPI Security Context
This class represents a GSSAPI security context that may be used with and/or returned by other GSSAPI methods.
It inherits from the low-level GSSAPI
SecurityContext
class, and thus may used with both low-level and high-level API methods.This class may be pickled and unpickled (the attached delegated credentials object will not be preserved, however).
The constructor creates a new security context, but does not begin the initiate or accept process.
If the base argument is used, an existing
SecurityContext
object from the low-level API is converted into a high-level object.If the token argument is passed, the security context is imported using the token.
Otherwise, a new security context is created.
If the usage argument is not passed, the constructor will attempt to detect what the appropriate usage is based on either the existing security context (if base or token are used) or the argument set.
For a security context of the initiate usage, the name argument must be used, and the creds, mech, flags, lifetime, and channel_bindings arguments may be used as well.
For a security context of the accept usage, the creds and channel_bindings arguments may optionally be used.
- get_signature(message: bytes) bytes [source]
Calculate the signature for a message.
This method calculates the signature (called a MIC) for the given message, which may be then used with
verify_signature()
to confirm the validity of the signature. This is useful if you wish to transmit the message signature and message in your own format.- Parameters:
message (bytes) – the input message
- Returns:
the message signature
- Return type:
- Raises:
- verify_signature(message: bytes, mic: bytes) int [source]
Verify the signature for a message.
This method verifies that a signature (generated by
get_signature()
is valid for the given message.If the signature is valid, the method will return. Otherwise, it will raise an error.
- Parameters:
- Returns:
the QoP used.
- Return type:
- Raises:
BadMICError – the signature was not valid
- wrap(message: bytes, encrypt: bool) WrapResult [source]
Wrap a message, optionally with encryption
This wraps a message, signing it and optionally encrypting it.
- Parameters:
- Returns:
the wrapped message and details about it (e.g. whether encryption was used succesfully)
- Return type:
- Raises:
- unwrap(message: bytes) UnwrapResult [source]
Unwrap a wrapped message.
This method unwraps/unencrypts a wrapped message, verifying the signature along the way.
- Parameters:
message (bytes) – the message to unwrap/decrypt
- Returns:
the unwrapped message and details about it (e.g. wheter encryption was used)
- Return type:
- Raises:
- encrypt(message: bytes) bytes [source]
Encrypt a message.
This method wraps and encrypts a message, similarly to
wrap()
. The difference is that encryption is always used, and the method will raise an exception if this is not possible. Additionally, this method simply returns the encrypted message directly.- Parameters:
message (bytes) – the message to encrypt
- Returns:
the encrypted message
- Return type:
- Raises:
EncryptionNotUsed – the encryption could not be used
- decrypt(message: bytes) bytes [source]
Decrypt a message.
This method decrypts and unwraps a message, verifying the signature along the way, similarly to
unwrap()
. The difference is that this method will raise an exception if encryption was established by the context and not used, and simply returns the decrypted message directly.- Parameters:
message (bytes) – the encrypted message
- Returns:
the decrypted message
- Return type:
- Raises:
EncryptionNotUsed – encryption was expected, but not used
- get_wrap_size_limit(desired_output_size: int, encrypted: bool = True) int [source]
Calculate the maximum message size for a given wrapped message size.
This method calculates the maximum input message size for a given maximum wrapped/encrypted message size.
- Parameters:
- Returns:
the maximum input message size
- Return type:
- Raises:
- process_token(token: bytes) None [source]
Process an output token asynchronously.
This method processes an output token even when the security context was not expecting it.
Warning
This method is deprecated.
- Parameters:
token (bytes) – the token to process
- Raises:
- export() bytes [source]
Export a security context.
This method exports a security context, allowing it to be passed between processes.
- Returns:
the exported security context
- Return type:
- Raises:
- property delegated_creds: Credentials | None
The credentials delegated from the initiator to the acceptor
Warning
This value will not be preserved across picklings. These should be separately exported and transferred.
- step(token: bytes | None = None) bytes | None [source]
Perform a negotation step.
This method performs a negotiation step based on the usage type of this context. If __DEFER_STEP_ERRORS__ is set to True on the class, this method will return a token, even when exceptions would be thrown. The generated exception will be thrown on the next method call or property lookup on the context. This is the default behavior.
This method should be used in a while loop, as such:
input_token = None try: while not ctx.complete: output_token = ctx.step(input_token) if not output_token: break input_token = send_and_receive(output_token) except GSSError as e: handle_the_issue()
Tip
Disabling __DEFER_STEP_ERRORS__ is rarely necessary. When this method is used in a loop (as above), __DEFER_STEP_ERRORS__ will ensure that you always send an error token when it’s available, keeping the other end of the security context updated with the status of the negotiation.
- Parameters:
token (bytes) – the input token from the other participant’s step
- Returns:
the output token to send to the other participant
- Return type:
- Raises:
ExpiredTokenError – (initiate only)
BadNameTypeError – (initiate only)
BadNameError – (initiate only)
Enums and Helper Classes
The following enumerations from the low-level API are also
used with the high-level API. For convenience, they are
imported in the high-level API gssapi
module:
- class NameType[source]
Bases:
object
- anonymous = <OID 1.3.6.1.5.6.3>
- composite_export = <OID 1.3.6.1.5.6.6>
- export = <OID 1.3.6.1.5.6.4>
- hostbased_service = <OID 1.2.840.113554.1.2.1.4>
- kerberos_principal = <OID 1.2.840.113554.1.2.2.1>
- krb5_nt_principal_name = <OID 1.2.840.113554.1.2.2.1>
- machine_uid = <OID 1.2.840.113554.1.2.1.2>
- string_uid = <OID 1.2.840.113554.1.2.1.3>
- user = <OID 1.2.840.113554.1.2.1.1>
- class RequirementFlag(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]
Bases:
IntEnum
The ok_as_delegate
flag corresponds to the C level flag
GSS_C_DELEG_POLICY_FLAG
. This flag is similar to delegate_to_peer
except it only delegates if the KDC delegation policies for the service
principal allow it to use delegation. This is typically used on Microsoft
domain environments to control whether constrained or unconstrained delegation
is allowed for a service principal. By setting this flag, the delegation
process follows the same behaviour as delegation on SSPI/Windows.
Here are the four cases when either of these flags are set or not.
- Neither flag set
No delegation occurs.
- delegate_to_peer
Always try to delegate regardless of the KDC delegation policies.
delegate_to_peer
is set in the return flags if successful.- ok_as_delegate
Try to delegate but only if the KDC trusts the service principal for delegation.
delegate_to_peer
andok_as_delegate
are set in the return flags if successful.- delegate_to_peer | ok_as_delegate
Acts like
delegate_to_peer
being set but will also setok_as_delegate
in the return flags if the service principal was trusted for delegation by the KDC.
- class AddressType(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]
Bases:
IntEnum
Similarly, there are a couple classes from the low-level API that are imported into the high-level API module. These classes are less likely to be used directly by a user, but are returned by several methods:
- class IntEnumFlagSet(enum, flags=None)[source]
Bases:
GenericFlagSet
Exceptions
The high-level API can raise all of the exceptions that the low-level API can raise in addition to several other high-level-specific exceptions:
- exception GSSError(maj_code, min_code, *args, **kwargs)[source]
Bases:
Exception
- MESSAGE = 'Major ({maj_stat}): {maj_str}, Minor ({min_stat}): {min_str}'
- exception GeneralError(minor_message: str, **kwargs: str)[source]
Bases:
Exception
A General High-Level API Error
- MAJOR_MESSAGE = 'General error'
- FMT_STR = '{maj}: {min}.'
- exception UnknownUsageError(minor_message: str, **kwargs: str)[source]
Bases:
GeneralError
An Error indicating an unknown usage type
- MAJOR_MESSAGE = 'Unable to determine {obj} usage'
- exception EncryptionNotUsed(minor_message: str, unwrapped_message: bytes | None = None, **kwargs: str)[source]
Bases:
GeneralError
An Error indicating that encryption was requested, but not used
- MAJOR_MESSAGE = 'Confidentiality was requested, but not used'
- exception BadChannelBindingsError(maj_code, min_code, *args, **kwargs)[source]
Bases:
GSSError
- ROUTINE_CODE = 262144
- exception BadMICError(maj_code, min_code, *args, **kwargs)[source]
Bases:
GSSError
- ROUTINE_CODE = 393216
- exception BadMechanismError(maj_code, min_code, *args, **kwargs)[source]
Bases:
GSSError
- ROUTINE_CODE = 65536
- exception BadNameError(maj_code, min_code, *args, **kwargs)[source]
Bases:
GSSError
- ROUTINE_CODE = 131072
- exception BadNameTypeError(maj_code, min_code, *args, **kwargs)[source]
Bases:
GSSError
- ROUTINE_CODE = 196608
- exception BadQoPError(maj_code, min_code, *args, **kwargs)[source]
Bases:
GSSError
- ROUTINE_CODE = 917504
- exception BadStatusError(maj_code, min_code, *args, **kwargs)[source]
Bases:
GSSError
- ROUTINE_CODE = 327680
- exception DuplicateCredentialsElementError(maj_code, min_code, *args, **kwargs)[source]
Bases:
GSSError
- ROUTINE_CODE = 1114112
- exception DuplicateTokenError(maj_code, min_code, *args, **kwargs)[source]
Bases:
SupplementaryError
- SUPPLEMENTARY_CODE = 2
- exception ExpiredContextError(maj_code, min_code, *args, **kwargs)[source]
Bases:
GSSError
- ROUTINE_CODE = 786432
- exception ExpiredCredentialsError(maj_code, min_code, *args, **kwargs)[source]
Bases:
GSSError
- ROUTINE_CODE = 720896
- exception ExpiredTokenError(maj_code, min_code, *args, **kwargs)[source]
Bases:
SupplementaryError
- SUPPLEMENTARY_CODE = 4
- exception InvalidCredentialsError(maj_code, min_code, *args, **kwargs)[source]
Bases:
GSSError
- ROUTINE_CODE = 655360
- exception InvalidTokenError(maj_code, min_code, *args, **kwargs)[source]
Bases:
GSSError
- ROUTINE_CODE = 589824
- exception MalformedParameterError(maj_code, min_code, *args, **kwargs)[source]
Bases:
GSSError
- CALLING_CODE = 50331648
- exception MechanismNameRequiredError(maj_code, min_code, *args, **kwargs)[source]
Bases:
GSSError
- ROUTINE_CODE = 1179648
- exception MissingContextError(maj_code, min_code, *args, **kwargs)[source]
Bases:
GSSError
- ROUTINE_CODE = 524288
- exception MissingCredentialsError(maj_code, min_code, *args, **kwargs)[source]
Bases:
GSSError
- ROUTINE_CODE = 458752
- exception NameReadError(maj_code, min_code, *args, **kwargs)[source]
Bases:
ParameterReadError
,BadNameError
- exception NameTypeReadError(maj_code, min_code, *args, **kwargs)[source]
Bases:
ParameterReadError
,BadNameTypeError
Bases:
GSSError
- exception ParameterReadError(maj_code, min_code, *args, **kwargs)[source]
Bases:
GSSError
- CALLING_CODE = 16777216
- exception ParameterWriteError(maj_code, min_code, *args, **kwargs)[source]
Bases:
GSSError
- CALLING_CODE = 33554432
- exception TokenOutOfSequenceError(maj_code, min_code, *args, **kwargs)[source]
Bases:
SupplementaryError
- exception TokenReadError(maj_code, min_code, *args, **kwargs)[source]
Bases:
ParameterReadError
,InvalidTokenError
- exception TokenTooEarlyError(maj_code, min_code, *args, **kwargs)[source]
Bases:
TokenOutOfSequenceError
- SUPPLEMENTARY_CODE = 16
- exception TokenTooLateError(maj_code, min_code, *args, **kwargs)[source]
Bases:
TokenOutOfSequenceError
- SUPPLEMENTARY_CODE = 8