The Linux-PAM Application Developers' Guide: The public interface to Linux-PAM

Next Previous Contents

## 3. The public interface to Linux-PAM

Firstly, the relevant include file for the Linux-PAM library is `<security/pam_appl.h>`. It contains the definitions for a number of functions. After listing these functions, we collect some guiding remarks for programmers.

## 3.1 What can be expected by the application

Here we document those functions in the Linux-PAM library that may be called from an application.

### Initialization of Linux-PAM

> `

>     extern int pam_start(const char *service_name, const char *user,
>                          const struct pam_conv *pam_conversation,
>                          pam_handle_t **pamh);

> `

This is the first of the Linux-PAM functions that must be called by an application. It initializes the interface and reads the system configuration file, `/etc/pam.conf` (see the Linux-PAM System Administrators' Guide). Following a successful return (`PAM_SUCCESS`) the contents of `*pamh` is a handle that provides continuity for successive calls to the Linux-PAM library. The arguments expected by `pam_start` are as follows: the `service_name` of the program, the `user`name of the individual to be authenticated, a pointer to an application-supplied `pam_conv` structure and a pointer to a `pam_handle_t` pointer.

The `pam_conv` structure is discussed more fully in the section below. The `pam_handle_t` is a blind structure and the application should not attempt to probe it directly for information. Instead the Linux-PAM library provides the functions `pam_set_item` and `pam_get_item`. These functions are documented below.

### Termination of the library

> `

>     extern int pam_end(pam_handle_t *pamh, int pam_status);

> `

This function is the last function an application should call in the Linux-PAM library. Upon return the handle `pamh` is no longer valid and all memory associated with it will be invalid (likely to cause a segmentation fault if accessed).

Under normal conditions the argument `pam_status` has the value PAM_SUCCESS, but in the event of an unsuccessful service application the approprite Linux-PAM error-return value should be used here. attempt its purpose is to be passed as an argument to the module specific function `cleanup()` (see the Linux-PAM Module Developers' Guide).

### Setting PAM items

> `

>     extern int pam_set_item(pam_handle_t *pamh, int item_type,
>                             const void *item);

> `

This function is used to (re)set the value of one of the following item_types:

`PAM_SERVICE`

  The service name

`PAM_USER`

  The user name

`PAM_TTY`

  The terminal name: prefixed by `/dev/` if it is a device file; for graphical, X-based, applications the value for this item should be the `$DISPLAY` variable.

`PAM_RHOST`

  The remote host name

`PAM_CONV`

  The conversation structure (see section below)

`PAM_RUSER`

  The remote user name

`PAM_USER_PROMPT`

  The string used when prompting for a user's name. The default value for this string is ``Please enter username: ''.

For all `item_type`s, other than `PAM_CONV`, `item` is a pointer to a `<NUL>` terminated character string. In the case of `PAM_CONV`, `item` points to an initialized `pam_conv` structure (see section below).

A successful call to this function returns `PAM_SUCCESS`. However, the application should expect one of the following errors:

`PAM_PERM_DENIED`

  An attempt was made to replace the conversation structure with a `NULL` value.

`PAM_BUF_ERR`

  The function ran out of memory making a copy of the item.

`PAM_BAD_ITEM`

  The application attempted to set an undefined item.

### Getting PAM items

> `

>     extern int pam_get_item(const pam_handle_t *pamh, int item_type,
>                             const void **item);

> `

This function is used to obtain the value of the indicated `item_type`. Upon successful return, `*item` contains a pointer to the value of the corresponding item. Note, this is a pointer to the actual data and should not be `free()`'ed or over-written! A successful call is signaled by a return value of `PAM_SUCCESS`. If an attempt is made to get an undefined item, `PAM_BAD_ITEM` is returned.

### Understanding errors

> `

>     extern const char *pam_strerror(pam_handle_t *pamh, int errnum);

> `

This function returns some text describing the Linux-PAM error associated with the argument `errnum`. If the error is not recognized ```Unknown Linux-PAM error`'' is returned.

### Planning for delays

> `

>     extern int pam_fail_delay(pam_handle_t *pamh, unsigned int micro_sec);

> `

This function is offered by Linux-PAM to facilitate time delays following a failed call to `pam_authenticate()` and before control is returned to the application. When using this function the application programmer should check if it is available with,

> `

>     #ifdef HAVE_PAM_FAIL_DELAY
>         ....
>     #endif /* HAVE_PAM_FAIL_DELAY */

> `

Generally, an application requests that a user is authenticated by Linux-PAM through a call to `pam_authenticate()` or `pam_chauthtok()`. These functions call each of the stacked authentication modules listed in the relevant Linux-PAM configuration file. As directed by this file, one of more of the modules may fail causing the `pam_...()` call to return an error. It is desirable for there to also be a pause before the application continues. The principal reason for such a delay is security: a delay acts to discourage brute force dictionary attacks primarily, but also helps hinder timed (covert channel) attacks.

The `pam_fail_delay()` function provides the mechanism by which an application or module can suggest a minimum delay (of `micro_sec` micro-seconds). Linux-PAM keeps a record of the longest time requested with this function. Should `pam_authenticate()` fail, the failing return to the application is delayed by an amount of time randomly distributed (by up to 25%) about this longest value.

Independent of success, the delay time is reset to its zero default value when Linux-PAM returns control to the application.

For applications written with a single thread that are event driven in nature, `libpam` generating this dalay may be undesirable. Instead, the application may want to register the delay in some other way. For example, in a single threaded server that serives multiple authentication requests from a single event loop, the application might want to simply mark a given connection as blocked until an application timer expires. For this reason, Linux-PAM supplies the `PAM_FAIL_DELAY` item. It can be queried and set with `pam_get_item()` and `pam_set_item()` respectively. The value used to set it should be a function pointer of the following prototype:

> `

>     void (*delay_fn)(int retval, unsigned usec_delay, void *appdata_ptr);

> `

The arguments being the `retval` return code of the module stack, the `usec_delay` micro-second delay that libpam is requesting and the `appdata_ptr` that the application has associated with the current `pamh` (/tt/pam_handle_t/). This last value was set by the application when it called `pam_start` or explicitly with `pam_set_item(... , PAM_CONV, ...)`. Note, if this function item is unset (or set to `NULL`), then `libpam` will perform the delay.

### Authenticating the user

> `

>     extern int pam_authenticate(pam_handle_t *pamh, int flags);

> `

This function serves as an interface to the authentication mechanisms of the loaded modules. The single optional flag, which may be logically OR'd with `PAM_SILENT`, takes the following value,

`PAM_DISALLOW_NULL_AUTHTOK`

  Instruct the authentication modules to return `PAM_AUTH_ERR` if the user does not have a registered authorization token---it is set to `NULL` in the system database.

The value returned by this function is one of the following:

`PAM_AUTH_ERR`

  The user was not authenticated

`PAM_CRED_INSUFFICIENT`

  For some reason the application does not have sufficient credentials to authenticate the user.

`PAM_AUTHINFO_UNAVAIL`

  The modules were not able to access the authentication information. This might be due to a network or hardware failure etc.

`PAM_USER_UNKNOWN`

  The supplied username is not known to the authentication service

`PAM_MAXTRIES`

  One or more of the authentication modules has reached its limit of tries authenticating the user. Do not try again.

If one or more of the authentication modules fails to load, for whatever reason, this function will return `PAM_ABORT`.

### Setting user credentials

> `

>     extern int pam_setcred(pam_handle_t *pamh, int flags);

> `

This function is used to set the module-specific credentials of the user. It is usually called after the user has been authenticated, after the account management function has been called and after a session has been opened for the user.

A credential is something that the user possesses. It is some property, such as a Kerberos ticket, or a supplementary group membership that make up the uniqueness of a given user. On a Linux (or UN*X system) the user's `UID` and `GID`'s are credentials too. However, it has been decided that these properties (along with the default supplementary groups of which the user is a member) are credentials that should be set directly by the application and not by PAM.

This function simply calls the `pam_sm_setcred` functions of each of the loaded modules. Valid `flags`, any one of which, may be logically OR'd with `PAM_SILENT`, are:

`PAM_ESTABLISH_CRED`

  Set the credentials for the authentication service,

`PAM_DELETE_CRED`

  Delete the credentials associated with the authentication service,

`PAM_REINITIALIZE_CRED`

  Reinitialize the user credentials, and

`PAM_REFRESH_CRED`

  Extend the lifetime of the user credentials.

A successful return is signalled with `PAM_SUCCESS`. Errors that are especially relevant to this function are the following:

`PAM_CRED_UNAVAIL`

  A module cannot retrieve the user's credentials.

`PAM_CRED_EXPIRED`

  The user's credentials have expired.

`PAM_USER_UNKNOWN`

  The user is not known to an authentication module.

`PAM_CRED_ERR`

  A module was unable to set the credentials of the user.

### Account management

> `

>     extern int pam_acct_mgmt(pam_handle_t *pamh, int flags);

> `

This function is typically called after the user has been authenticated. It establishes whether the user's account is healthy. That is to say, whether the user's account is still active and whether the user is permitted to gain access to the system at this time. Valid flags, any one of which, may be logically OR'd with `PAM_SILENT`, and are the same as those applicable to the `flags` argument of `pam_authenticate`.

This function simply calls the corresponding functions of each of the loaded modules, as instructed by the configuration file, `/etc/pam.conf`.

The normal response from this function is `PAM_SUCCESS`, however, specific failures are indicated by the following error returns:

`PAM_AUTHTOKEN_REQD`

  The user is valid but their authentication token has expired. The correct response to this return-value is to require that the user satisfies the `pam_chauthtok()` function before obtaining service. It may not be possible for some applications to do this. In such cases, the user should be denied access until such time as they can update their password.

`PAM_ACCT_EXPIRED`

  The user is no longer permitted access to the system.

`PAM_AUTH_ERR`

  There was an authentication error.

`PAM_PERM_DENIED`

  The user is not permitted to gain access at this time.

`PAM_USER_UNKNOWN`

  The user is not known to a module's account management component.

### Updating authentication tokens

> `

>     extern int pam_chauthtok(pam_handle_t *pamh, const int flags);

> `

This function is used to change the authentication token for a given user (as indicated by the state associated with the handle, `pamh`). The following is a valid but optional flag which may be logically OR'd with `PAM_SILENT`,

`PAM_CHANGE_EXPIRED_AUTHTOK`

  This argument indicates to the modules that the users authentication token (password) should only be changed if it has expired.

Note, if this argument is not passed, the application requires that all authentication tokens are to be changed.

`PAM_SUCCESS` is the only successful return value, valid error-returns are:

`PAM_AUTHTOK_ERR`

  A module was unable to obtain the new authentication token.

`PAM_AUTHTOK_RECOVERY_ERR`

  A module was unable to obtain the old authentication token.

`PAM_AUTHTOK_LOCK_BUSY`

  One or more of the modules was unable to change the authentication token since it is currently locked.

`PAM_AUTHTOK_DISABLE_AGING`

  Authentication token aging has been disabled for at least one of the modules.

`PAM_PERM_DENIED`

  Permission denied.

`PAM_TRY_AGAIN`

  Not all of the modules were in a position to update the authentication token(s). In such a case none of the user's authentication tokens are updated.

`PAM_USER_UNKNOWN`

  The user is not known to the authentication token changing service.

### Session initialization

> `

>     extern int pam_open_session(pam_handle_t *pamh, int flags);

> `

This function is used to indicate that an authenticated session has begun. It is used to inform the module that the user is currently in a session. It should be possible for the Linux-PAM library to open a session and close the same session (see section below) from different applications.

Currently, this function simply calls each of the corresponding functions of the loaded modules. The only valid flag is `PAM_SILENT` and this is, of course, optional.

If any of the required loaded modules are unable to open a session for the user, this function will return `PAM_SESSION_ERR`.

### Terminating sessions

> `

>     extern int pam_close_session(pam_handle_t *pamh, int flags);

> `

This function is used to indicate that an authenticated session has ended. It is used to inform the module that the user is exiting a session. It should be possible for the Linux-PAM library to open a session and close the same session from different applications.

Currently, this function simply calls each of the corresponding functions of the loaded modules. The only valid flag is `PAM_SILENT` and this is, of course, optional.

If any of the required loaded modules are unable to close a session for the user, this function will return `PAM_SESSION_ERR`.

### Setting PAM environment variables

> `

>     extern int pam_putenv(pam_handle_t *pamh, const char *name_value);

> `

Warning, the environment support in Linux-PAM is based solely on a six line email from the developers at Sun. Its interface is likely to be generally correct, however, the details are likely to be changed as more information becomes available.

This function attempts to (re)set a Linux-PAM environment variable. The `name_value` argument is a single `NUL` terminated string of one of the following forms:

```NAME=value of variable`''

  In this case the environment variable of the given `NAME` is set to the indicated value: ```value of variable`''. If this variable is already known, it is overwritten. Otherwise it is added to the Linux-PAM environment.

```NAME=`''

  This function sets the variable to an empty value. It is listed separately to indicate that this is the correct way to achieve such a setting.

```NAME`''

  Without an ``=`' the `pam_putenv()` function will delete the correspoding variable from the Linux-PAM environment.

Success is indicated with a return value of `PAM_SUCCESS`. Failure is indicated by one of the following returns:

`PAM_PERM_DENIED`

  name given is a `NULL` pointer

`PAM_BAD_ITEM`

  variable requested (for deletion) is not currently set

`PAM_ABORT`

  the Linux-PAM handle, `pamh`, is corrupt

`PAM_BUF_ERR`

  failed to allocate memory when attempting update

### Getting a PAM environment variable

> `

>     extern const char *pam_getenv(pam_handle_t *pamh, const char *name);

> `

Warning, the environment support in Linux-PAM is based solely on a six-line email from the developers at Sun. Its interface is likely to be generally correct, however, the details are likely to be changed as more information becomes available.

Obtain the value of the indicated Linux-PAM environment variable. On error, internal failure or the unavailability of the given variable (unspecified), this function simply returns `NULL`.

### Getting the PAM environment

> `

>     extern const char * const *pam_getenvlist(pam_handle_t *pamh);

> `

Warning, the environment support in Linux-PAM is based solely on a six line email from the developers at Sun. Its interface is likely to be generally correct, however, the details are likely to be changed as more information becomes available.

This function returns a pointer to the complete `Linux-PAM` environment. It is a pointer to a read-only list of read-only environment variables. It should be noted that this memory will become invalid after a call to `pam_end()` (see the section above). If application wishes to make use of this list after such a call, it should first make a copy of all the set variables. (A function that performs such a transcription is to be found in `libpam_misc`.)

## 3.2 What is expected of an application

### The conversation function

An application must provide a ``conversation function''. It is used for direct communication between a loaded module and the application and will typically provide a means for the module to prompt the user for a password etc. . The structure, `pam_conv`, is defined by including `<security/pam_appl.h>`; to be,

> `

>     struct pam_conv {
>         int (*conv)(int num_msg,
>             const struct pam_message **msg,
>             struct pam_response **resp,
>             void *appdata_ptr);
>         void *appdata_ptr;
>     };

> `

It is initialized by the application before it is passed to the library. The contents of this structure are attached to the `*pamh` handle. The point of this argument is to provide a mechanism for any loaded module to interact directly with the application program. This is why it is called a conversation structure.

When a module calls the referenced `conv()` function, the argument `*appdata_ptr` is set to the second element of this structure.

The other arguments of a call to `conv()` concern the information exchanged by module and application. That is to say, `num_msg` holds the length of the array of pointers, `msg`. After a successful return, the pointer `*resp` points to an array of `pam_response` structures, holding the application supplied text. Note, `*resp` is an `struct pam_response` array and not an array of pointers.

The message (from the module to the application) passing structure is defined by `<security/pam_appl.h>` as:

> `

>     struct pam_message {
>         int msg_style;
>         const char *msg;
>     };

> `

Valid choices for `msg_style` are:

`PAM_PROMPT_ECHO_OFF`

  Obtain a string without echoing any text

`PAM_PROMPT_ECHO_ON`

  Obtain a string whilst echoing text

`PAM_ERROR_MSG`

  Display an error

`PAM_TEXT_INFO`

  Display some text.

The point of having an array of messages is that it becomes possible to pass a number of things to the application in a single call from the module. It can also be convenient for the application that related things come at once: a windows based application can then present a single form with many messages/prompts on at once.

The response (from the application to the module) passing structure is defined by including `<security/pam_appl.h>` as:

> `

>     struct pam_response {
>         char *resp;
>         int resp_retcode;
>     };

> `

Currently, there are no definitions for `resp_retcode` values; the normal value is `0`.

Prior to the 0.59 release of Linux-PAM, the length of the returned `pam_response` array was equal to the number of prompts (types `PAM_PROMPT_ECHO_OFF` and `PAM_PROMPT_ECHO_ON`) in the `pam_message` array with which the conversation function was called. This meant that it was not always necessary for the module to `free(3)` the responses if the conversation function was only used to display some text.

Post Linux-PAM-0.59 (and in the interests of compatibility with Sunsoft). The number of resposes is always equal to the `num_msg` conversation function argument. This is slightly easier to program but does require that the response array is `free(3)`'d after every call to the conversation function. The index of the responses corresponds directly to the prompt index in the `pam_message` array.

The maximum length of the `pam_msg.msg` and `pam_response.resp` character strings is `PAM_MAX_MSG_SIZE`. (This is not enforced by Linux-PAM.)

`PAM_SUCCESS` is the expected return value of this function. However, should an error occur the application should not set `*resp` but simply return `PAM_CONV_ERR`.

Note, if an application wishes to use two conversation functions, it should activate the second with a call to `pam_set_item()`.

Notes: New item types are being added to the conversation protocol. Currently Linux-PAM supports: `PAM_BINARY_PROMPT` and `PAM_BINARY_MSG`. These two are intended for server-client hidden information exchange and may be used as an interface for maching-machine authentication.

## 3.3 Programming notes

Note, all of the authentication service function calls accept the token `PAM_SILENT`, which instructs the modules to not send messages to the application. This token can be logically OR'd with any one of the permitted tokens specific to the individual function calls. `PAM_SILENT` does not override the prompting of the user for passwords etc., it only stops informative messages from being generated.

Next Previous Contents