draxoft.auth.pam

This module provides a Python-style interface to PAM’s C API; all functionality is exposed through the handle class and its instances.

Due to the Python GC, there is no need to explicitly close handles – simply allow the GC to reclaim them, or use the del statement to immediately clean up. For this reason, there is no direct analog to pam_end(3).

class handle(**parameters)

Represents a PAM handle.

Parameters:
  • service – specifies the PAM service used
  • user – associates this handle with a specific user
  • conv – this handle’s conversation callback
  • delay – this handle’s delay callback (if the fail delay API is supported)
  • data – opaque data passed into any associated callbacks
Raises:
  • TypeError – invalid parameters
  • OSError – error allocating low-level object
  • PamError – PAM library error

All of the parameters have reasonable defaults – for authenticating the user running the program interactively.

Other uses will require either supplying values in the constructor call or populating the instance attributes afterwards.

Authentication

handle.authenticate(silent=False, disallow_null_token=False) → bool

Authenticates the user associated with this handle.

Parameters:
  • silent – do not emit any messages
  • disallow_null_token – fail if the user’s authentication token is None
>>> from draxoft.auth import pam
>>> import random
>>> h = pam.handle()
>>> h.user = ''.join(random.sample('abcdefghijklmnopqrstuvwxyz', 7))
>>> h.user 
fbvqrpo
>>> h.conv = lambda style,msg,data: 'password'
>>> h.authenticate()
Traceback (most recent call last):
   ...
pam.PamError: [Errno 13] unknown user
>>> try:
...     h.authenticate()
... except pam.PamError, e:
...     e.errno == pam.PAM_USER_UNKNOWN
True

Conversation callback

handle.conv
Signature :callback(style, message, data)

Conversation callback. Provides a conversation callback for retrieving user IDs and authentication tokens.

The style parameter specifies the prompt style, which implies the type of data being collected or displayed – PAM_PROMPT_ECHO_OFF for passwords, PAM_PROMPT_ECHO_ON for user names, PAM_ERROR_MSG for error messages, and PAM_TEXT_INFO for informational messages. The message parameter is the text to be displayed, if applicable, and data is the data attribute.

Defaults to _conv_callback().

handle.data

Opaque data passed into callback functions.

Message styles

PAM_PROMPT_ECHO_OFF

Display a prompt and accept the user’s response without echoing it to the terminal. This is commonly used for passwords.

PAM_PROMPT_ECHO_ON

Display a prompt and accept the user’s response, echoing it to the terminal. This is commonly used for user names and one-time passphrases.

PAM_ERROR_MSG

Display an error message.

PAM_TEXT_INFO

Display an informational message.

Account management

handle.acct_mgmt(silent=False, disallow_null_token=False)

Verifies and enforces account restrictions after the user has been authenticated.

Credential management

handle.establish_credentials(silent=False)

Establish the credentials of the target user.

handle.delete_credentials(silent=False)

Revoke all established credentials.

handle.reinitialize_credentials(silent=False)

Fully reinitialize credentials.

handle.refresh_credentials(silent=False)

Refresh credentials.

Session management

handle.open_session(silent=False)

Sets up a user session for a previously authenticated user.

handle.close_session(silent=False)

Tears down a previously-established user session.

Environment

handle.environment

Mapping from environment variable names to values, both strings.

Warning

Direct references to this object are unsafe! Do not assign it to a variable or in any other way store its value without a copy operation.

The implementation of this object is closely linked with that of the parent handle in a way that creates circular references. As a result, no reference is stored for the parent object – which means a reference to an environment attribute could well access reclaimed memory when used or garbage collected, potentially causing a crash.

This should be considered a bug and will be fixed “Real Soon Now.”

If the 'unsetenv' extension is provided, variables may be removed using the del operator.

>>> h = pam.handle()
>>> h.environment['answer'] = 42   # the input can be a Python object...
>>> h.environment['answer']        # ...but the output will be a string.
'42'
>>> if 'unsetenv' in pam.extensions:
...     del h.environment['answer']
...     'answer' not in h.environment
... else:
...     'answer' in h.environment
...
True
handle.elevated

The environment attribute may contain sensitive information, particularly after a call to authenticate(). By default, this information will be removed. If this module is being run effective-user-ID 0, this attribute can be set to True to prevent this scrubbing.

>>> h = pam.handle()
>>> h.elevated
False
>>> h.elevated = True
Traceback (most recent call last):
   ...
OSError: [Errno 13] Permission denied

Fail delay

Only supported/defined if 'fail_delay' in extensions.

Warning

The fail delay API is experimental and poorly tested.

Due to development environment, there is little occasion to test the Linux-PAM-specific features. Any bug reports or further testing will be welcomed.

See also

pam_fail_delay(3)
PAM man page describing the fail delay API in more detail.
handle.fail_delay(usec)

Provides a mechanism by which an application can suggest a minimum delay of usec microseconds.

The handle records the longest time requested; should authenticate() fail, the return to the application is delayed by an amount of time randomly distributed (by up to 25%) about this longest value.

handle.delay
Signature :callback(rc, usec, data)

This callback allows an application to control the mechanism by which the PAM fail delay is implemented.

For some applications, a blocking delay between failure and return may be unacceptable. Single-threaded server applications, for example, might prefer to block just the client’s queued requests instead of the server itself.

The rc argument is the last return code; usec is the requested delay (in microseconds) and data is the opaque data.

The default is None, in which case fail delay (if any) is entirely controlled by the fail_delay() method.

Errors

exception PamError

Base class: EnvironmentError

Wrapper class for errors occurring in the PAM library. Nearly every handle method or property may raise these in event of an internal error.

strerror

Describes the error “in plain English” suitable for display.

errno

One of the error codes listed below. Unfortunately, this value is an integer and therefore may carry little meaning for the recipient.

error codes
Error Description
PAM_ABORT
General failure.
PAM_ACCT_EXPIRED
User account has expired.
PAM_AUTHINFO_UNAVAIL
Authentication information is unavailable.
PAM_AUTHTOK_DISABLE_AGING
Authentication token aging disabled.
PAM_AUTHTOK_ERR
Authentication token failure.
PAM_AUTHTOK_EXPIRED
Password has expired.
PAM_AUTHTOK_LOCK_BUSY
Authentication token lock busy.
PAM_AUTHTOK_RECOVERY_ERR
Failed to recover old authentication token.
PAM_AUTH_ERR
Authentication error.
PAM_BUF_ERR
Memory buffer error.
PAM_CONV_ERR
Conversation error.
PAM_CRED_ERR
Failed to set user credentials.
PAM_CRED_EXPIRED
User credentials have expired.
PAM_CRED_INSUFFICIENT
Insufficient credentials.
PAM_CRED_UNAVAIL
Failed to retrieve user credentials.
PAM_DOMAIN_UNKNOWN
Unknown authentication domain.
PAM_IGNORE
Ignore this module.
PAM_MAXTRIES
Maximum number of tries exceeded.
PAM_MODULE_UNKNOWN
Unknown module type.
PAM_NEW_AUTHTOK_REQD
New authentication token required.
PAM_NO_MODULE_DATA
Module data not found.
PAM_OPEN_ERR
Failed to load module.
PAM_PERM_DENIED
Permission denied.
PAM_SERVICE_ERR
Error in service module.
PAM_SESSION_ERR
Session failure.
PAM_SUCCESS
Success.
PAM_SYMBOL_ERR
Invalid symbol.
PAM_SYSTEM_ERR
System error.
PAM_TRY_AGAIN
Try again.
PAM_USER_UNKNOWN
Unknown user.

Extensions

implementation

Specifies the PAM implementation, if known.

Platform Implementation
AIX 4.3 (patched) 'Linux-PAM'
AIX 5.1 (ML01+) '?'
AIX 5.2+ '?'
Darwin (Mac OS X) 'OpenPAM'
DragonflyBSD 'OpenPAM'
FreeBSD 'OpenPAM'
HP-UX '?'
Linux 'Linux-PAM' (some distros support 'OpenPAM')
NetBSD 'OpenPAM'
PC-BSD 'OpenPAM'
Solaris 'OpenPAM'
extensions

Set of strings describing the API extensions supported by this module. Potential extensions include:

'fail_delay'
This module supports the PAM fail delay API. Currently only provided by Linux-PAM implementations.
'unsetenv'
Environment variables can be deleted in this implementation. Currently only supported by OpenPAM.