diff --git a/documentation/content/en/articles/pam/_index.adoc b/documentation/content/en/articles/pam/_index.adoc index bbea5aa3d2..6cb5d09d0a 100644 --- a/documentation/content/en/articles/pam/_index.adoc +++ b/documentation/content/en/articles/pam/_index.adoc @@ -1,672 +1,706 @@ --- title: Pluggable Authentication Modules authors: - author: Dag-Erling Smørgrav copyright: 2001-2003 Networks Associates Technology, Inc. description: A guide to the PAM system and modules under FreeBSD trademarks: ["pam", "freebsd", "linux", "opengroup", "sun", "general"] tags: ["pam", "introduction", "authentication", "modules", "FreeBSD"] --- +//// +Copyright (c) 2001-2003 Networks Associates Technology, Inc. +All rights reserved. + +This software was developed 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. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. The name of the author may not be used to endorse or promote + products derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. +//// + = Pluggable Authentication Modules :doctype: article :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :source-highlighter: rouge :experimental: [.abstract-title] Abstract 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. ''' toc::[] [[pam-intro]] == 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(TM). [[pam-terms]] == Terms and Conventions [[pam-definitions]] === 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. [[pam-usage-examples]] === Usage Examples This section aims to illustrate the meanings of some of the terms defined above by way of a handful of simple examples. ==== Client and Server Are One This simple example shows `alice` man:su[1]'ing to `root`. [source,shell] .... % 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 man:su[1] process is both client and server. * The authentication token is `xi3kiune`. * The arbitrator is `root`, which is why man:su[1] is setuid `root`. ==== Client and Server Are Separate The example below shows `eve` try to initiate an man:ssh[1] connection to `login.example.com`, ask to log in as `bob`, and succeed. Bob should have chosen a better password! [source,shell] .... % 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 man:ssh[1] process. * The server is the man: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`. ==== Sample Policy The following is FreeBSD's default policy for `sshd`: [.programlisting] .... 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 man:sshd[8] server.) * `auth`, `account`, `session` and `password` are facilities. * [.filename]#pam_nologin.so#, [.filename]#pam_unix.so#, [.filename]#pam_login_access.so#, [.filename]#pam_lastlog.so# and [.filename]#pam_permit.so# are modules. It is clear from this example that [.filename]#pam_unix.so# provides at least two facilities (authentication and account management.) [[pam-essentials]] == PAM Essentials [[pam-facilities-primitives]] === 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: ** man: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. ** man: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: ** man: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: ** man:pam_open_session[3] performs tasks associated with session set-up: add an entry in the [.filename]#utmp# and [.filename]#wtmp# databases, start an SSH agent, etc. ** man:pam_close_session[3] performs tasks associated with session tear-down: add an entry in the [.filename]#utmp# and [.filename]#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: ** man:pam_chauthtok[3] changes the authentication token, optionally verifying that it is sufficiently hard to guess, has not been used previously, etc. [[pam-modules]] === 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(R) password database, NIS, LDAP and Radius. [[pam-module-naming]] ==== Module Naming FreeBSD implements each mechanism in a single module, named `pam_mechanism.so` (for instance, `pam_unix.so` for the UNIX(R) 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(TM) has a `pam_dial_auth.so.1` module which is commonly used to authenticate dialup users. [[pam-module-versioning]] ==== 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(TM) PAM modules commonly have a version number, they are not truly versioned, because the number is a part of the module name and must be included in the configuration. [[pam-chains-policies]] === Chains and Policies When a server initiates a PAM transaction, the PAM library tries to load a policy for the service specified in the man: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: `binding`:: If the module succeeds and no earlier module in the chain has failed, the chain is immediately terminated and the request is granted. If the module fails, the rest of the chain is executed, but the request is ultimately denied. + This control flag was introduced by Sun in Solaris(TM) 9 (SunOS(TM) 5.9), and is also supported by OpenPAM. `required`:: If the module succeeds, the rest of the chain is executed, and the request is granted unless some other module fails. If the module fails, the rest of the chain is also executed, but the request is ultimately denied. `requisite`:: If the module succeeds, the rest of the chain is executed, and the request is granted unless some other module fails. If the module fails, the chain is immediately terminated and the request is denied. `sufficient`:: If the module succeeds and no earlier module in the chain has failed, the chain is immediately terminated and the request is granted. If the module fails, the module is ignored and the rest of the chain is executed. + As the semantics of this flag may be somewhat confusing, especially when it is used for the last module in a chain, it is recommended that the `binding` control flag be used instead if the implementation supports it. `optional`:: The module is executed, but its result is ignored. If all modules in a chain are marked `optional`, all requests will always be granted. 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 `binding` or `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. [[pam-transactions]] === Transactions The lifecycle of a typical PAM transaction is described below. Note that if any of these steps fails, the server should report a suitable error message to the client and abort the transaction. . 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`. . The server calls man:pam_start[3] to initialize the PAM library and specify its service name and the target account, and register a suitable conversation function. . 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 man:pam_set_item[3]. . The server calls man:pam_authenticate[3] to authenticate the applicant. . The server calls man:pam_acct_mgmt[3] to verify that the requested account is available and valid. If the password is correct but has expired, man:pam_acct_mgmt[3] will return `PAM_NEW_AUTHTOK_REQD` instead of `PAM_SUCCESS`. . If the previous step returned `PAM_NEW_AUTHTOK_REQD`, the server now calls man:pam_chauthtok[3] to force the client to change the authentication token for the requested account. . Now that the applicant has been properly authenticated, the server calls man: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. . Once the correct credentials have been established, the server calls man:pam_open_session[3] to set up the session. . The server now performs whatever service the client requested-for instance, provide the applicant with a shell. . Once the server is done serving the client, it calls man:pam_close_session[3] to tear down the session. . Finally, the server calls man: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. [[pam-config]] == PAM Configuration [[pam-config-file]] === PAM Policy Files [[pam-config-pam.conf]] ==== The [.filename]#/etc/pam.conf# The traditional PAM policy file is [.filename]#/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: [.programlisting] .... 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. The examples in the original PAM paper grouped configuration lines by facility, and the Solaris(TM) stock [.filename]#pam.conf# still does that, but FreeBSD's stock configuration groups configuration lines by service. Either way is fine; either way makes equal sense. [[pam-config-pam.d]] ==== The [.filename]#/etc/pam.d# OpenPAM and Linux-PAM support an alternate configuration mechanism, which is the preferred mechanism in FreeBSD. In this scheme, each policy is contained in a separate file bearing the name of the service it applies to. These files are stored in [.filename]#/etc/pam.d/#. These per-service policy files have only four fields instead of [.filename]#pam.conf#'s five: the service name field is omitted. Thus, instead of the sample [.filename]#pam.conf# line from the previous section, one would have the following line in [.filename]#/etc/pam.d/login#: [.programlisting] .... auth required pam_nologin.so no_warn .... As a consequence of this simplified syntax, 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: [source,shell] .... # 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. Since each service's policy is stored in a separate file, the [.filename]#pam.d# mechanism also makes it very easy to install additional policies for third-party software packages. [[pam-config-file-order]] ==== The Policy Search Order As we have seen above, PAM policies can be found in a number of places. What happens if policies for the same service exist in multiple places? It is essential to understand that PAM's configuration system is centered on chains. [[pam-config-breakdown]] === Breakdown of a Configuration Line As explained in <>, each line in [.filename]#/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 [.filename]#/etc/pam.d/# instead of [.filename]#/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 <>. Likewise, the control flag is one of the four keywords described in <>, 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(TM) and OpenPAM do it.) Unsurprisingly, OpenPAM does not support this syntax. [[pam-policies]] === Policies To configure PAM correctly, it is essential to understand how policies are interpreted. When an application calls man:pam_start[3], the PAM library loads the policy for the specified service and constructs four module chains (one for each facility.) If one or more of these chains are empty, the corresponding chains from the policy for the `other` service are substituted. 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 discuss below, the following table applies: .PAM Chain Execution Summary [cols="1,1,1,1", options="header"] |=== | | PAM_SUCCESS | PAM_IGNORE | other |binding |if (!fail) break; |- |fail = true; |required |- |- |fail = true; |requisite |- |- |fail = true; break; |sufficient |if (!fail) break; |- |- |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 man:pam_setcred[3] treats `binding` and `sufficient` modules as if they were `required`. The third and final exception is that man: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 `binding` and `sufficient` modules as if they were `required`. [[pam-freebsd-modules]] == FreeBSD PAM Modules [[pam-modules-deny]] === man:pam_deny[8] The man:pam_deny[8] module is one of the simplest modules available; it responds to any request with `PAM_AUTH_ERR`. It is useful for quickly disabling a service (add it to the top of every chain), or for terminating chains of `sufficient` modules. [[pam-modules-echo]] === man:pam_echo[8] The man:pam_echo[8] module simply passes its arguments to the conversation function as a `PAM_TEXT_INFO` message. It is mostly useful for debugging, but can also serve to display messages such as "Unauthorized access will be prosecuted" before starting the authentication procedure. [[pam-modules-exec]] === man:pam_exec[8] The man:pam_exec[8] module takes its first argument to be the name of a program to execute, and the remaining arguments are passed to that program as command-line arguments. One possible application is to use it to run a program at login time which mounts the user's home directory. [[pam-modules-ftpusers]] === man:pam_ftpusers[8] The man:pam_ftpusers[8] module [[pam-modules-group]] === man:pam_group[8] The man:pam_group[8] module accepts or rejects applicants on the basis of their membership in a particular file group (normally `wheel` for man:su[1]). It is primarily intended for maintaining the traditional behavior of BSD man:su[1], but has many other uses, such as excluding certain groups of users from a particular service. [[pam-modules-guest]] === man:pam_guest[8] The man:pam_guest[8] module allows guest logins using fixed login names. Various requirements can be placed on the password, but the default behavior is to allow any password as long as the login name is that of a guest account. The man:pam_guest[8] module can easily be used to implement anonymous FTP logins. [[pam-modules-krb5]] === man:pam_krb5[8] The man:pam_krb5[8] module [[pam-modules-ksu]] === man:pam_ksu[8] The man:pam_ksu[8] module [[pam-modules-lastlog]] === man:pam_lastlog[8] The man:pam_lastlog[8] module [[pam-modules-login-access]] === man:pam_login_access[8] The man:pam_login_access[8] module provides an implementation of the account management primitive which enforces the login restrictions specified in the man:login.access[5] table. [[pam-modules-nologin]] === man:pam_nologin[8] The man:pam_nologin[8] module refuses non-root logins when [.filename]#/var/run/nologin# exists. This file is normally created by man:shutdown[8] when less than five minutes remain until the scheduled shutdown time. [[pam-modules-opie]] === man:pam_opie[8] The man:pam_opie[8] module implements the man:opie[4] authentication method. The man:opie[4] system is a challenge-response mechanism where the response to each challenge is a direct function of the challenge and a passphrase, so the response can be easily computed "just in time" by anyone possessing the passphrase, eliminating the need for password lists. Moreover, since man:opie[4] never reuses a challenge that has been correctly answered, it is not vulnerable to replay attacks. [[pam-modules-opieaccess]] === man:pam_opieaccess[8] The man:pam_opieaccess[8] module is a companion module to man:pam_opie[8]. Its purpose is to enforce the restrictions codified in man:opieaccess[5], which regulate the conditions under which a user who would normally authenticate herself using man:opie[4] is allowed to use alternate methods. This is most often used to prohibit the use of password authentication from untrusted hosts. In order to be effective, the man:pam_opieaccess[8] module must be listed as `requisite` immediately after a `sufficient` entry for man:pam_opie[8], and before any other modules, in the `auth` chain. [[pam-modules-passwdqc]] === man:pam_passwdqc[8] The man:pam_passwdqc[8] module [[pam-modules-permit]] === man:pam_permit[8] The man:pam_permit[8] module is one of the simplest modules available; it responds to any request with `PAM_SUCCESS`. It is useful as a placeholder for services where one or more chains would otherwise be empty. [[pam-modules-radius]] === man:pam_radius[8] The man:pam_radius[8] module [[pam-modules-rhosts]] === man:pam_rhosts[8] The man:pam_rhosts[8] module [[pam-modules-rootok]] === man:pam_rootok[8] The man:pam_rootok[8] module reports success if and only if the real user id of the process calling it (which is assumed to be run by the applicant) is 0. This is useful for non-networked services such as man:su[1] or man:passwd[1], to which the `root` should have automatic access. [[pam-modules-securetty]] === man:pam_securetty[8] The man:pam_securetty[8] module [[pam-modules-self]] === man:pam_self[8] The man:pam_self[8] module reports success if and only if the names of the applicant matches that of the target account. It is most useful for non-networked services such as man:su[1], where the identity of the applicant can be easily verified. [[pam-modules-ssh]] === man:pam_ssh[8] The man:pam_ssh[8] module provides both authentication and session services. The authentication service allows users who have passphrase-protected SSH secret keys in their [.filename]#~/.ssh# directory to authenticate themselves by typing their passphrase. The session service starts man:ssh-agent[1] and preloads it with the keys that were decrypted in the authentication phase. This feature is particularly useful for local logins, whether in X (using man:xdm[1] or another PAM-aware X login manager) or at the console. [[pam-modules-tacplus]] === man:pam_tacplus[8] The man:pam_tacplus[8] module [[pam-modules-unix]] === man:pam_unix[8] The man:pam_unix[8] module implements traditional UNIX(R) password authentication, using man:getpwnam[3] to obtain the target account's password and compare it with the one provided by the applicant. It also provides account management services (enforcing account and password expiration times) and password-changing services. This is probably the single most useful module, as the great majority of admins will want to maintain historical behavior for at least some services. [[pam-appl-prog]] == PAM Application Programming This section has not yet been written. [[pam-module-prog]] == PAM Module Programming This section has not yet been written. :sectnums!: [appendix] [[pam-sample-appl]] == Sample PAM Application The following is a minimal implementation of man:su[1] using PAM. Note that it uses the OpenPAM-specific man:openpam_ttyconv[3] conversation function, which is prototyped in [.filename]#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 <> is a good starting point, but should not be used in real-world applications. [.programlisting] .... ifeval::["{backend}" == "html5"] include::static/source/articles/pam/su.c[] endif::[] ifeval::["{backend}" == "pdf"] include::../../../../static/source/articles/pam/su.c[] endif::[] ifeval::["{backend}" == "epub3"] include::../../../../static/source/articles/pam/su.c[] endif::[] .... :sectnums!: [appendix] [[pam-sample-module]] == Sample PAM Module The following is a minimal implementation of man: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 man:pam_get_authtok[3], which enormously simplifies prompting the user for a password. [.programlisting] .... ifeval::["{backend}" == "html5"] include::static/source/articles/pam/pam_unix.c[] endif::[] ifeval::["{backend}" == "pdf"] include::../../../../static/source/articles/pam/pam_unix.c[] endif::[] ifeval::["{backend}" == "epub3"] include::../../../../static/source/articles/pam/pam_unix.c[] endif::[] .... :sectnums!: [appendix] [[pam-sample-conv]] == Sample PAM Conversation Function The conversation function presented below is a greatly simplified version of OpenPAM's man: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 are not using OpenPAM, feel free to download the source code and adapt man:openpam_ttyconv[3] to your uses; we believe it to be as robust as a tty-oriented conversation function can reasonably get. [.programlisting] .... ifeval::["{backend}" == "html5"] include::static/source/articles/pam/converse.c[] endif::[] ifeval::["{backend}" == "pdf"] include::../../../../static/source/articles/pam/converse.c[] endif::[] ifeval::["{backend}" == "epub3"] include::../../../../static/source/articles/pam/converse.c[] endif::[] .... :sectnums!: [[pam-further]] == Further Reading === Papers Making Login Services Independent of Authentication Technologies Vipin Samar. Charlie Lai. Sun Microsystems. _link:https://pubs.opengroup.org/onlinepubs/8329799/toc.htm[X/Open Single Sign-on Preliminary Specification]_. The Open Group. 1-85912-144-6. June 1997. _link:https://mirrors.kernel.org/pub/linux/libs/pam/pre/doc/draft-morgan-pam-07.txt[Pluggable Authentication Modules]_. Andrew G. Morgan. 1999-10-06. === User Manuals _link:https://docs.oracle.com/cd/E26505_01/html/E27224/pam-1.html[PAM Administration]_. Sun Microsystems. === Related Web Pages _link:https://www.openpam.org/[OpenPAM homepage]_ Dag-Erling Smørgrav. ThinkSec AS. _link:http://www.kernel.org/pub/linux/libs/pam/[Linux-PAM homepage]_ Andrew Morgan. _Solaris PAM homepage_. Sun Microsystems. diff --git a/documentation/content/fr/articles/pam/_index.adoc b/documentation/content/fr/articles/pam/_index.adoc index 8daeac087b..1917721569 100644 --- a/documentation/content/fr/articles/pam/_index.adoc +++ b/documentation/content/fr/articles/pam/_index.adoc @@ -1,600 +1,634 @@ --- title: Pluggable Authentication Modules authors: - author: Dag-Erling Smørgrav copyright: 2001-2003 Networks Associates Technology, Inc. releaseinfo: "$FreeBSD$" trademarks: ["pam", "freebsd", "linux", "opengroup", "sun", "general"] --- +//// +Copyright (c) 2001-2003 Networks Associates Technology, Inc. +All rights reserved. + +This software was developed 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. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. The name of the author may not be used to endorse or promote + products derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. +//// + = Pluggable Authentication Modules :doctype: article :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :source-highlighter: rouge :experimental: :toc-title: Table des matières :part-signifier: Partie :chapter-signifier: Chapitre :appendix-caption: Annexe :table-caption: Tableau :example-caption: Exemple [.abstract-title] Abstract Cet article décrit les principes sous-jacent et les mécanismes de la bibliothèque PAM, il explique comment configurer PAM, l'intégrer dans les applications, et écrire ses propres modules PAM. Version française de Clément Mathieu ``. ''' toc::[] [[pam-intro]] == Introduction La bibliothèque PAM est une API généralisée pour les services relevant de l'authentification permettant à un administrateur système d'ajouter une nouvelle méthode d'authentification en ajoutant simplement un nouveau module PAM, ainsi que de modifier les règles d'authentification en éditant les fichiers de configuration. PAM a été conçu et développé en 1995 par Vipin Samar et Charlie Lai de Sun Microsystems, et n'a pas beaucoup évolué depuis. En 1997 l'Open Group publie les premières spécifications XSSO qui standardisent l'API PAM et ajoute des extensions pour un simple (ou plutot intégré) "sign-on". Lors de l'écriture de cet article, la spécification n'a toujours pas été adoptée comme standard. Bien que cet article se concentre principalement sur FreeBSD 5.x, qui utilise OpenPAM, il devrait également être applicable à FreeBSD 4.x qui utilise Linux-PAM, ainsi qu'à d'autres systèmes d'exploitations tels que Linux ou Solaris. [[pam-trademarks]] == Marques déposées Sun, Sun Microsystems, SunOS 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. [[pam-terms]] == Termes et conventions [[pam-definitions]] == Définitions La terminologie de PAM est plutôt confuse. Ni la publication originale de Samar et Lai, ni la spécification XSSO n'ont essayé de définir formellement des termes pour les acteurs et les entités intervenant dans PAM, les termes qu'ils utilisent (mais ne définissent pas) sont parfois trompeurs et ambigus. Le premier essai d'établir une terminologie consistante et non ambiguë fut un papier écrit par Andrew G. Morgan (l'auteur de Linux-PAM) en 1999. Bien que les choix de Morgan furent un énorme pas en avant, ils ne sont pas parfait d'après l'auteur de ce document. Ce qui suit, largement inspiré par Morgan, est un essai de définir précisément et sans ambiguïté des termes pour chaque acteur ou entité utilisé dans PAM. [.glosslist] compte:: L'ensemble de permissions que le demandeur demande a l'arbitre. demandeur:: L'utilisateur ou l'entité demandant authentification. arbitre:: L'utilisateur ou l'entité possédant les privilèges nécessaires pour vérifier la requête du demandeur ainsi que l'autorité d'accorder ou de rejeter la requête. chaîne:: Une séquence de modules qui sera invoquée pour répondre à une requête PAM. La chaîne comprend les informations concernant l'ordre dans lequel invoquer les modules, les arguments à leur passer et la façon d'interpréter les résultats. client:: L'application responsable de la requête d'authentification au nom du demandeur et de recueillir l'information d'authentification nécessaire. mécanisme:: Il s'agit de l'un des quatre groupes basiques de fonctionnalités fournit par PAM : authentification, gestion de compte, gestion de session et mise à jour du jeton d'authentification. module:: Une collection d'une ou plusieurs fonctions implémentant un service d'authentification particulier, rassemblées dans un fichier binaire (normalement chargeable dynamiquement) et identifié par un nom unique. règles:: Le jeu complet de configuration des règles décrivant comment traiter les requêtes PAM pour un service particulier. Une règle consiste normalement en quatre chaînes, une pour chaque mécanisme, bien que quelques services n'utilisent pas les quatre mécanismes. serveur:: L'application agissant au nom de l'arbitre pour converser avec le client, récupérer les informations d'authentification, vérifier les droits du demandeur et autoriser ou rejeter la requête. service:: Un ensemble de serveurs fournissant des fonctionnalités similaires ou liées et nécessitant une authentification similaire. Les règles de PAM sont définies sur un le principe de par-service; ainsi tous les serveurs qui demandent le même nom de service seront soumis aux mêmes règles. session:: Le contexte dans lequel le service est délivré au demandeur par le serveur. L'un des quatre mécanismes de PAM, la gestion de session, s'en occupe exclusivement par la mise en place et le relâchement de ce contexte. jeton:: Un morceau d'information associé avec un compte tel qu'un mot de passe ou une passphrase que le demandeur doit fournir pour prouver son identité. transaction:: Une séquence de requêtes depuis le même demandeur vers la même instance du même serveur, commençant avec l'authentification et la mise en place de la session et se terminant avec le démontage de la session. [[pam-usage-examples]] == Exemples d'utilisation Cette section a pour but d'illustrer quelques-uns des termes définis précédemment à l'aide d'exemples basiques. == Client et serveurs ne font qu'un Cet exemple simple montre `alice` utilisant man:su[1] pour devenir `root`. [source,shell] .... % 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 .... * Le demandeur est `alice`. * Le compte est `root`. * Le processus man:su[1] est à la fois client et serveur. * Le jeton d'authentification est `xi3kiune`. * L'arbitre est `root`, ce qui explique pourquoi man:su[1] est setuid `root`. == Client et serveur sont distincts. L'exemple suivant montre `eve` essayant d'initier une connexion man:ssh[1] vers `login.exemple.com`, en demandant à se logguer en tant que `bob`. La connexion réussit. Bob aurait du choisir un meilleur mot de passe ! [source,shell] .... % 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! % .... * Le demandeur est `eve`. * Le client d'`eve` est représenté par les processus man:ssh[1] * Le serveur est le processus man:sshd[8] sur `login.example.com` * Le compte est `bob`. * Le jeton d'identification est `god`. * Bien que cela ne soit pas montré dans cet exemple, l'arbitre est `root`. == Exemple de règles Les lignes qui suivent sont les règles par défaut de `sshd`: [.programlisting] .... 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 .... * Cette politique s'applique au service `sshd` (qui n'est pas nécessairement restreint au serveur man:sshd[8]) * `auth`, `account`, `session` et `password` sont des mécanismes. * [.filename]#pam_nologin.so#, [.filename]#pam_unix.so#, [.filename]#pam_login_access.so#, [.filename]#pam_lastlog.so# et [.filename]#pam_permit.so# sont des modules. Il est clair dans cet exemple que [.filename]#pam_unix.so# fournit au moins deux mécanismes ( authentification et gestion de compte). [[pam-conventions]] == Conventions Cette section n'a pas encore été écrite. [[pam-essentials]] == Les bases de PAM [[pam-facilities-primitives]] == Mécanismes et primitives L'API PAM fournit six primitives d'authentification différentes regroupées dans quatre mécanismes qui seront décrits dans la partie suivante. `auth`:: _Authentification._ Ce mécanisme concerne l'authentification du demandeur et établit les droits du compte. Il fournit deux primitives : ** man:pam_authenticate[3] authentifie le demandeur, généralement en demandant un jeton d'identification et en le comparant a une valeur stockée dans une base de données ou obtenue par le biais d'un serveur d'authentification. ** man:pam_setcred[3] établi les paramètres du compte tel que l'uid, les groupes dont le compte fait parti ou les limites sur l'utilisation des ressources. `account`:: _Gestion de compte._ Ce mécanisme concerne la disponibilité du compte pour des raisons autres que l'authentification. Par exemple les restrictions basées sur l'heure courante ou la charge du serveur. Il fournit une seule primitive: ** man:pam_acct_mgmt[3] vérifie que le compte demandé est disponible. `session`:: _Gestion de session._ Ce mécanisme concerne la mise en place de la session et sa terminaison, par exemple l'enregistrement de la session dans les journaux. Il fournit deux primitives: ** man:pam_open_session[3] accomplie les tâches associées à la mise en place d'une session : ajouter une entrée dans les bases [.filename]#utmp# et [.filename]#wtmp#, démarrer un agent SSH... ** man:pam_close_session[3] accomplie les tâches associées à la terminaison d'une session : ajouter une entrée dans les bases [.filename]#utmp# et [.filename]#wtmp#, arrêter l'agent SSH... `password`:: _Gestion des mots de passe._ Ce mécanisme est utilisé pour modifier le jeton d'authentification associé à un compte, soit parce qu'il a expiré, soit parce que l'utilisateur désire le changer. Il fournit une seule primitive: ** man:pam_chauthtok[3] modifie le jeton d'authentification, et éventuellement vérifie que celui-ci est assez robuste pour ne pas être deviné facilement ou qu'il n'a pas déjà utilisé. [[pam-modules]] === Modules Les modules sont le concept clef de PAM; après tout ils constituent le "M" de PAM. Un module PAM est lui-même un morceau de code qui implémente les primitives d'un ou plusieurs mécanismes pour une forme particulière d'authentification; par exemple, les bases de mots de passe UNIX que sont NIS, LDAP et Radius. [[pam-module-naming]] == Nom des modules FreeBSD implémente chaque mécanismes dans un module distinct nommé `pam_mécanisme.so` (par exemple `pam_unix.so` pour le mécanisme Unix .) Les autres implementations possèdent parfois des modules séparés pour des mécanismes séparés et incluent aussi bien le nom du service que celui du mécanisme dans le nom du module. Un exemple est le module `pam_dial_auth.so.1` de Solaris qui est utilisé pour authentifier les utilisateurs dialup. [[pam-module-versioning]] == Gestion des versions de module L'implémentation originale de PAM par FreeBSD, basée sur Linux-PAM, n'utilisait pas de numéro de version pour les modules PAM. Ceci peut poser des problèmes avec les applications tiers qui peuvent être liées avec d'anciennes bibliothèques systèmes, puisqu'il n'y a pas possibilité de charger la version correspondante du module désiré. Pour sa part, OpenPAM cherche les modules qui ont la même version que la bibliothèque PAM (pour le moment 2) et se rabat sur un module sans version si aucun module avec version n'a put être chargé. Ainsi les anciens modules peuvent être fournis pour les anciennes applications, tout en permettant aux nouvelles applications (ou bien nouvellement compilées) de tirer parti des modules les plus récents. Bien que les modules PAM de Solaris possèdent généralement un numéro de version, ils ne sont pas réellement versionnés car le numéro correspond à une partie du nom du module et doit être inclus dans la configuration. [[pam-chains-policies]] == Chaînes et politiques Lorsqu'un serveur initie une transaction PAM, la bibliothèque PAM essaie de charger une politique pour le service spécifié dans l'appel a man:pam_start[3] . La politique indique comment la requête d'authentification doit être traitée et est définie dans un fichier de configuration. Il s'agit de l'autre concept clef de PAM : la possibilité pour l'administrateur de configurer la politique de sécurité d'un système en éditant simplement une fichier texte. Une politique consiste en quatre chaînes, une pour chacune des quatre mécanismes de PAM. Chaque chaîne est une suite de règles de configuration, chacune spécifiant un module à invoquer, des paramètres, options, à passer au module et un drapeau de contrôle qui décrit comment interpréter le code de retour du module. Comprendre le drapeau de contrôle est essentiel pour comprendre les fichiers de configuration de PAM. Il existe quatre drapeaux de contrôle différents : `binding`:: Si le module réussit et qu'aucun module précédent de la chaîne n'a échoué, la chaîne s'interrompt immédiatement et la requête est autorisée. Si le module échoue le reste de la chaîne est exécuté, mais la requête est rejetée au final. + Ce drapeau de contrôle a été introduit par Sun Solaris dans la version 9 (SunOS 5.9); il est aussi supporté par OpenPAM. `required`:: Si le module réussit, le reste de la chaîne est exécuté, et la requête est autorisée si aucun des autres modules n'échoue. Si le module échoue, le reste de la chaîne est exécuté, mais au final la requête est rejetée. `requisite`:: Si le module réussit le reste de la chaîne est exécuté, et la requête est autorisée sauf si d'autres modules échoués. Si le module échoue la chaîne est immédiatement terminée et la requête est rejetée. `sufficient`:: Si le module réussit et qu'aucun des modules précédent n'a échoué la chaîne est immédiatement terminée et la requête est allouée. Si le module échoue il est ignore et le reste de la chaîne est exécuté. + Puisque la sémantique de ce drapeau peut être un peu confuse, spécialement lorsqu'il s'agit de celui du dernier module de la chaîne, il est recommandé d'utiliser le drapeau `binding` à la place de celui-ci sous la condition que l'implémentation le supporte. `optional`:: Le module est exécuté mais le résultat est ignoré. Si tout les modules de la chaîne sont marqués `optional`, toutes les requêtes seront toujours acceptées. Lorsqu'un serveur invoque l'une des six primitives PAM, PAM récupère la chaîne du mécanisme à laquelle la requête correspond et invoque chaque module de la chaîne dans l'ordre indiqué, jusqu'à ce que la fin soit atteinte ou qu'aucune exécution supplémentaire ne soit nécessaire (soit à cause du succès d'un module en `binding` ou `sufficient`, soit à cause de l'échec d'un module `requisite`). La requête est acceptée si et seulement si au moins un module a été invoqué, et que tout les modules non optionnels ont réussi. Notez qu'il est possible, bien que peu courant, d'avoir le même module listé plusieurs fois dans la même chaîne. Par exemple un module qui détermine le nom utilisateur et le mot de passe à l'aide d'un serveur directory peut être invoqué plusieurs fois avec des paramètres spécifiant différents serveurs a contacter. PAM considère les différentes occurrences d'un même module dans une même chaîne comme des modules différents et non liés. [[pam-transactions]] === Transactions Le cycle de vie d'une transaction PAM typique est décrit ci-dessous. Notez que si l'une de ces étapes échoue, le serveur devrait reporter un message d'erreur au client et arrêter la transaction. . Si nécessaire, le serveur obtient les privilèges de l'arbitre par le biais d'un mécanisme indépendant de PAM - généralement en ayant été démarré par `root` ou en étant setuid `root`. . Le serveur appel man:pam_start[3] afin d'initialiser la bibliothèque PAM et indique le service et le compte cible, et enregistre une fonction de conversation appropriée. . Le serveur obtient diverses informations concernant la transaction (tel que le nom d'utilisateur du demandeur et le nom d'hôte de la machine sur lequel le client tourne) et les soumet à PAM en utilisant la fonction man:pam_set_item[3]. . Le serveur appel man:pam_authenticate[3] pour authentifier le demandeur. . Le serveur appel la fonction man:pam_acct_mgmt[3] qui vérifie que le compte est valide et disponible. Si le mot de passe est correct mais a expiré, man:pam_acct_mgmt[3] retournera `PAM_NEW_AUTHTOK_REQD` à la place de `PAM_SUCCESS`. . Si l'étape précédente a retourné `PAM_NEW_AUTHTOK_REQD`, le serveur appel maintenant man:pam_chauthtok[3] pour obliger l'utilisateur à changer le jeton d'authentification du compte désiré. . Maintenant que le demandeur a été correctement authentifié, le serveur appelle man:pam_setcred[3] pour obtenir les privilèges du compte désiré. Il lui est possible de faire ceci parce qu'il agit au nom de l'arbitre dont il possède les privilèges. . Lorsque les privilèges corrects ont été établi le serveur appelle man:pam_open_session[3] pour mettre en place la session. . Maintenant le serveur effectue les services demandés par le client - par exemple fournir un shell au demandeur. . Lorsque le serveur a fini de servir le client, il appelle man:pam_close_session[3] afin de terminer la session. . Pour finir, le serveur appelle man:pam_end[3] afin signaler à la bibliothèque PAM que la transaction se termine et qu'elle peut libérer les ressources qu'elle a alloué au cours de la transaction. [[pam-config]] == Configuration de PAM [[pam-config-file-locations]] == Emplacement des fichiers de configuration Le fichier de configuration de PAM est traditionnellement [.filename]#/etc/pam.conf#. Ce fichier contient toutes les politiques de PAM pour votre système. Chaque ligne du fichier décrit une étape dans une chaîne, tel que nous allons le voir ci-dessous: [.programlisting] .... login auth required pam_nologin.so no_warn .... Les champs sont respectivement, le service, le nom du mécanisme, le drapeau de contrôle, le nom du module et les arguments du module. Tout champ additionnel est considéré comme argument du module. Une chaîne différente est construite pour chaque couple service/mécanisme; ainsi, alors que l'ordre des lignes est important lorsqu'il s'agit des mêmes services ou mécanismes, l'ordre dans lequel les différents services et mécanismes apparaissent ne l'est pas - excepté l'entrée pour le service `other`, qui sert de référence par défaut et doit être placé à la fin. L'exemple du papier original sur PAM regroupait les lignes de configurations par mécanisme et le fichier [.filename]#pam.conf# de Solaris le fait toujours, mais FreeBSD groupe les lignes de configuration par service. Toutefois il ne s'agit pas de la seule possibilité et les autres possèdent aussi un sens. OpenPAM et Linux-PAM offrent un mécanisme de configuration alternatif où les politiques sont placées dans des fichiers séparés portant le nom du service auquel ils s'appliquent. Ces fichiers sont situés dans [.filename]#/etc/pam.d/# et ne contiennent que quatre champs à la place de cinq - le champ contenant le nom du service est omis. Il s'agit du mode par défaut dans FreeBSD 4.x. Notez que si le fichier [.filename]#/etc/pam.conf# existe et contient des informations de configuration pour des services qui n'ont pas de politique spécifiée dans [.filename]#/etc/pam.d#, ils seront utilisés pour ces services. Le gros avantage de [.filename]#/etc/pam.d/# sur [.filename]#/etc/pam.conf# est qu'il est possible d'utiliser la même politique pour plusieurs services en liant chaque nom de service à un fichier de configuration. Par exemple pour utiliser la même politique pour les services `su` et `sudo`, nous pouvons faire comme ceci : [source,shell] .... # cd /etc/pam.d # ln -s su sudo .... Ceci fonctionne car le nom de service est déterminé a partir du nom de fichier plutôt qu'indiqué à l'intérieur du fichier de configuration, ainsi le même fichier peut être utilisé pour des services nommés différemment. Un autre avantage est qu'un logiciel tiers peu facilement installer les politiques pour ses services sans avoir besoin d'éditer [.filename]#/etc/pam.conf#. Pour continuer la tradition de FreeBSD, OpenPAM regardera dans [.filename]#/usr/local/etc/pam.d# pour trouver les fichiers de configurations; puis si aucun n'est trouvé pour le service demandé, il cherchera dans [.filename]#/etc/pam.d/# ou [.filename]#/etc/pam.conf#. Finalement, quelque soit le mécanisme que vous choisissiez, la politique "magique"`other` est utilisée par défaut pour tous les services qui n'ont pas leur propre politique. [[pam-config-breakdown]] == Breakdown of a configuration line Comme expliqué dans <>, chaque ligne de [.filename]#pam.conf# consiste en quatre champs ou plus: le nom de service, le nom du mécanisme, le drapeau de contrôle, le nom du module et la présence ou non d'arguments pour le module. Le nom du service est généralement, mais pas toujours, le nom de l'application auquelle les règles s'appliquent. Si vous n'êtes pas sûr, référez vous à la documentation de l'application pour déterminer quel nom de service elle utilise. Notez que si vous utilisez [.filename]#/etc/pam.d/# à la place de [.filename]#/etc/pam.conf#, le nom du service est spécifié par le nom du fichier de configuration et n'est pas indiqué dans les lignes de configuration qui, dès lors, commencent par le nom du mécanisme. Le mécanisme est l'un des quatre mots clef décrit dans <>. De même, le drapeau de contrôle est l'un des quatre mots clef décrits dans <> et décrit comment le module doit interpréter le code de retour du module. Linux-PAM supporte une syntaxe alternative qui vous laisse spécifier l'action à associer à chaque code de retour possible; mais ceci devrait être évité puisque ce n'est pas standard et étroitement lié à la façon dont Linux-PAM appelle les services (qui diffère grandement de la façon de Solaris et OpenPAM). C'est sans étonnement que l'on apprend qu'OpenPAM ne supporte pas cette syntaxe. [[pam-policies]] == Politiques Pour configurer PAM correctement, il est essentiel de comprendre comment les politiques sont interprétées. Lorsqu'une application appelle man:pam_start[3] la bibliothèque PAM charge la politique du service spécifié et construit les quatre chaînes de module (une pour chaque mécanisme). Si une ou plusieurs chaînes sont vides, les chaînes de la politique du service `other` sont utilisées. Plus tard, lorsque l'application appelle l'une des six primitives PAM, la bibliothèque PAM récupère la chaîne du mécanisme correspondant et appelle la fonction appropriée avec chaque module listé dans la chaîne. Après chaque appel d'une fonction de service, le type du module et le code d'erreur sont retournés par celle-ci pour déterminer quoi faire. À quelques exceptions près, dont nous parlerons plus tard, la table suivante s'applique: .Résumé de la chaîne d'exécution PAM [cols="1,1,1,1", options="header"] |=== | | PAM_SUCCESS | PAM_IGNORE | other |binding |if (!fail) break; |- |fail = true; |required |- |- |fail = true; |requisite |- |- |fail = true; break; |sufficient |if (!fail) break; |- |- |optional |- |- |- |=== Si `fail` est vrai à la fin de la chaîne, ou lorsqu'un "break" est atteint, le dispatcheur retourne le code d'erreur renvoyé par le premier module qui a échoué. Autrement `PAM_SUCCESS` est retourné. La première exception est que le code d'erreur `PAM_NEW_AUTHOK_REQD` soit considéré comme un succès, sauf si aucun module n'échoue et qu'au moins un module retourne `PAM_NEW_AUTHOK_REQD` le dispatcheur retournera `PAM_NEW_AUTHOK_REQD`. La seconde exception est que man:pam_setcred[3] considère les modules `binding` et `sufficient` comme s'ils étaient `required`. La troisième et dernière exception est que man:pam_chauthtok[3] exécute la totalité de la chaîne deux fois (la première pour des vérifications préliminaires et la deuxième pour mettre le mot de passe) et lors de la première exécution il considère les modules `binding` et `sufficient` comme s'ils étaient `required`. [[pam-freebsd-modules]] == Les modules PAM de FreeBSD [[pam-modules-deny]] === man:pam_deny[8] Le module man:pam_deny[8] est l'un des modules disponibles les plus simples; il répond à n'importe qu'elle requête par `PAM_AUTH_ERR`. Il est utile pour désactiver rapidement un service (ajoutez-le au début de chaque chaîne), ou pour terminer les chaînes de modules `sufficient`. [[pam-modules-echo]] === man:pam_echo[8] Le module man:pam_echo[8] passe simplement ses arguments à la fonction de conversation comme un message `PAM_TEXT_INFO`. Il est principalement utilisé pour le debogage mais il peut aussi servir à afficher un message tel que "Les accès illégaux seront poursuivits" avant de commencer la procédure d'authentification. [[pam-modules-exec]] === man:pam_exec[8] Le module man:pam_exec[8] prend comme premier argument le nom du programme à exécuter, les arguments restant étant utilisés comme arguments pour ce programme. L'une des applications possibles est d'utiliser un programme qui monte le répertoire de l'utilisateur lors du login. [[pam-modules-ftp]] == pam_ftp(8) Le module pam_ftp(8) [[pam-modules-ftpusers]] === man:pam_ftpusers[8] Le module man:pam_ftpusers[8] [[pam-modules-group]] === man:pam_group[8] Le module man:pam_group[8] accepte ou rejette le demandeur à partir de son appartenance à un groupe particulier (généralement `wheel` pour man:su[1]). Il a pour but premier de conserver le comportement traditionnel de man:su[1] mais possède d'autres applications comme par exemple exclure un certain groupe d'utilisateurs d'un service particulier. [[pam-modules-krb5]] === man:pam_krb5[8] Le module man:pam_krb5[8] [[pam-modules-ksu]] === man:pam_ksu[8] Le module man:pam_ksu[8] [[pam-modules-lastlog]] === man:pam_lastlog[8] Le module man:pam_lastlog[8] [[pam-modules-login-access]] === man:pam_login_access[8] Le module man:pam_login_access[8] [[pam-modules-nologin]] === man:pam_nologin[8] Le module man:pam_nologin[8] [[pam-modules-opie]] === man:pam_opie[8] Le module man:pam_opie[8] implémente la méthode d'authentification man:opie[4]. Le système man:opie[4] est un mécanisme de challenge-response où la réponse à chaque challenge est une fonction directe du challenge et une phrase de passe, ainsi la réponse peut facilement être calculée "en temps voulu" par n'importe qui possédant la phrase de passe ce qui élimine le besoin d'une liste de mots de passe. De plus, puisque man:opie[4] ne réutilise jamais un mot de passe qui a reçu une réponse correcte, il n'est pas vulnérable aux attaques basée sur le rejouage. [[pam-modules-opieaccess]] === man:pam_opieaccess[8] Le module man:pam_opieaccess[8] est un compagnon du module man:pam_opie[8]. Son but est de renforcer les restrictions codifiées dans man:opieaccess[5], il régule les conditions sous lesquelles un utilisateur qui normalement devrait s'authentifier par man:opie[4] est amené à utiliser d'autres méthodes. Ceci est généralement utilisé pour interdire l'authentification par mot de passe depuis des hôtes non digne de confiance. Pour être réellement effectif, le module man:pam_opieaccess[8] doit être listé comme `requisite` immédiatement après une entrée `sufficient` pour man:pam_opie[8] et avant tout autre module, dans la chaîne `auth`. [[pam-modules-passwdqc]] === man:pam_passwdqc[8] Le module man:pam_passwdqc[8] [[pam-modules-permit]] === man:pam_permit[8] Le module man:pam_permit[8] est l'un des modules disponibles les plus simples; il répond à n'importe quelle requête par `PAM_SUCCESS`. Il est utile pour les services où une ou plusieurs chaînes auraient autrement été vides. [[pam-modules-radius]] === man:pam_radius[8] Le module man:pam_radius[8] [[pam-modules-rhosts]] === man:pam_rhosts[8] Le module man:pam_rhosts[8] [[pam-modules-rootok]] === man:pam_rootok[8] Le module man:pam_rootok[8] retourne un succès si et seulement si l'identifiant d'utilisateur réel du processus appelant est 0. Ceci est utile pour les services non basés sur le réseau tel que man:su[1] ou man:passwd[1] où l'utilisateur `root` doit avoir un accès automatique. [[pam-modules-securetty]] === man:pam_securetty[8] Le module man:pam_securetty[8] [[pam-modules-self]] === man:pam_self[8] Le module man:pam_self[8] retourne un succès si et seulement si le nom du demandeur correspond au nom du compte désiré. Il est utile pour les services non basés sur le réseau tel que man:su[1] où l'identité du demandeur peut être vérifiée facilement . [[pam-modules-ssh]] === man:pam_ssh[8] Le module man:pam_ssh[8] [[pam-modules-tacplus]] === man:pam_tacplus[8] Le module man:pam_tacplus[8] [[pam-modules-unix]] === man:pam_unix[8] Le module man:pam_unix[8] implémente l'authentification Unix traditionnelle par mot de passe, il utilise man:getpwnam[3] pour obtenir le mot de passe du compte visé et le compare avec celui fournit par le demandeur. Il fournit aussi des services de gestion de compte (désactivation du compte et date d'expiration) ainsi que des services pour le changement de mot de passe. Il s'agit certainement du module le plus utile car la plupart des administrateurs désirent garder le comportement historique pour quelques services. [[pam-appl-prog]] == Programmation d'applications PAM Cette section n'a pas encore été écrite. [[pam-module-prog]] == Programmation de modules PAM Cette section n'a pas été encore écrite. :sectnums!: [appendix] [[pam-sample-appl]] == Exemples d'application PAM Ce qui suit est une implémentation minimale de man:su[1] en utilisant PAM. Notez qu'elle utilise la fonction de conversation man:openpam_ttyconv[3] spécifique à OpenPAM qui est prototypée dans [.filename]#security/openpam.h#. Si vous désirez construire cette application sur un système utilisant une bibliothèque PAM différente vous devrez fournir votre propre fonction de conversation. Une fonction de conversation robuste est étonnamment difficile à implémenter; celle présentée dans <> est un bon point de départ, mais ne devrait pas être utilisée dans des applications réelles. [.programlisting] .... ifeval::["{backend}" == "html5"] include::static/source/articles/pam/su.c[] endif::[] ifeval::["{backend}" == "pdf"] include::../../../../static/source/articles/pam/su.c[] endif::[] ifeval::["{backend}" == "epub3"] include::../../../../static/source/articles/pam/su.c[] endif::[] .... :sectnums!: [appendix] [[pam-sample-module]] == Exemple d'un module PAM Ce qui suit est une implémentation minimale de man:pam_unix[8] offrant uniquement les services d'authentification. Elle devrait compiler et tourner avec la plupart des implémentations PAM, mais tire parti des extensions d'OpenPAM si elles sont disponibles : notez l'utilisation de man:pam_get_authtok[3] qui simplifie énormément l'affichage de l'invite pour demander le mot de passe à l'utilisateur. [.programlisting] .... ifeval::["{backend}" == "html5"] include::static/source/articles/pam/pam_unix.c[] endif::[] ifeval::["{backend}" == "pdf"] include::../../../../static/source/articles/pam/pam_unix.c[] endif::[] ifeval::["{backend}" == "epub3"] include::../../../../static/source/articles/pam/pam_unix.c[] endif::[] .... :sectnums!: [appendix] [[pam-sample-conv]] == Exemple d'une fonction de conversation PAM La fonction de conversation présentée ci-dessous est une version grandement simplifiée de la fonction man:openpam_ttyconv[3] d'OpenPAM. Elle est pleinement fonctionnelle et devrait donner au lecteur une bonne idée de comment doit se comporter une fonction de conversation, mais elle est trop simple pour une utilisation réelle. Même si vous n'utilisez pas OpenPAM, N'hésitez pas à télécharger le code source et d'adapter man:openpam_ttyconv[3] à vos besoins, nous pensons qu'elle est raisonnablement aussi robuste qu'une fonction de conversation orientée tty peut l'être. [.programlisting] .... ifeval::["{backend}" == "html5"] include::static/source/articles/pam/converse.c[] endif::[] ifeval::["{backend}" == "pdf"] include::../../../../static/source/articles/pam/converse.c[] endif::[] ifeval::["{backend}" == "epub3"] include::../../../../static/source/articles/pam/converse.c[] endif::[] .... :sectnums!: [[pam-further]] == Lectures complémentaires === Publications _link:http://www.sun.com/software/solaris/pam/pam.external.pdf[Rendre les services de connexion indépendants des technologies d'authentification]_. Vipin Samar et Charlie Lai. Sun Microsystems. _link:http://www.opengroup.org/pubs/catalog/p702.htm[X/Open Single Sign-on Preliminary Specification]_. The Open Group. 1-85912-144-6. June 1997. _link:http://www.kernel.org/pub/linux/libs/pam/pre/doc/current-draft.txt[Pluggable Authentication Modules]_. Andrew G. Morgan. 1999-10-06. === Guides utilisateur _link:http://www.sun.com/software/solaris/pam/pam.admin.pdf[Administration de PAM]_. Sun Microsystems. === Page internet liées _link:http://openpam.sourceforge.net/[La page d'OpenPAM]_. Dag-Erling Smørgrav. ThinkSec AS. _link:http://www.kernel.org/pub/linux/libs/pam/[La page de Linux-PAM]_. Andrew G. Morgan. _link:http://wwws.sun.com/software/solaris/pam/[La page de Solaris PAM]_. Sun Microsystems. diff --git a/documentation/content/ru/articles/pam/_index.adoc b/documentation/content/ru/articles/pam/_index.adoc index 38aced4fe4..a99b44630a 100644 --- a/documentation/content/ru/articles/pam/_index.adoc +++ b/documentation/content/ru/articles/pam/_index.adoc @@ -1,570 +1,604 @@ --- title: Подключаемые Модули Аутентификации (PAM) authors: - author: Dag-Erling Smørgrav releaseinfo: "$FreeBSD$" trademarks: ["pam", "freebsd", "linux", "opengroup", "sun", "general"] --- +//// +Copyright (c) 2001-2003 Networks Associates Technology, Inc. +All rights reserved. + +This software was developed 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. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. The name of the author may not be used to endorse or promote + products derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. +//// + = Подключаемые Модули Аутентификации (PAM) :doctype: article :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :source-highlighter: rouge :experimental: :toc-title: Содержание :part-signifier: Часть :chapter-signifier: Глава :appendix-caption: Приложение :table-caption: Таблица :figure-caption: Рисунок :example-caption: Пример [.abstract-title] Abstract В этой статье описываются принципы и механизмы, лежащие в основе библиотеки Подключаемых Модулей Аутентификации (PAM - Pluggable Authentication Modules), и рассказывается, как настроить PAM, как интегрировать PAM в приложения и как создавать модули PAM. ''' toc::[] [[pam-intro]] == Введение Библиотека Pluggable Authentication Modules (PAM) является обобщённым API для служб, связанных с аутентификацией, которые позволяют системному администратору добавлять новые методы аутентификации простой установкой новых модулей PAM, и изменять политику аутентификации посредством редактирования конфигурационных файлов. PAM описали и разработали Vipin Samar и Charlie Lai из Sun Microsystems в 1995 году, с тех он сильно не менялся. В 1997 году Open Group опубликовала предварительные спецификации на X/Open Single Sign-on (XSSO), что стандартизовало API для PAM и добавило расширения для одноразовой (или достаточно интегрированной) подписи. На момент написания этого документа эта спецификация ещё не была принята за стандарт. Хотя эта статья посвящена в основном FreeBSD 5.x, в которой используется OpenPAM, она подойдёт для FreeBSD 4.x, использующей Linux-PAM, и других операционных систем, таких, как Linux и Solaris(TM). [[pam-terms]] == Термины и соглашения [[pam-definitions]] == Определения Терминология, используемая в PAM, достаточно запутана. Ни оригинальная работа Samar и Lai, ни спецификация XSSO не делают никаких попыток формально определить термины для различных объектов и участвующих в PAM сторон, а термины, которые они используют (но не определяют) иногда неверны и неоднозначны. Первой попыткой создать недвусмысленную и согласованную терминологию была работа, которую написал Andrew G. Morgan (автор Linux-PAM) в 1999 году. Хотя выбор терминологии, которую сделал Морган, был гигантским скачком вперед, это, по мнению автора данной статьи, не означает ее правильность. Далее делается попытка, в значительной степени на основе работы Моргана, дать точные и недвусмысленные определения терминов для всех участников и объектов PAM. [.glosslist] учётная запись (account):: Набор полномочий, которые аппликант запрашивает от арбитратора. аппликант (applicant):: Пользователь или объект, запрашивающие аутентификацию. арбитратор (arbitrator):: Пользователь или объект, имеющий привилегии, достаточные для проверки полномочий аппликанта и права подтвердить или отклонить запрос. цепочка (chain):: Последовательность модулей, которые будут вызваны в ответ на запрос PAM. В цепочку включена информация о последовательности вызовов модулей, аргументах, которые нужно им передать, и о том, как интерпретировать результаты. клиент (client):: Приложение, отвечающее за инициирование запроса на аутентификацию от имени аппликанта и получающее от него необходимую для аутентификации информацию. подсистема (facility):: Одна из четырех основных групп функциональности, которые дает PAM: аутентификация, управление учетными записями, управление сеансом и обновление ключом аутентификации. модуль (module):: Набор из одной или большего количества связанных функций, реализующих определенную подсистему аутентификации, собранный в один (обычно динамически загружаемый) двоичный файл, идентифицируемый по имени. политика (policy):: Полный набор конфигурационных деклараций, описывающих, как обрабатывать запросы PAM к определенной услуге. Политика обычно состоит из четырех цепочек, по одной для каждой подсистемы, хотя некоторые службы используют не все четыре подсистемы. сервер (server):: Приложение, выступающее от имени арбитратора для общения с клиентом, запрашивания аутентификационной информации, проверки полномочий аппликанта и подтверждающее или отклоняющее запрос. сервис (service):: Класс серверов, предоставляющих похожую или связанную функциональность, и требующую подобную аутентификацию. Политики PAM задаются на основе сервисов, так что ко всем серверам, объявляющим одно и тоже имя сервиса, будет применяться одна и та же политика. сеанс (session):: Контекст, в котором сервис оказывается аппликанту сервером. Одна из четырех подсистем PAM, управление сеансом, касается исключительно настройке и очистке этого контекста. ключ (token):: Блок информации, связанный с учётной записью, например, пароль или ключевая фраза, которую аппликант должен предоставить для своей идентификации. транзакция (transaction):: Последовательность запросов от одного и того же аппликанта к одному и тому же экземпляру того же самого сервера, начиная с аутентификации и установления сеанса и заканчивая закрытием сеанса. [[pam-usage-examples]] == Примеры использования Этот раздел предназначен для иллюстрации значений некоторых терминов, определенных выше, при помощи простых примеров. == Объединенные клиент и сервер В этом простом примере показывается пользователь `alice`, выполняющий команду man:su[1] для того, чтобы стать пользователем `root`. [source,shell] .... % 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 .... * Аппликантом является `alice`. * Учетной записью является `root`. * Процесс man:su[1] является как клиентом, так и сервером. * Аутентификационным ключом является `xi3kiune`. * Арбитратором выступает `root`, и именно поэтому у команды man:su[1] выставлен бит выполнения с правами `root`. == Клиент и сервер разделены В примере ниже рассматривается пользователь `eve`, пытающийся установить man:ssh[1]-соединение с `login.example.com`, и успешно входя как пользователь `bob`. Боб должен был выбрать пароль получше! [source,shell] .... % 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! % % .... * Аппликантом является `eve`. * Клиентом является процесс man:ssh[1] пользователя Eve. * Сервером является процесс man:sshd[8] на машине `login.example.com` * Учетной записью является `bob`. * Ключом аутентификации является `god`. * Хотя этого не видно в примере, но арбитратором является `root`. == Пример политики Следующее является политикой, используемой во FreeBSD по умолчанию для `sshd`: [.programlisting] .... 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 .... * Эта политика применяется к службе `sshd` (что не обязательно ограничено сервером man:sshd[8]). * `auth`, `account`, `session` и `password` являются подсистемами. * [.filename]#pam_nologin.so#, [.filename]#pam_unix.so#, [.filename]#pam_login_access.so#, [.filename]#pam_lastlog.so# и [.filename]#pam_permit.so# являются модулями. Из этого примера видно, что [.filename]#pam_unix.so# реализует по крайней мере две подсистемы (аутентификацию и управление учётными записями). [[pam-essentials]] == Основы PAM [[pam-facilities-primitives]] == Подсистемы и примитивы API для PAM предоставляет шесть различных примитивов для аутентификации, сгруппированных в четыре подсистемы, каждая из которых описывается ниже. `auth`:: _Аутентификация._ Эта подсистема, собственно говоря, реализует аутентификацию аппликанта и выяснение полномочий учётной записи. Она предоставляет два примитива: ** Функция man:pam_authenticate[3] аутентифицирует аппликанта, обычно запрашивая аутентификационный ключ и сравнивая его со значением, хранящимся в базе данных или получаемым от сервера аутентификации. ** Функция man:pam_setcred[3] устанавливает полномочия учётной записи, такие, как идентификатор пользователя, членство в группах и ограничения на использование ресурсов. `account`:: _Управление учётной записью._ Эта подсистема обрабатывает вопросы доступности учетной записи, не связанные с аутентификацией, такие, как ограничения в доступе на основе времени суток или загрузки сервера. Он предоставляет единственный примитив: ** Функция man:pam_acct_mgmt[3] проверяет, доступна ли запрашиваемая учётная запись. `session`:: _Управление сеансом._ Эта подсистема отрабатывает задачи, связанные с установлением и закрытием сеанса, такие, как учет входов пользователей. Она предоставляет два примитива: ** Функция man:pam_open_session[3] выполняет действия, связанные с установлением сеанса: добавление записей в базы данных [.filename]#utmp# и [.filename]#wtmp#, запуск агента SSH и так далее. ** Функция man:pam_close_session[3] выполняет действия, связанные с закрытием сеанса: добавление записей в базы данных [.filename]#utmp# и [.filename]#wtmp#, завершение работы агента SSH и так далее. `password`:: _Управление паролем._ Эта подсистема используется для изменения ключа аутентификации, связанного с учетной записью, по причине истечения его срока действия или желания пользователя изменить его. Она предоставляет единственный примитив: ** Функция man:pam_chauthtok[3] изменяет ключ аутентификации, опционально проверяя, что он труден для подбора, не использовался ранее и так далее. [[pam-modules]] == Модули Модули являются центральной концепцией в PAM; в конце концов, им соответствует буква "M" в сокращении "PAM". Модуль PAM представляет собой самодостаточный кусок программного кода, который реализует примитивы одной или большего количества подсистем одного конкретного механизма; к возможным механизмам для подсистемы аутентификации, к примеру, относятся базы данных паролей UNIX(R), системы NIS, LDAP или Radius. [[pam-module-naming]] == Именование модулей Во FreeBSD каждый механизм реализуется в отдельном модуле с именем `pam_mechanism.so` (например, `pam_unix.so` для механизма UNIX(R).) В других реализациях иногда отдельные модули используются для разных подсистем, и в их имя включается, кроме названия механизма, и имя подсистемы. К примеру, в Solaris(TM) имеется модуль `pam_dial_auth.so.1`, который часто используется для аутентификации пользователей, работающих по коммутируемым каналам связи. [[pam-module-versioning]] == Версии модулей Изначальная реализация PAM во FreeBSD, которая была основана на Linux-PAM, не использовала номера версий для модулей PAM. Это будет приводить к проблемам при работе унаследованных приложений, которые могут быть скомпонованы со старыми версиями системных библиотек, так как способа подгрузить соответствующую версию требуемых модулей нет. OpenPAM, с другой стороны, ищет модули, которые имеют тот же самый номер версии, что и библиотека PAM (на данный момент 2), и использует модуль без версии, только если модуль с известной версией не был загружен. Поэтому для старых приложений могут предоставляться старые модули, при этом новые (или заново построенные) приложения будут использовать все возможности последних версий модулей. Хотя модули PAM в Solaris(TM) имеют номер версии, по-настоящему номер версии в них не отслеживается, потому что номер является частью имени и должен включаться в конфигурацию. [[pam-chains-policies]] == Цепочки и политики Когда сервер инициирует PAM-транзакцию, библиотека PAM пытается загрузить политику для службы, указанной при вызове функции man:pam_start[3]. Политика определяет, как должны обрабатываться запросы на аутентификацию, и задаётся в конфигурационном файле. Это составляет другую основополагающую концепцию PAM: возможность администратору настраивать политику безопасности системы (в самом широком её понимании) простым редактированием текстового файла. Политика состоит из четырёх цепочек, по одной на каждый из методов PAM. Каждое звено представляет собой последовательность конфигурационных утверждений, задающих вызываемый модуль, некоторые (необязательные) параметры для передачи в модуль, и управляющий флаг, описывающий, как интерпретировать возвращаемый из модуля код. Понимание смысла управляющего флага необходимо для понимания конфигурационных файлов PAM. Существуют четыре различных управляющих флага: `binding`:: Если модуль отработал успешно, и ни один из предыдущих модулей в цепочке не сработал отрицательно, то цепочка прерывается, а запрос подтверждается. Если же модуль отработает неудачно, то выполняется оставшаяся часть цепочки, однако запрос отвергается. + Этот управляющий флаг был добавлен компанией Sun в Solaris(TM) 9 (SunOS(TM) 5.9), и поддерживается в OpenPAM. `required`:: Если модуль возвратил положительный ответ, выполняется оставшаяся часть цепочки, запрос удовлетворяется, если никакой другой модуль не отработает отрицательно. Если же модуль возвратит отрицательный ответ, остаток цепочки тоже отрабатывается, но запрос отвергается. `requisite`:: Если модуль возвращает положительный ответ, выполняется оставшаяся часть цепочки, запрос удовлетворяется, если никакой другой модуль не отработает отрицательно. Если же модуль отрабатывает отрицательно, то отработка цепочки немедленно прекращается, а запрос отвергается. `sufficient`:: Если модуль возвратит положительный ответ, и ни один из предыдущих модулей в цепочке на отработал отрицательно, то отработка цепочки немедленно прекращается, а запрос удовлетворяется. Если модуль отработал отрицательно, то результат игнорируется и цепочка отрабатывается дальше. + Так как семантика этого флага может оказаться запутанной, особенно при его использовании с последним модулем в цепочке, рекомендуется вместо него использовать управляющий флаг `binding`, если реализация его поддерживает. `optional`:: Модуль отрабатывается, но результат выполнения игнорируется. Если все модули в цепочке помечены как `optional`, то удовлетворяться будут все запросы. Когда сервер вызывает один из шести PAM-примитивов, PAM запрашивает цепочку подсистемы, к которой принадлежит примитив, и запускает каждый модуль, перечисленный в цепочке в порядке их перечисления, пока список не будет исчерпан либо не будет определено, что дальнейшей обработки не нужно (по причине достижение модуля, вернувшего положительный ответ при условии `binding` или `sufficient`, либо отрицательный с условием `requisite`). Запрос подтверждается, если только был вызван по крайней мере один модуль, и все неопциональные модули вернули положительный ответ. Заметьте, что возможно, хотя это не распространено, перечислять один и тот же модуль несколько раз в одной цепочке. К примеру, модуль, просматривающий имена и пароли пользователя в сервере каталога может быть вызван несколько раз с различными параметрами, задающими различные серверы каталогов для связи. PAM считает различные появления одного модуля в той же самой цепочке разными и не связанными модулями. [[pam-transactions]] == Транзакции Жизненный цикл типичной PAM-транзакции описан ниже. Заметьте, что в случае, если любой из перечисленных шагов оканчивается неудачно, сервер должен выдать клиенту соответствующее сообщение об ошибке и прервать транзакцию. . Если это необходимо, сервер получает полномочия арбитратора через независимый от PAM механизм-чаще всего по факту запуска пользователем `root` или с установленным setuid-битом `root`. . Сервер вызывает функцию man:pam_start[3] для инициализации библиотеки PAM и задания имени сервиса и целевой учётной записи, а также регистрации подходящего способа общения. . Сервер получает различную информацию, относящуюся к транзакции (такую, как имя пользователя аппликанта и имя хоста, на котором запущен клиент), и отправляет её в PAM при помощи функции man:pam_set_item[3]. . Сервер вызывает функцию man:pam_authenticate[3] для аутентификации аппликанта. . Сервер вызывает функцию man:pam_acct_mgmt[3] для проверки того, что запрошенная учётная запись доступна и корректна. Если пароль верен, но его срок истёк, man:pam_acct_mgmt[3] возвратит результат `PAM_NEW_AUTHTOK_REQD`, а не `PAM_SUCCESS`. . Если на предыдущем шаге был получен результат `PAM_NEW_AUTHTOK_REQD`, то сервер вызывает функцию man:pam_chauthtok[3] для того, чтобы вынудить клиента изменить ключ аутентификации для запрошенной учётной записи. . Теперь, когда аппликант полностью аутентифицирован, сервер вызывает функцию man:pam_setcred[3] для получения полномочий запрошенной учётной записи. Сделать это возможно, потому что он работает как арбитратор, и оставляет за собой полномочия арбитратора. . После получения необходимых полномочий, сервер вызывает функцию man:pam_open_session[3] для установления сеанса. . Теперь сервер выполняет тот сервис, который затребовал клиент-например, предоставляет аппликанту оболочку. . После того, как сервер закончил обслуживание клиента, он вызывает функцию man:pam_close_session[3] для закрытия сеанса. . Наконец, сервер вызывает функцию man:pam_end[3] для оповещения библиотеки PAM о том, что работа с ней завершена и какие-либо выделенные в течение сеанса ресурсы можно освободить. [[pam-config]] == Настройка PAM [[pam-config-file]] == Файлы политик PAM [[pam-config-pam.conf]] == Файл [.filename]#/etc/pam.conf# Традиционно файлом политик PAM является [.filename]#/etc/pam.conf#. Он содержит все политики PAM для вашей системы. Каждая строка файла описывает один шаг в цепочке, как показано ниже: [.programlisting] .... login auth required pam_nologin.so no_warn .... Поля следуют в таком порядке: имя службы, имя подсистемы, управляющий флаг, имя модуля и параметры модуля. Любые дополнительные поля интерпретируются как дополнительные параметры модуля. Для каждой пары сервис/подсистема составляется отдельная цепочка, и тогда получается, что, хотя порядок следования строк для одной и той же услуги и подсистемы является значимым, порядок перечисления отдельных сервисов не значим. В примерах из оригинальной работы по PAM строки конфигурации сгруппированы по подсистемам, в поставляемом с Solaris(TM) файле [.filename]#pam.conf# именно так и сделано, но в стандартном конфигурационном файле из поставки FreeBSD строки настроек сгруппированы по сервисам. Подходит любой из этих способов; они имеют один и тот же смысл. [[pam-config-pam.d]] == Каталог [.filename]#/etc/pam.d# OpenPAM и Linux-PAM поддерживают альтернативный механизм настройки, который для FreeBSD является предпочтительным. В этой схеме каждая политика содержится в отдельном файле с именем, соответствующем сервису, к которому она применяется. Эти файлы размещаются в каталоге [.filename]#/etc/pam.d/#. Такие файлы политик, ориентированные на сервисы, имеют только четыре поля, вместо пяти полей в файле [.filename]#pam.conf#: поле имени сервиса опущено. Таким образом, вместо примера строки файла [.filename]#pam.conf# из предыдущего раздела получится следующая строка в файле [.filename]#/etc/pam.d/login#: [.programlisting] .... auth required pam_nologin.so no_warn .... Как следствие такого упрощённого синтаксиса, возможно использование одних и тех же политик для нескольких сервисов, связывая каждое имя сервиса с тем же самым файлом политик. К примеру, для использования той же самой политики для сервисов `su` и `sudo`, можно сделать следующее: [source,shell] .... # cd /etc/pam.d # ln -s su sudo .... Это работает, потому что имя сервиса определяется именем файла, а не его указанием в файле политики, так что один и тот же файл может использоваться для нескольких сервисов с разными названиями. Так как политика каждого сервиса хранится в отдельном файле, то механизм [.filename]#pam.d# делает установку дополнительных политик для программных пакетов сторонних разработчиков очень лёгкой задачей. [[pam-config-file-order]] == Порядок поиска политик Как вы видели выше, политики PAM могут находиться в нескольких местах. Что будет, если политики для одного и того же сервиса имеются в разных местах? Необходимо осознать, что система конфигурации PAM ориентирована на цепочки. [[pam-config-breakdown]] == Структура строки настройки Как это объяснено в <>, каждая строка файла [.filename]#/etc/pam.conf# состоит из четырёх или большего количества полей: имени сервиса, имени подсистемы, управляющего флага, имени модуля и дополнительных параметров модуля, которые могут отсутствовать. Имя сервиса обычно (хотя не всегда) является именем приложения, которое этот сервис обслуживает. Если вы не уверены, обратитесь к документации по конкретному приложению для определения используемого имени сервиса. Заметьте, что если вы используете [.filename]#/etc/pam.d/# вместо [.filename]#/etc/pam.conf#, то имя сервиса задается именем файла политики, и опускается из строк настройки, которые в таком случае начинаются с названия подсистемы. Имя подсистемы представляет собой одно из четырёх ключевых слов, описанных в <>. Точно также управляющий флаг является одним из четырёх ключевых слов, описанных в <>, в котором рассказано, как интерпретировать возвращаемый из модуля код. В Linux-PAM поддерживается альтернативный синтаксис, который позволяет указать действие, связанной с каждый возможным кодом возврата, но этого следует избегать, так как он не является стандартным и тесно связан со способом диспетчеризации вызовов сервисов в Linux-PAM (а он значительно отличается от способа взаимодействия в Solaris(TM) и OpenPAM). Не вызывает удивления тот факт, что в OpenPAM этот синтаксис не поддерживается. [[pam-policies]] == Политики Для корректной настройки PAM необходимо понимать, как происходит интерпретация политик. В момент, когда приложение вызывает функцию man:pam_start[3], библиотека PAM загружает политику для указанного сервиса и выстраивает четыре цепочки модулей (по одной для каждой подсистемы). Если одна или большее количество этих цепочек являются пустыми, то будут выполняться подстановки соответствующих цепочек из политики для сервиса `other`. Когда затем приложение вызывает одну из шести примитивов PAM, библиотека PAM выделяет из цепочки нужную подсистему и вызывает функцию, соответствующую сервису, в каждом модуле, перечисленном в цепочке, в том порядке, в каком они перечислены в конфигурации. После каждого обращения к функции сервиса, тип модуля и возвращённый из этой функции код результата выполнения используются для того, что делать дальше. За некоторыми исключениями, которые будут описаны ниже, применяется такая таблица: .Сводная таблица отработки цепочек PAM [cols="1,1,1,1", options="header"] |=== | | PAM_SUCCESS | PAM_IGNORE | other |binding |if (!fail) break; |- |fail = true; |required |- |- |fail = true; |requisite |- |- |fail = true; break; |sufficient |if (!fail) break; |- |- |optional |- |- |- |=== Если переменная `fail` принимает истинное значение в конце отработки цепочки, или когда достигнут "break", диспетчер возвращает код ошибки, возвращённый первым модулем, отработавшим неудачно. В противном случае возвращается `PAM_SUCCESS`. Первым исключением является то, что код ошибки `PAM_NEW_AUTHTOK_REQD` интерпретируется как успешный результат, кроме случая, когда модуль отработал успешно, и по крайней мере один модуль возвратил `PAM_NEW_AUTHTOK_REQD`, тогда диспетчер возвратит результат `PAM_NEW_AUTHTOK_REQD`. Вторым исключением является то, что man:pam_setcred[3] считает, что модули `binding` и `sufficient` являются равнозначными `required`. Третьим и последним исключением является то, что функция man:pam_chauthtok[3] отрабатывает полную цепочку дважды (один раз для предварительных проверок, и ещё раз для реального задания пароля), и на подготовительной фазе она считает, что модули `binding` и `sufficient` являются равнозначными `required`. [[pam-freebsd-modules]] == Модули PAM во FreeBSD [[pam-modules-deny]] === man:pam_deny[8] Модуль man:pam_deny[8] является одним из простейших доступных модулей; на любой запрос он возвращает результат `PAM_AUTH_ERR`. Он полезен для быстрого отключения сервиса (добавьте его на верх каждой цепочки) или завершения цепочек модулей `sufficient`. [[pam-modules-echo]] === man:pam_echo[8] Модуль man:pam_echo[8] просто передаёт свои параметры в функцию взаимодействия как сообщение `PAM_TEXT_INFO`. В основном полезна для отладки, но также может использоваться для вывода сообщений, таких как "Unauthorized access will be prosecuted" до запуска процедуры аутентификации. [[pam-modules-exec]] === man:pam_exec[8] Модуль man:pam_exec[8] воспринимает первый переданный ему параметр как имя программы для выполнения, а остальные аргументы передаются этой программе в качестве параметров командной строки. Одним из возможных применений является его использование для запуска в момент регистрации в системе программы монтирования домашнего каталога пользователя. [[pam-modules-ftpusers]] === man:pam_ftpusers[8] Модуль man:pam_ftpusers[8] [[pam-modules-group]] === man:pam_group[8] Модуль man:pam_group[8] принимает или отвергает аппликантов в зависимости от их членства в определённой файловой группе (обычно `wheel` для man:su[1]). В первую очередь предназначен для сохранения традиционного поведения утилиты BSD man:su[1], хотя имеет и много других применений, таких как отключение определённых групп пользователей от некоторого сервиса. [[pam-modules-guest]] === man:pam_guest[8] Модуль man:pam_guest[8] позволяет осуществлять гостевые входы с использованием фиксированных имён входа в систему. На пароль могут накладываться различные ограничения, однако действием по умолчанию является ввод любого пароля при использовании имени, соответствующего гостевому входу. Модуль man:pam_guest[8] можно легко использовать для реализации анонимных входов на FTP. [[pam-modules-krb5]] === man:pam_krb5[8] Модуль man:pam_krb5[8] [[pam-modules-ksu]] === man:pam_ksu[8] Модуль man:pam_ksu[8] [[pam-modules-lastlog]] === man:pam_lastlog[8] Модуль man:pam_lastlog[8] [[pam-modules-login-access]] === man:pam_login_access[8] Модуль man:pam_login_access[8] предоставляет реализацию примитива для управления учётными записями, который вводит в действие ограничения на вход, задаваемые в таблице man:login.access[5]. [[pam-modules-nologin]] === man:pam_nologin[8] Модуль man:pam_nologin[8] отвергает любые входы не пользователем root, если существует файл [.filename]#/var/run/nologin#. Обычно этот файл создаётся утилитой man:shutdown[8], когда до запланированного завершения работы системы остаётся менее пяти минут. [[pam-modules-opie]] === man:pam_opie[8] Модуль man:pam_opie[8] реализует метод аутентификации man:opie[4]. Система man:opie[4] является механизмом работы по схеме запрос-ответ, при котором ответ на каждый запрос является прямой функцией от запроса и ключевой фразы, так что ответ может быть легко и "вовремя" вычислен любым, знающим ключевую фразу, что избавляет от необходимости передавать пароль. Кроме того, так как в man:opie[4] никогда повторно не используется запрос, ответ на который был корректно получен, эта схема является устойчивой к атакам, основанным на повторе действий. [[pam-modules-opieaccess]] === man:pam_opieaccess[8] Модуль man:pam_opieaccess[8] дополняет модуль man:pam_opie[8]. Его работа заключается в выполнении ограничений, задаваемых файлом man:opieaccess[5], который определяет условия, при которых пользователь, нормально прошедший аутентификацию посредством man:opie[4], может использовать альтернативные методы. Чаще всего он используется для запрета использования аутентификации на основе паролей с непроверенных хостов. Для эффективности модуль man:pam_opieaccess[8] должен быть определён в цепочке `auth` как `requisite` сразу же после записи `sufficient` для man:pam_opie[8], но перед любыми другими модулями. [[pam-modules-passwdqc]] === man:pam_passwdqc[8] Модуль man:pam_passwdqc[8] [[pam-modules-permit]] === man:pam_permit[8] Модуль man:pam_permit[8] является одним из самых простым из имеющихся; на любой запрос он отвечает `PAM_SUCCESS`. Он полезен в качестве замены пустого места для сервисов, когда одна или большее количество цепочек в противном случае останутся пустыми. [[pam-modules-radius]] === man:pam_radius[8] Модуль man:pam_radius[8] [[pam-modules-rhosts]] === man:pam_rhosts[8] Модуль man:pam_rhosts[8] [[pam-modules-rootok]] === man:pam_rootok[8] Модуль man:pam_rootok[8] возвращает положительный результат в том и только в том случае, если реальный id пользователя процесса, его вызвавшего (предполагается, что его запускает аппликант) равен 0. Это полезно для несетевых сервисов, таких как man:su[1] или man:passwd[1], к которым пользователь `root` должен иметь автоматический доступ. [[pam-modules-securetty]] === man:pam_securetty[8] Модуль man:pam_securetty[8] [[pam-modules-self]] === man:pam_self[8] Модуль man:pam_self[8] возвращает положительный результат тогда и только тогда, когда имена аппликанта соответствуют целевой учётной записи. Больше всего это пригодится в несетевых сервисах, таких как man:su[1], в которых идентификация аппликанта может быть с лёгкостью проверена. [[pam-modules-ssh]] === man:pam_ssh[8] Модуль man:pam_ssh[8] предоставляет как сервис аутентификации, так и сеанса. Сервис аутентификации позволяет пользователям, имеющим секретные ключи SSH, защищённые паролями, в своих каталогах [.filename]#~/.ssh#, аутентифицироваться посредством этих паролей. Сеансовый сервис запускает man:ssh-agent[1] и загружает ключи, которые были расшифрованы на фазе аутентификации. Такая возможность, в частности, полезна для локальных входов в систему, как в систему X (посредством man:xdm[1] или другого X-менеджера входов, умеющего работать с PAM), так и на консоль. [[pam-modules-tacplus]] === man:pam_tacplus[8] Модуль man:pam_tacplus[8] [[pam-modules-unix]] === man:pam_unix[8] Модуль man:pam_unix[8] реализует традиционную аутентификацию UNIX(R) на основе паролей, использующую функцию man:getpwnam[3] для получения пароля целевой учётной записи и сравнивающую её с тем, что представил аппликант. Он также предоставляет средства управления учётными записями (отслеживая время действия учётной записи и пароля) и смены паролей. Наверное, это самый полезный модуль, так как подавляющее большинство администраторов хотят сохранить исторически сложившееся поведение по крайней мере некоторых сервисов. [[pam-appl-prog]] == Программирование приложений с PAM Этот раздел ещё не написан. [[pam-module-prog]] == Программирование модуля PAM Этот раздел ещё не написан. :sectnums!: [appendix] [[pam-sample-appl]] == Пример PAM-приложения Далее следует минимальная реализация программы man:su[1] с использованием PAM. Заметьте, что в ней используется специфичная для OpenPAM функция взаимодействия man:openpam_ttyconv[3], объявление которой расположено в файле [.filename]#security/openpam.h#. Если вы собираетесь строить это приложение в системе с другой библиотекой PAM, вам необходимо будет создать собственную функцию взаимодействия. Надёжную функцию взаимодействия неожиданно трудно написать; та, что находится в <>, хороша в качестве отправной точки, но в реальных приложениях использоваться не может. [.programlisting] .... include::static/source/articles/pam/su.c[] .... :sectnums!: [appendix] [[pam-sample-module]] == Пример PAM-модуля Далее приведена минимальная реализация man:pam_unix[8], предоставляющая только сервисы аутентификации. Она должна строиться и работать с большинством из реализаций PAM, но использует возможности расширений OpenPAM, если они присутствуют: отметьте использование функции man:pam_get_authtok[3], которая кардинально упрощает организацию ввода пароля пользователем. [.programlisting] .... include::static/source/articles/pam/pam_unix.c[] .... :sectnums!: [appendix] [[pam-sample-conv]] == Пример функции взаимодействия PAM Функция взаимодействия, приводимая ниже, является значительно упрощённой версией функции man:openpam_ttyconv[3] из OpenPAM. Она полнофункциональна, и должна послужить источником идей о том, как должна себя вести функция взаимодействия, однако она слишком проста для реальных приложений. Даже если вы не используете OpenPAM, можете сгрузить исходный код и использовать man:openpam_ttyconv[3] в своих целях; мы надеемся, что она достаточно надёжна в качестве функции для взаимодействия с терминальными устройствами. [.programlisting] .... include::static/source/articles/pam/converse.c[] .... :sectnums!: [[pam-further]] == Lectures complémentaires === Publications _link:http://www.sun.com/software/solaris/pam/pam.external.pdf[Rendre les services de connexion indépendants des technologies d'authentification]_. Vipin Samar et Charlie Lai. Sun Microsystems. _link:http://www.opengroup.org/pubs/catalog/p702.htm[X/Open Single Sign-on Preliminary Specification]_. The Open Group. 1-85912-144-6. June 1997. _link:http://www.kernel.org/pub/linux/libs/pam/pre/doc/current-draft.txt[Pluggable Authentication Modules]_. Andrew G. Morgan. 1999-10-06. === Guides utilisateur _link:http://www.sun.com/software/solaris/pam/pam.admin.pdf[Administration de PAM]_. Sun Microsystems. === Page internet liées _link:http://openpam.sourceforge.net/[La page d'OpenPAM]_. Dag-Erling Smørgrav. ThinkSec AS. _link:http://www.kernel.org/pub/linux/libs/pam/[La page de Linux-PAM]_. Andrew G. Morgan. _link:http://wwws.sun.com/software/solaris/pam/[La page de Solaris PAM]_. Sun Microsystems.