Documentation
¶
Overview ¶
Package pamtester verifies and changes users' login passwords through the operating system's native authentication stack, without cgo:
- Linux: Linux-PAM (libpam.so.0), called via purego.
- macOS: OpenPAM (libpam.2.dylib), called via purego.
- Windows: LogonUserW / NetUserChangePassword (no PAM involved).
- FreeBSD: OpenPAM (libpam.so.6), called via purego; cgo builds only.
Other platforms, or builds with the nopamtester tag, get a stub whose Start returns errors.ErrUnsupported.
The core type is Transaction, which corresponds to one PAM transaction (pam_start .. pam_end). Authenticate, AcctMgmt and ChangeAuthTok are its methods; failures wrap an Error, so they can be classified with errors.Is identically on every platform.
How it works:
Commands like login, su, sudo, and passwd all authenticate passwords
through PAM (Pluggable Authentication Modules). The flow is:
1. pam_start() Opens a PAM transaction and registers a
conversation callback function.
2. pam_authenticate() PAM internally uses modules like pam_unix.so,
which call back into the registered conversation
function to request the password. We supply the
password string to be verified in that callback.
3. pam_acct_mgmt() Checks account validity (expired, locked, ...).
4. pam_end() Closes the transaction.
The actual password comparison (reading /etc/shadow and hashing) is done by
pam_unix.so. Non-root processes can verify their own password: when
pam_unix lacks permission to read /etc/shadow directly, it delegates to
the setuid-root unix_chkpwd helper. unix_chkpwd refuses to check other
users' passwords, so verifying arbitrary accounts requires root.
Concurrency and blocking:
Start, Authenticate, AcctMgmt, ChangeAuthTok and the *Conv variants are synchronous foreign calls. Each blocks the calling goroutine and pins its OS thread until PAM (or Win32) returns, and the Go runtime starts extra threads to keep other goroutines running. A server that authenticates many clients at once therefore uses one OS thread per in-flight call; bound the concurrency (e.g. with a semaphore) instead of spawning a goroutine per request without limit.
Calls can take long. pam_unix and pam_faildelay delay a failed attempt by about two seconds as brute-force protection, so a wrong password makes Authenticate slow by design; modules backed by the network (sssd, LDAP, Kerberos, RADIUS) wait for their own timeouts.
PAM calls cannot be cancelled: there is no context.Context support, because libpam offers no way to interrupt a module. A caller can stop waiting by running the call in a goroutine and selecting on a timer, but the call keeps running on its thread, and the Transaction stays locked — Close and further methods block — until it returns.
A Transaction may be used from several goroutines; its methods serialize on an internal mutex. Separate Transactions run in parallel. Linux-PAM and OpenPAM themselves are fine with that, but individual modules need not be thread-safe (older or third-party modules may use non-reentrant libc calls or shared state); if a stack includes such modules, serialize all calls through one mutex in the application.
Index ¶
- Variables
- type ConvFunc
- type Error
- type Options
- type Style
- type Transaction
- func (t *Transaction) AcctMgmt() error
- func (t *Transaction) Authenticate(password string) error
- func (t *Transaction) AuthenticateConv(conv ConvFunc) error
- func (t *Transaction) ChangeAuthTok(oldPassword, newPassword string) error
- func (t *Transaction) ChangeAuthTokConv(conv ConvFunc) error
- func (t *Transaction) Close() error
- func (t *Transaction) Messages() []string
- func (t *Transaction) User() (string, error)
Constants ¶
This section is empty.
Variables ¶
var PamService = "passwd"
PamService is the default PAM service configuration file under /etc/pam.d/, used when Options.Service is empty.
On many distributions /etc/pam.d/passwd only defines a "password" stack. Authenticate and AcctMgmt then work only because Linux-PAM falls back, per module type, to /etc/pam.d/other — on Debian/Ubuntu that includes common-auth/common-account, but distributions whose "other" stack is pam_deny reject every authentication. Services that mainly verify passwords should set Options.Service to a stack with an "auth" section (e.g. "login", "system-auth", or a dedicated file for the application).
Functions ¶
This section is empty.
Types ¶
type ConvFunc ¶
ConvFunc answers one PAM conversation message. For PromptEchoOff and PromptEchoOn the returned string is sent to the module; for ErrorMsg and TextInfo it is ignored. Returning an error aborts the PAM call: it then fails with ErrConv (or the module's own code), and the returned error also wraps the ConvFunc's error, so errors.Is works with either.
A ConvFunc is called synchronously from within the PAM call on the caller's goroutine, so it may block, e.g. to ask an interactive user.
type Error ¶
type Error int32
Error is a PAM return code (from <security/_pam_types.h>) as a Go error. Errors returned by this package wrap an Error, so callers can classify failures with errors.Is:
if errors.Is(err, pamtester.ErrAuth) { ... wrong password ... }
const ( ErrOpen Error = 1 // PAM_OPEN_ERR ErrSymbol Error = 2 // PAM_SYMBOL_ERR ErrService Error = 3 // PAM_SERVICE_ERR ErrSystem Error = 4 // PAM_SYSTEM_ERR ErrBuf Error = 5 // PAM_BUF_ERR ErrPermDenied Error = 6 // PAM_PERM_DENIED ErrAuth Error = 7 // PAM_AUTH_ERR — wrong password ErrCredInsufficient Error = 8 // PAM_CRED_INSUFFICIENT ErrUserUnknown Error = 10 // PAM_USER_UNKNOWN ErrMaxTries Error = 11 // PAM_MAXTRIES ErrNewAuthTokReqd Error = 12 // PAM_NEW_AUTHTOK_REQD — password correct but expired, must be changed ErrAcctExpired Error = 13 // PAM_ACCT_EXPIRED ErrSession Error = 14 // PAM_SESSION_ERR ErrCredExpired Error = 16 // PAM_CRED_EXPIRED ErrCred Error = 17 // PAM_CRED_ERR ErrNoModuleData Error = 18 // PAM_NO_MODULE_DATA ErrConv Error = 19 // PAM_CONV_ERR ErrAuthTok Error = 20 // PAM_AUTHTOK_ERR ErrAuthTokRecovery Error = 21 // PAM_AUTHTOK_RECOVERY_ERR — e.g. wrong old password in ChangeAuthTok ErrAuthTokLockBusy Error = 22 // PAM_AUTHTOK_LOCK_BUSY ErrAuthTokDisableAging Error = 23 // PAM_AUTHTOK_DISABLE_AGING ErrTryAgain Error = 24 // PAM_TRY_AGAIN ErrIgnore Error = 25 // PAM_IGNORE ErrAbort Error = 26 // PAM_ABORT ErrAuthTokExpired Error = 27 // PAM_AUTHTOK_EXPIRED ErrModuleUnknown Error = 28 // PAM_MODULE_UNKNOWN ErrBadItem Error = 29 // PAM_BAD_ITEM ErrConvAgain Error = 30 // PAM_CONV_AGAIN ErrIncomplete Error = 31 // PAM_INCOMPLETE )
PAM return codes (Linux-PAM numbering).
type Options ¶
type Options struct {
// Service selects the PAM service file under /etc/pam.d/.
// Empty means the package-level default PamService.
Service string
// RHost, if non-empty, is set as PAM_RHOST — the remote host the request
// originates from. Services performing authentication on behalf of remote
// clients should set this so that modules like pam_faillock/pam_access
// and audit logs record the real source.
RHost string
// TTY, if non-empty, is set as PAM_TTY.
TTY string
// RUser, if non-empty, is set as PAM_RUSER — the requesting user.
RUser string
// AllowNullAuthTok lets Authenticate accept an empty password for
// accounts that have none. By default an empty password is rejected
// with ErrAuth before PAM is consulted, and PAM_DISALLOW_NULL_AUTHTOK is
// passed to pam_authenticate and pam_acct_mgmt — many stacks (Debian's
// common-auth, macOS checkpw) carry "nullok", which would otherwise let
// anyone log in to a password-less account with "".
AllowNullAuthTok bool
}
Options carries optional parameters for Start. The zero value is valid.
type Style ¶
type Style int
Style is the kind of a PAM conversation message passed to a ConvFunc.
const ( PromptEchoOff Style = 1 // ask for secret input, e.g. "Password: " PromptEchoOn Style = 2 // ask for visible input, e.g. a username or OTP ErrorMsg Style = 3 // error message; the reply is ignored TextInfo Style = 4 // informational message; the reply is ignored )
Conversation message styles (same values in Linux-PAM and OpenPAM).
type Transaction ¶
type Transaction struct {
// contains filtered or unexported fields
}
Transaction represents one PAM transaction, i.e. a pam_start .. pam_end lifetime. Obtain one with Start, and always Close it. A Transaction is safe for sequential use; its methods serialize via an internal mutex.
func Start ¶
func Start(user string, opts *Options) (*Transaction, error)
Start opens a PAM transaction for user. If user is empty the current process user is used. opts may be nil. The caller must Close the returned Transaction.
func (*Transaction) AcctMgmt ¶
func (t *Transaction) AcctMgmt() error
AcctMgmt runs pam_acct_mgmt: it checks that the account is valid — not expired or locked, and access not denied by modules like pam_access or pam_time. A special case is an error matching ErrNewAuthTokReqd: the account is fine but the password has expired and must be changed (e.g. via ChangeAuthTok).
func (*Transaction) Authenticate ¶
func (t *Transaction) Authenticate(password string) error
Authenticate verifies password via pam_authenticate. Returns nil if the password is correct; a wrong password yields an error matching ErrAuth (use errors.Is).
Regardless of what the PAM module asks (typically "Password:"), the conversation responds uniformly with the given password. On macOS the password is additionally pre-set as the PAM_AUTHTOK item: verification stacks like the default "checkpw" service pass use_first_pass to pam_opendirectory, which only reads that item and fails without ever calling the conversation. (OpenPAM, unlike Linux-PAM, allows applications to set PAM_AUTHTOK.)
An empty password is rejected with ErrAuth unless Options.AllowNullAuthTok is set.
Note that Authenticate only proves the password is right — call AcctMgmt afterwards to check that the account itself is still usable.
func (*Transaction) AuthenticateConv ¶
func (t *Transaction) AuthenticateConv(conv ConvFunc) error
AuthenticateConv runs pam_authenticate with conv answering every conversation message, for stacks that ask more than a single password — e.g. a password followed by an OTP, or a username prompt. Error and info messages are passed to conv as well, and are also kept for Messages.
Unlike Authenticate, nothing is pre-set as PAM_AUTHTOK, so on macOS use a service whose modules prompt (not the default "checkpw", whose pam_opendirectory runs with use_first_pass). PAM_DISALLOW_NULL_AUTHTOK is still passed unless Options.AllowNullAuthTok is set.
func (*Transaction) ChangeAuthTok ¶
func (t *Transaction) ChangeAuthTok(oldPassword, newPassword string) error
ChangeAuthTok changes the user's password via pam_chauthtok. Each prompt is classified by passwordPromptIsNew: prompts for the current/old password get oldPassword, prompts for the new password or its confirmation get newPassword, and an unrecognised prompt gets oldPassword (or newPassword when oldPassword is empty, as when root changes a password). Go programs never call setlocale(), so libpam prompts stay untranslated C-locale English and this matching is reliable even when LANG is set. For stacks whose prompts do not fit, use ChangeAuthTokConv.
If AcctMgmt on this transaction reported ErrNewAuthTokReqd, the change is made with PAM_CHANGE_EXPIRED_AUTHTOK — as login(1) and sshd do — so modules only update the expired token.
Failures (wrong oldPassword, newPassword rejected by quality checks or password policy, or no permission to update the password store) yield errors matching ErrAuthTok or ErrAuthTokRecovery depending on the module.
Linux: without root privileges pam_unix first asks for the current password ("Current password:"), then for the new one twice; as root the old password is usually not requested and oldPassword may be empty. Actually updating the password requires write access to /etc/shadow: root always works, while non-root only works on systems whose pam_unix ships a setuid unix_update helper (e.g. RHEL; Debian/Ubuntu do not — there the passwd(1) command relies on its own setuid bit).
macOS: the default service "checkpw" carries no password stack, so use a service that does, e.g. Options{Service: "passwd"} (whose stack is `password required pam_opendirectory.so`). pam_opendirectory prompts "Old Password:" then "New Password:". Updates go through OpenDirectory, so non-root users can change their own password.
func (*Transaction) ChangeAuthTokConv ¶
func (t *Transaction) ChangeAuthTokConv(conv ConvFunc) error
ChangeAuthTokConv runs pam_chauthtok with conv answering every conversation message, for callers that want to drive the password change interactively or handle prompts ChangeAuthTok does not recognise.
func (*Transaction) Close ¶
func (t *Transaction) Close() error
Close ends the transaction with pam_end and releases all resources. Calling Close more than once is harmless.
func (*Transaction) Messages ¶
func (t *Transaction) Messages() []string
Messages returns the error and informational messages (PAM_ERROR_MSG / PAM_TEXT_INFO) that PAM modules emitted during the most recent Authenticate, AcctMgmt or ChangeAuthTok call — e.g. why a new password was rejected, or that the password is about to expire. They are also appended to the text of the error returned by a failed call.
func (*Transaction) User ¶
func (t *Transaction) User() (string, error)
User returns the PAM_USER item: the user name as the PAM modules see it. Modules may rewrite it — e.g. case folding, alias or Kerberos principal mapping, or a username prompt — so after a successful Authenticate this is the account that was actually checked, which may differ from the name given to Start.
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
pamtester
command
Command pamtester is a small CLI demo that reads a password from stdin and verifies it against the current user's PAM account.
|
Command pamtester is a small CLI demo that reads a password from stdin and verifies it against the current user's PAM account. |