                        Pluggable Authentication Modules

  Dag-Erling Smo/rgrav

   Copyright (c) 2001, 2002 by Networks Associates Technology, Inc.

   $FreeBSD: doc/en_US.ISO8859-1/articles/pam/article.sgml,v 1.18 2002/06/21
   16:42:35 des Exp $

   This article was written for the FreeBSD Project by ThinkSec AS and
   Network Associates Laboratories, the Security Research Division of Network
   Associates, Inc. under DARPA/SPAWAR contract N66001-01-C-8035 (``CBOSS''),
   as part of the DARPA CHATS research program.

   This article describes the underlying principles and mechanisms of the
   Pluggable Authentication Modules (PAM) library, and explains how to
   configure PAM, how to integrate PAM into applications, and how to write
   PAM modules.

     ----------------------------------------------------------------------

   Table of Contents

   1. Introduction

   2. Terms and conventions

   3. PAM Essentials

   4. PAM Configuration

   5. FreeBSD PAM Modules

   6. PAM Application Programming

   7. PAM Module Programming

   A. Sample PAM Application

   B. Sample PAM Module

   C. Sample PAM Conversation Function

   Further Reading

     ----------------------------------------------------------------------

                                1. Introduction

   The Pluggable Authentication Modules (PAM) library is a generalized API
   for authentication-related services which allows a system administrator to
   add new authentication methods simply by installing new PAM modules, and
   to modify authentication policies by editing configuration files.

   PAM was defined and developed in 1995 by Vipin Samar and Charlie Lai of
   Sun Microsystems, and has not changed much since. In 1997, the Open Group
   published the X/Open Single Sign-on (XSSO) preliminary specification,
   which standardized the PAM API and added extensions for single (or rather
   integrated) sign-on. At the time of this writing, this specification has
   not yet been adopted as a standard.

   Although this article focuses primarily on FreeBSD 5.x, which uses
   OpenPAM, it should be equally applicable to FreeBSD 4.x, which uses
   Linux-PAM, and other operating systems such as Linux and Solaris.

     ----------------------------------------------------------------------

1.1. Trademarks

   Sun, Sun Microsystems and Solaris are trademarks or registered trademarks
   of Sun Microsystems, Inc.

   UNIX and The Open Group are trademarks or registered trademarks of The
   Open Group.

   All other brand or product names mentioned in this document may be
   trademarks or registered trademarks of their respective owners.

     ----------------------------------------------------------------------

                            2. Terms and conventions

2.1. Definitions

   The terminology surrounding PAM is rather confused. Neither Samar and
   Lai's original paper nor the XSSO specification made any attempt at
   formally defining terms for the various actors and entities involved in
   PAM, and the terms that they do use (but do not define) are sometimes
   misleading and ambiguous. The first attempt at establishing a consistent
   and unambiguous terminology was a whitepaper written by Andrew G. Morgan
   (author of Linux-PAM) in 1999. While Morgan's choice of terminology was a
   huge leap forward, it is in this author's opinion by no means perfect.
   What follows is an attempt, heavily inspired by Morgan, to define precise
   and unambiguous terms for all actors and entities involved in PAM.

   account

           The set of credentials the applicant is requesting from the
           arbitrator.

   applicant

           The user or entity requesting authentication.

   arbitrator

           The user or entity who has the privileges necessary to verify the
           applicant's credentials and the authority to grant or deny the
           request.

   chain

           A sequence of modules that will be invoked in response to a PAM
           request. The chain includes information about the order in which
           to invoke the modules, what arguments to pass to them, and how to
           interpret the results.

   client

           The application responsible for initiating an authentication
           request on behalf of the applicant and for obtaining the necessary
           authentication information from him.

   facility

           One of the four basic groups of functionality provided by PAM:
           authentication, account management, session management and
           authentication token update.

   module

           A collection of one or more related functions implementing a
           particular authentication facility, gathered into a single
           (normally dynamically loadable) binary file and identified by a
           single name.

   policy

           The complete set of configuration statements describing how to
           handle PAM requests for a particular service. A policy normally
           consists of four chains, one for each facility, though some
           services do not use all four facilities.

   server

           The application acting on behalf of the arbitrator to converse
           with the client, retrieve authentication information, verify the
           applicant's credentials and grant or deny requests.

   service

           A class of servers providing similar or related functionality and
           requiring similar authentication. PAM policies are defined on a
           per-service basis, so all servers that claim the same service name
           will be subject to the same policy.

   session

           The context within which service is rendered to the applicant by
           the server. One of PAM's four facilities, session management, is
           concerned exclusively with setting up and tearing down this
           context.

   token

           A chunk of information associated with the account, such as a
           password or passphrase, which the applicant must provide to prove
           his identity.

   transaction

           A sequence of requests from the same applicant to the same
           instance of the same server, beginning with authentication and
           session set-up and ending with session tear-down.

     ----------------------------------------------------------------------

2.2. Usage examples

   This section aims to illustrate the meanings of some of the terms defined
   above by way of a handful of simple examples.

     ----------------------------------------------------------------------

  2.2.1. Client and server are one

   This simple example shows alice su(1)'ing to root.

     % whoami
     alice
     % ls -l `which su`
     -r-sr-xr-x  1 root  wheel  10744 Dec  6 19:06 /usr/bin/su
     % su -
     Password: xi3kiune
     # whoami
     root

     * The applicant is alice.

     * The account is root.

     * The su(1) process is both client and server.

     * The authentication token is xi3kiune.

     * The arbitrator is root, which is why su(1) is setuid root.

     ----------------------------------------------------------------------

  2.2.2. Client and server are separate

   The example below shows eve try to initiate an ssh(1) connection to
   login.example.com, ask to log in as bob, and succeed. Bob should have
   chosen a better password!

     % whoami
     eve
     % ssh bob@login.example.com
     bob@login.example.com's password: god
     Last login: Thu Oct 11 09:52:57 2001 from 192.168.0.1
     Copyright (c) 1980, 1983, 1986, 1988, 1990, 1991, 1993, 1994
         The Regents of the University of California.  All rights reserved.
     FreeBSD 4.4-STABLE (LOGIN) #4: Tue Nov 27 18:10:34 PST 2001
    
     Welcome to FreeBSD!
     %

     * The applicant is eve.

     * The client is Eve's ssh(1) process.

     * The server is the sshd(8) process on login.example.com

     * The account is bob.

     * The authentication token is god.

     * Although this is not shown in this example, the arbitrator is root.

     ----------------------------------------------------------------------

  2.2.3. Sample policy

   The following is FreeBSD's default policy for sshd:

     sshd        auth            required        pam_nologin.so  no_warn
     sshd        auth            required        pam_unix.so     no_warn try_first_pass
     sshd        account         required        pam_login_access.so
     sshd        account         required        pam_unix.so
     sshd        session         required        pam_lastlog.so  no_fail
     sshd        password        required        pam_permit.so

     * This policy applies to the sshd service (which is not necessarily
       restricted to the sshd(8) server.)

     * auth, account, session and password are facilities.

     * pam_nologin.so, pam_unix.so, pam_login_access.so, pam_lastlog.so and
       pam_permit.so are modules. It is clear from this example that
       pam_unix.so provides at least two facilities (authentication and
       account management.)

     ----------------------------------------------------------------------

2.3. Conventions

   This section has not yet been written.

     ----------------------------------------------------------------------

                               3. PAM Essentials

3.1. Facilities and primitives

   The PAM API offers six different authentication primitives grouped in four
   facilities, which are described below.

   auth

           Authentication. This facility concerns itself with authenticating
           the applicant and establishing the account credentials. It
           provides two primitives:

              * pam_authenticate(3) authenticates the applicant, usually by
                requesting an authentication token and comparing it with a
                value stored in a database or obtained from an authentication
                server.

              * pam_setcred(3) establishes account credentials such as user
                ID, group membership and resource limits.

   account

           Account management. This facility handles
           non-authentication-related issues of account availability, such as
           access restrictions based on the time of day or the server's work
           load. It provides a single primitive:

              * pam_acct_mgmt(3) verifies that the requested account is
                available.

   session

           Session management. This facility handles tasks associated with
           session set-up and tear-down, such as login accounting. It
           provides two primitives:

              * pam_open_session(3) performs tasks associated with session
                set-up: add an entry in the utmp and wtmp databases, start an
                SSH agent, etc.

              * pam_close_session(3) performs tasks associated with session
                tear-down: add an entry in the utmp and wtmp databases, stop
                the SSH agent, etc.

   password

           Password management. This facility is used to change the
           authentication token associated with an account, either because it
           has expired or because the user wishes to change it. It provides a
           single primitive:

              * pam_chauthtok(3) changes the authentication token, optionally
                verifying that it is sufficiently hard to guess, has not been
                used previously, etc.

     ----------------------------------------------------------------------

3.2. Modules

   Modules are a very central concept in PAM; after all, they are the ``M''
   in ``PAM''. A PAM module is a self-contained piece of program code that
   implements the primitives in one or more facilities for one particular
   mechanism; possible mechanisms for the authentication facility, for
   instance, include the UNIX password database, NIS, LDAP and Radius.

     ----------------------------------------------------------------------

  3.2.1. Module Naming

   FreeBSD implements each mechanism in a single module, named
   pam_mechanism.so (for instance, pam_unix.so for the Unix mechanism.) Other
   implementations sometimes have separate modules for separate facilities,
   and include the facility name as well as the mechanism name in the module
   name. To name one example, Solaris has a pam_dial_auth.so.1 module which
   is commonly used to authenticate dialup users.

     ----------------------------------------------------------------------

  3.2.2. Module Versioning

   FreeBSD's original PAM implementation, based on Linux-PAM, did not use
   version numbers for PAM modules. This would commonly cause problems with
   legacy applications, which might be linked against older versions of the
   system libraries, as there was no way to load a matching version of the
   required modules.

   OpenPAM, on the other hand, looks for modules that have the same version
   number as the PAM library (currently 2), and only falls back to an
   unversioned module if no versioned module could be loaded. Thus legacy
   modules can be provided for legacy applications, while allowing new (or
   newly built) applications to take advantage of the most recent modules.

   Although Solaris PAM modules commonly have a version number, they're not
   truly versioned, because the number is a part of the module name and must
   be included in the configuration.

     ----------------------------------------------------------------------

3.3. Chains and policies

   When a server initiates a PAM transaction, the PAM library tries to load a
   policy for the service specified in the pam_start(3) call. The policy
   specifies how authentication requests should be processed, and is defined
   in a configuration file. This is the other central concept in PAM: the
   possibility for the admin to tune the system security policy (in the wider
   sense of the word) simply by editing a text file.

   A policy consists of four chains, one for each of the four PAM facilities.
   Each chain is a sequence of configuration statements, each specifying a
   module to invoke, some (optional) parameters to pass to the module, and a
   control flag that describes how to interpret the return code from the
   module.

   Understanding the control flags is essential to understanding PAM
   configuration files. There are four different control flags:

   required

           Success is required, but the chain continues no matter what this
           module returns, so that later modules can override it.

   requisite

           A negative result from this module will immediately terminate the
           chain and deny the request.

   sufficient

           A positive result from this module will immediately terminate the
           chain and grant the request. On failure, the chain continues.

   optional

           A negative result from this module will be ignored.

   When a server invokes one of the six PAM primitives, PAM retrieves the
   chain for the facility the primitive belongs to, and invokes each of the
   modules listed in the chain, in the order they are listed, until it
   reaches the end, or determines that no further processing is necessary
   (either because a sufficient module succeeded, or because a requisite
   module failed.) The request is granted if and only if at least one module
   was invoked, and all non-optional modules succeeded.

   Note that it is possible, though not very common, to have the same module
   listed several times in the same chain. For instance, a module that looks
   up user names and passwords in a directory server could be invoked
   multiple times with different parameters specifying different directory
   servers to contact. PAM treat different occurrences of the same module in
   the same chain as different, unrelated modules.

     ----------------------------------------------------------------------

3.4. Transactions

   The lifecycle of a typical PAM transaction is described below. Note that
   if this any of these steps fails, the server should report a suitable
   error message to the client and abort the transaction.

    1. If necessary, the server obtains arbitrator credentials through a
       mechanism independent of PAM--most commonly by virtue of having been
       started by root, or of being setuid root.

    2. The server calls pam_start(3) to initialize the PAM library and
       specify its service name and the target account, and register a
       suitable conversation function.

    3. The server obtains various information relating to the transaction
       (such as the applicant's user name and the name of the host the client
       runs on) and submits it to PAM using pam_set_item(3).

    4. The server calls pam_authenticate(3) to authenticate the applicant.

    5. The server calls pam_acct_mgmt(3) verify that the requested account is
       available and valid. If the password is correct but has expired,
       pam_acct_mgmt(3) will return PAM_NEW_AUTHTOK_REQD instead of
       PAM_SUCCESS.

    6. If the previous step returned PAM_NEW_AUTHTOK_REQD, the server now
       calls pam_chauthtok(3) to force the client to change the
       authentication token for the requested account.

    7. Now that the applicant has been properly authenticated, the server
       calls pam_setcred(3) to establish the credentials of the requested
       account. It is able to do this because it acts on behalf of the
       arbitrator, and holds the arbitrator's credentials.

    8. Once the correct credentials have been established, the server calls
       pam_open_session(3) to set up the session.

    9. The server now performs whatever service the client requested--for
       instance, provide the applicant with a shell.

   10. Once the server is done serving the client, it calls
       pam_close_session(3) to tear down the session.

   11. Finally, the server calls pam_end(3) to notify the PAM library that it
       is done and that it can release whatever resources it has allocated in
       the course of the transaction.

     ----------------------------------------------------------------------

                              4. PAM Configuration

4.1. Location of configuration files

   The traditional PAM configuration file is /etc/pam.conf. This file
   contains all the PAM policies for your system. Each line of the file
   describes one step in a chain, as shown below:

     login   auth    required        pam_nologin.so  no_warn

   The fields are, in order: service name, facility name, control flag,
   module name, and module arguments. Any additional fields are interpreted
   as additional module arguments.

   A separate chain is constructed for each service / facility pair, so while
   the order in which lines for the same service and facility appear is
   significant, the order in which the individual services and facilities are
   listed is not--except that entries for the other service, which serves as
   a fall-back, should come last. The examples in the original PAM paper
   grouped configuration lines by facility, and Solaris' stock pam.conf still
   does that, but FreeBSD's stock configuration groups configuration lines by
   service. Either way is fine; either way makes equal sense.

   OpenPAM and Linux-PAM offer an alternate configuration mechanism, where
   policies are contained in separate files, named for the service they apply
   to, in /etc/pam.d/, with only four fields instead of five--the service
   name field is omitted. This is the preferred mechanism in FreeBSD 5.x.
   Note, however, that if /etc/pam.conf exists, and contains configuration
   statements for services which do not have a specific policy in
   /etc/pam.d/, it will be used as a fall-back for these services.

   The great advantage of /etc/pam.d/ over /etc/pam.conf is that it is
   possible to use the same policy for multiple services by linking each
   service name to a same policy file. For instance, to use the same policy
   for the su and sudo services, one could do as follows:

     # cd /etc/pam.d
     # ln -s su sudo

   This works because the service name is determined from the file name
   rather than specified in the policy file, so the same file can be used for
   multiple differently-named services.

   One other advantage is that third-party software can easily install
   policies for their services without the need to edit /etc/pam.conf. True
   to the FreeBSD tradition, OpenPAM will even look for policy files in
   /usr/local/etc/pam.d/ if no configuration for the requested service is
   present in /etc/pam.d/ or /etc/pam.conf.

   Finally, whichever configuration mechanism you choose, the ``magic''
   policy other is used as a fall-back for any service that does not have its
   own policy.

     ----------------------------------------------------------------------

4.2. Breakdown of a configuration line

   As explained in the Location of configuration files section, each line in
   /etc/pam.conf consists of four or more fields: the service name, the
   facility name, the control flag, the module name, and zero or more module
   arguments.

   The service name is generally (though not always) the name of the
   application the statement applies to. If you are unsure, refer to the
   individual application's documentation to determine what service name it
   uses.

   Note that if you use /etc/pam.d/ instead of /etc/pam.conf, the service
   name is specified by the name of the policy file, and omitted from the
   actual configuration lines, which then start with the facility name.

   The facility is one of the four facility keywords described in the
   Facilities and primitives section.

   Likewise, the control flag is one of the four keywords described in the
   Chains and policies section, describing how to interpret the return code
   from the module. Linux-PAM supports an alternate syntax that lets you
   specify the action to associate with each possible return code, but this
   should be avoided as it is non-standard and closely tied in with the way
   Linux-PAM dispatches service calls (which differs greatly from the way
   Solaris and OpenPAM do it.) Unsurprisingly, OpenPAM does not support this
   syntax.

     ----------------------------------------------------------------------

4.3. Policies

   To configure PAM correctly, it is essential to understand how chains are
   executed.

   When an application calls pam_start(3), the PAM library loads the
   configuration for the specified service and constructs four module chains
   (one for each facility.) If the configuration does not specify any modules
   for one or more facilities, the configuration for the other service is
   used instead for these facilities.

   When the application later calls one of the six PAM primitives, the PAM
   library retrieves the chain for the corresponding facility and calls the
   appropriate service function in each module listed in the chain, in the
   order in which they were listed in the configuration. After each call to a
   service function, the module type and the error code returned by the
   service function are used to determine what happens next. With a few
   exceptions, which we will discuss later, the following table applies:

   Table 1. PAM chain execution summary

   +------------------------------------------------------------------------+
   |                | PAM_SUCCESS      | PAM_IGNORE    | other              |
   |----------------+------------------+---------------+--------------------|
   | required       | -                | -             | fail = true        |
   |----------------+------------------+---------------+--------------------|
   | requisite      | -                | -             | fail = true, break |
   |----------------+------------------+---------------+--------------------|
   | sufficient     | if (!fail) break | -             | fail = true        |
   |----------------+------------------+---------------+--------------------|
   | optional       | -                | -             | -                  |
   +------------------------------------------------------------------------+

   If fail is true at the end of a chain, or when a ``break'' is reached, the
   dispatcher returns the error code returned by the first module that
   failed. Otherwise, it returns PAM_SUCCESS.

   The first exception of note is that the error code PAM_NEW_AUTHTOK_REQD is
   treated like a success, except that if no module failed, and at least one
   module returned PAM_NEW_AUTHTOK_REQD, the dispatcher will return
   PAM_NEW_AUTHTOK_REQD.

   The second exception is that pam_setcred(3) treats sufficient modules as
   if they were required.

   The third and final exception is that pam_chauthtok(3) runs the entire
   chain twice (once for preliminary checks and once to actually set the
   password), and in the preliminary phase it treats sufficient modules as if
   they were required.

     ----------------------------------------------------------------------

                             5. FreeBSD PAM Modules

   This section has not yet been written.

     ----------------------------------------------------------------------

                         6. PAM Application Programming

   This section has not yet been written.

     ----------------------------------------------------------------------

                           7. PAM Module Programming

   This section has not yet been written.

     ----------------------------------------------------------------------

                           A. Sample PAM Application

   The following is a minimal implementation of su(1) using PAM. Note that it
   uses the OpenPAM-specific openpam_ttyconv(3) conversation function, which
   is prototyped in security/openpam.h. If you wish build this application on
   a system with a different PAM library, you will have to provide your own
   conversation function. A robust conversation function is surprisingly
   difficult to implement; the one presented in the Sample PAM Conversation
   Function appendix is a good starting point, but should not be used in
   real-world applications.

    
 #include <sys/param.h>
 #include <sys/wait.h>

 #include <err.h>
 #include <pwd.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <syslog.h>
 #include <unistd.h>

 #include <security/pam_appl.h>
 #include <security/openpam.h>   /* for openpam_ttyconv() */

 extern char **environ;

 static pam_handle_t *pamh;
 static struct pam_conv pamc;

 static void
 usage(void)
 {

         fprintf(stderr, "Usage: su [login [args]]\n");
         exit(1);
 }

 int
 main(int argc, char *argv[])
 {
         char hostname[MAXHOSTNAMELEN];
         const char *user, *tty;
         char **args, **pam_envlist, **pam_env;
         struct passwd *pwd;
         int o, pam_err, status;
         pid_t pid;

         while ((o = getopt(argc, argv, "h")) != -1)
                 switch (o) {
                 case 'h':
                 default:
                         usage();
                 }

         argc -= optind;
         argv += optind;

         /* initialize PAM */
         pamc.conv = &openpam_ttyconv;
         pam_start("su", argc ? *argv : "root", &pamc, &pamh);

         /* set some items */
         gethostname(hostname, sizeof(hostname));
         if ((pam_err = pam_set_item(pamh, PAM_RHOST, hostname)) != PAM_SUCCESS)
                 goto pamerr;
         user = getlogin();
         if ((pam_err = pam_set_item(pamh, PAM_RUSER, user)) != PAM_SUCCESS)
                 goto pamerr;
         tty = ttyname(STDERR_FILENO);
         if ((pam_err = pam_set_item(pamh, PAM_TTY, tty)) != PAM_SUCCESS)
                 goto pamerr;

         /* authenticate the applicant */
         if ((pam_err = pam_authenticate(pamh, 0)) != PAM_SUCCESS)
                 goto pamerr;
         if ((pam_err = pam_acct_mgmt(pamh, 0)) == PAM_NEW_AUTHTOK_REQD)
                 pam_err = pam_chauthtok(pamh, PAM_CHANGE_EXPIRED_AUTHTOK);
         if (pam_err != PAM_SUCCESS)
                 goto pamerr;

         /* establish the requested credentials */
         if ((pam_err = pam_setcred(pamh, PAM_ESTABLISH_CRED)) != PAM_SUCCESS)
                 goto pamerr;

         /* authentication succeeded; open a session */
         if ((pam_err = pam_open_session(pamh, 0)) != PAM_SUCCESS)
                 goto pamerr;

         /* get mapped user name; PAM may have changed it */
         pam_err = pam_get_item(pamh, PAM_USER, (const void **)&user);
         if (pam_err != PAM_SUCCESS || (pwd = getpwnam(user)) == NULL)
                 goto pamerr;

         /* set uid and groups */
         if (initgroups(pwd->pw_name, pwd->pw_gid) == -1) {
                 warn("initgroups()");
                 goto err;
         }
         if (setgid(pwd->pw_gid) == -1) {
                 warn("setgid()");
                 goto err;
         }
         if (setuid(pwd->pw_uid) == -1) {
                 warn("setuid()");
                 goto err;
         }

         /* export PAM environment */
         if ((pam_envlist = pam_getenvlist(pamh)) != NULL) {
                 for (pam_env = pam_envlist; *pam_env != NULL; ++pam_env) {
                         putenv(*pam_env);
                         free(*pam_env);
                 }
                 free(pam_envlist);
         }

         /* build argument list */
         if ((args = calloc(argc + 2, sizeof *args)) == NULL) {
                 warn("calloc()");
                 goto err;
         }
         *args = pwd->pw_shell;
         memcpy(args + 1, argv, argc * sizeof *args);

         /* fork and exec */
         switch ((pid = fork())) {
         case -1:
                 warn("fork()");
                 goto err;
         case 0:
                 /* child: start a shell */
                 execve(*args, args, environ);
                 warn("execve()");
                 _exit(1);
         default:
                 /* parent: wait for child to exit */
                 waitpid(pid, &status, 0);

                 /* close the session and release PAM resources */
                 pam_err = pam_close_session(pamh, 0);
                 pam_end(pamh, pam_err);

                 exit(WEXITSTATUS(status));
         }

 pamerr:
         pam_end(pamh, pam_err);
         fprintf(stderr, "Sorry\n");
         exit(1);
 err:
         pam_end(pamh, pam_err);
         exit(1);
 }

     ----------------------------------------------------------------------

                              B. Sample PAM Module

   The following is a minimal implementation of pam_unix(8), offering only
   authentication services. It should build and run with most PAM
   implementations, but takes advantage of OpenPAM extensions if available:
   note the use of pam_get_authtok(3), which enormously simplifies prompting
   the user for a password.

    
 #include <sys/param.h>

 #include <pwd.h>
 #include <stdlib.h>
 #include <stdio.h>
 #include <string.h>
 #include <unistd.h>

 #include <security/pam_modules.h>

 #ifndef _OPENPAM
 static char password_prompt[] = "Password:";
 #endif

 #ifndef PAM_EXTERN
 #define PAM_EXTERN
 #endif

 PAM_EXTERN int
 pam_sm_authenticate(pam_handle_t *pamh, int flags,
         int argc, const char *argv[])
 {
 #ifndef _OPENPAM
         struct pam_conv *conv;
         struct pam_message msg;
         const struct pam_message *msgp;
         struct pam_response *resp;
 #endif
         struct passwd *pwd;
         const char *user;
         char *crypt_password, *password;
         int pam_err, retry;

         /* identify user */
         if ((pam_err = pam_get_user(pamh, &user, NULL)) != PAM_SUCCESS)
                 return (pam_err);
         if ((pwd = getpwnam(user)) == NULL)
                 return (PAM_USER_UNKNOWN);

         /* get password */
 #ifndef _OPENPAM
         pam_err = pam_get_item(pamh, PAM_CONV, (const void **)&conv);
         if (pam_err != PAM_SUCCESS)
                 return (PAM_SYSTEM_ERR);
         msg.msg_style = PAM_PROMPT_ECHO_OFF;
         msg.msg = password_prompt;
         msgp = &msg;
 #endif
         for (retry = 0; retry < 3; ++retry) {
 #ifdef _OPENPAM
                 pam_err = pam_get_authtok(pamh, PAM_AUTHTOK,
                     (const char **)&password, NULL);
 #else
                 resp = NULL;
                 pam_err = (*conv->conv)(1, &msgp, &resp, conv->appdata_ptr);
                 if (resp != NULL) {
                         if (pam_err == PAM_SUCCESS)
                                 password = resp->resp;
                         else
                                 free(resp->resp);
                         free(resp);
                 }
 #endif
                 if (pam_err == PAM_SUCCESS)
                         break;
         }
         if (pam_err == PAM_CONV_ERR)
                 return (pam_err);
         if (pam_err != PAM_SUCCESS)
                 return (PAM_AUTH_ERR);

         /* compare passwords */
         if ((!pwd->pw_passwd[0] && (flags & PAM_DISALLOW_NULL_AUTHTOK)) ||
             (crypt_password = crypt(password, pwd->pw_passwd)) == NULL ||
             strcmp(crypt_password, pwd->pw_passwd) != 0)
                 pam_err = PAM_AUTH_ERR;
         else
                 pam_err = PAM_SUCCESS;
 #ifndef _OPENPAM
         free(password);
 #endif
         return (pam_err);
 }

 PAM_EXTERN int
 pam_sm_setcred(pam_handle_t *pamh, int flags,
         int argc, const char *argv[])
 {

         return (PAM_SUCCESS);
 }

 PAM_EXTERN int
 pam_sm_acct_mgmt(pam_handle_t *pamh, int flags,
         int argc, const char *argv[])
 {

         return (PAM_SUCCESS);
 }

 PAM_EXTERN int
 pam_sm_open_session(pam_handle_t *pamh, int flags,
         int argc, const char *argv[])
 {

         return (PAM_SUCCESS);
 }

 PAM_EXTERN int
 pam_sm_close_session(pam_handle_t *pamh, int flags,
         int argc, const char *argv[])
 {

         return (PAM_SUCCESS);
 }

 PAM_EXTERN int
 pam_sm_chauthtok(pam_handle_t *pamh, int flags,
         int argc, const char *argv[])
 {

         return (PAM_SERVICE_ERR);
 }

 #ifdef PAM_MODULE_ENTRY
 PAM_MODULE_ENTRY("pam_unix");
 #endif

     ----------------------------------------------------------------------

                      C. Sample PAM Conversation Function

   The conversation function presented below is a greatly simplified version
   of OpenPAM's openpam_ttyconv(3). It is fully functional, and should give
   the reader a good idea of how a conversation function should behave, but
   it is far too simple for real-world use. Even if you're not using OpenPAM,
   feel free to download the source code and adapt openpam_ttyconv(3) to your
   uses; we believe it to be as robust as a tty-oriented conversation
   function can reasonably get.

    
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <unistd.h>

 #include <security/pam_appl.h>

 int
 converse(int n, const struct pam_message **msg,
         struct pam_response **resp, void *data)
 {
         char buf[PAM_MAX_RESP_SIZE];
         int i;

         data = data;
         if (n <= 0 || n > PAM_MAX_NUM_MSG)
                 return (PAM_CONV_ERR);
         if ((*resp = calloc(n, sizeof **resp)) == NULL)
                 return (PAM_BUF_ERR);
         for (i = 0; i < n; ++i) {
                 resp[i]->resp_retcode = 0;
                 resp[i]->resp = NULL;
                 switch (msg[i]->msg_style) {
                 case PAM_PROMPT_ECHO_OFF:
                         resp[i]->resp = strdup(getpass(msg[i]->msg));
                         if (resp[i]->resp == NULL)
                                 goto fail;
                         break;
                 case PAM_PROMPT_ECHO_ON:
                         fputs(msg[i]->msg, stderr);
                         if (fgets(buf, sizeof buf, stdin) == NULL)
                                 goto fail;
                         resp[i]->resp = strdup(buf);
                         if (resp[i]->resp == NULL)
                                 goto fail;
                         break;
                 case PAM_ERROR_MSG:
                         fputs(msg[i]->msg, stderr);
                         if (strlen(msg[i]->msg) > 0 &&
                             msg[i]->msg[strlen(msg[i]->msg) - 1] != '\n')
                                 fputc('\n', stderr);
                         break;
                 case PAM_TEXT_INFO:
                         fputs(msg[i]->msg, stdout);
                         if (strlen(msg[i]->msg) > 0 &&
                             msg[i]->msg[strlen(msg[i]->msg) - 1] != '\n')
                                 fputc('\n', stdout);
                         break;
                 default:
                         goto fail;
                 }
         }
         return (PAM_SUCCESS);
  fail:
         while (i)
                 free(resp[--i]);
         free(*resp);
         *resp = NULL;
         return (PAM_CONV_ERR);
 }

     ----------------------------------------------------------------------

                                Further Reading

     This is a list of documents relevant to PAM and related issues. It is by
     no means complete.

     ----------------------------------------------------------------------

Papers

   Making Login Services Independent of Authentication Technologies, Vipin
   Samar and Charlie Lai, Sun Microsystems.

   X/Open Single Sign-on Preliminary Specification, The Open Group,
   1-85912-144-6, June 1997.

   Pluggable Authentication Modules, Andrew G. Morgan, October 6, 1999.

     ----------------------------------------------------------------------

User Manuals

   PAM Administration, Sun Microsystems.

     ----------------------------------------------------------------------

Related Web pages

   OpenPAM homepage, Dag-Erling Smo/rgrav, ThinkSec AS.

   Linux-PAM homepage, Andrew G. Morgan.

   Solaris PAM homepage, Sun Microsystems.

     ----------------------------------------------------------------------

               This, and other documents, can be downloaded from
                    ftp://ftp.FreeBSD.org/pub/FreeBSD/doc/.

     For questions about FreeBSD, read the documentation before contacting
                            <questions@FreeBSD.org>.
       For questions about this documentation, e-mail <doc@FreeBSD.org>.
