pamtester

package module
v0.0.0-...-667a9a5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 11, 2026 License: MIT Imports: 9 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

pamtester

Verify and change users' login passwords through the OS authentication stack — no cgo required.

Platform Backend
Linux Linux-PAM (libpam.so.0) via purego
macOS OpenPAM (libpam.2.dylib) via purego
Windows LogonUserW / NetUserChangePassword
FreeBSD OpenPAM (libpam.so.6) via purego; requires cgo (see below)
others stub, Start returns errors.ErrUnsupported

On Linux the binary needs glibc: without cgo, purego links against libc.so.6, so on musl systems such as Alpine install gcompat (or build with -tags nopamtester if PAM is not needed there).

On FreeBSD purego only builds without cgo given a special -gcflags flag, so the PAM backend is enabled only when cgo is on (the default for native builds). CGO_ENABLED=0 builds, e.g. cross-compiles, get the stub.

Build with -tags nopamtester to compile the stub on every platform (e.g. to drop the purego dependency from a binary that never authenticates).

Example

package main

import (
    "errors"
    "fmt"
    "os"

    "github.com/phuslu/pamtester"
)

func main() {
    // "" means the current user. Non-root processes can only verify their
    // own password; checking other accounts requires root.
    t, err := pamtester.Start("", nil)
    if err != nil {
        fmt.Fprintln(os.Stderr, "pam start failed:", err)
        os.Exit(1)
    }
    defer t.Close()

    // Verify password (pam_authenticate)
    err = t.Authenticate("secret")
    switch {
    case err == nil:
        fmt.Println("password correct")
    case errors.Is(err, pamtester.ErrAuth):
        fmt.Println("wrong password")
    default:
        fmt.Fprintln(os.Stderr, "auth failed:", err)
        os.Exit(1)
    }

    // Check the account itself (expired, locked, access rules)
    if err := t.AcctMgmt(); errors.Is(err, pamtester.ErrNewAuthTokReqd) {
        fmt.Println("password expired, must be changed")
    }

    // Change password (equivalent to passwd; writing /etc/shadow
    // generally requires root on Debian/Ubuntu)
    if err := t.ChangeAuthTok("secret", "n3w-Secret!"); err != nil {
        // Module messages such as "BAD PASSWORD: ..." are included in err
        // and also available via t.Messages().
        fmt.Fprintln(os.Stderr, "change failed:", err)
    }
}

Errors

Every failure wraps a pamtester.Error using Linux-PAM numbering on all platforms (OpenPAM and Win32 codes are translated), so use errors.Is:

Error Meaning
ErrAuth wrong password
ErrUserUnknown no such user
ErrNewAuthTokReqd password correct but expired; must be changed
ErrAcctExpired account expired or disabled
ErrMaxTries account locked out
ErrPermDenied access denied (e.g. pam_access, logon restrictions)
ErrAuthTok, ErrAuthTokRecovery password change rejected / wrong old password

Custom conversation

For stacks that ask more than one password (OTP, 2FA, a username prompt), or to drive a password change interactively, pass a ConvFunc. It receives every message: prompts (PromptEchoOff, PromptEchoOn) are answered with the returned string, ErrorMsg/TextInfo are informational.

err := t.AuthenticateConv(func(style pamtester.Style, msg string) (string, error) {
    switch style {
    case pamtester.PromptEchoOff:
        if strings.Contains(strings.ToLower(msg), "verification code") {
            return readOTP()
        }
        return password, nil
    case pamtester.PromptEchoOn:
        return readLine(msg)
    default:
        fmt.Println(msg) // ErrorMsg / TextInfo
        return "", nil
    }
})

Returning an error aborts the PAM call; the returned error wraps it, so errors.Is(err, yourErr) works. ChangeAuthTokConv does the same for pam_chauthtok. On Windows, which has no PAM conversation, these ask for the password(s) with fixed prompts and then call Authenticate/ChangeAuthTok.

Empty passwords

Authenticate("") fails with ErrAuth by default, and PAM_DISALLOW_NULL_AUTHTOK is passed to PAM: stacks with nullok (Debian's common-auth, macOS checkpw) would otherwise accept an empty password for accounts that have none. Set Options.AllowNullAuthTok to opt out.

Concurrency and blocking

  • Each call blocks its goroutine and an OS thread until PAM returns. Bound concurrent authentications (e.g. a semaphore) rather than one goroutine per request without limit.
  • A wrong password is slow on purpose: pam_unix/pam_faildelay add about a 2 s delay. Network-backed modules (sssd, LDAP, Kerberos) wait for their own timeouts.
  • Calls cannot be cancelled (no context.Context; libpam has no way to interrupt a module). You can stop waiting with a goroutine + timer, but the call keeps running and the Transaction stays locked until it returns.
  • A Transaction serializes its own methods; separate transactions run in parallel. Some PAM modules are not thread-safe — if your stack has one, guard all calls with a single application-level mutex.
var sem = make(chan struct{}, 8) // at most 8 PAM calls in flight

func check(user, password string) error {
    sem <- struct{}{}
    defer func() { <-sem }()

    t, err := pamtester.Start(user, &pamtester.Options{Service: "myapp"})
    if err != nil {
        return err
    }
    defer t.Close()
    if err := t.Authenticate(password); err != nil {
        return err
    }
    return t.AcctMgmt()
}

Privileges

  • Verify own password: no root needed (Linux delegates to the setuid unix_chkpwd helper).
  • Verify other users: root on Linux.
  • Change password: root on Debian/Ubuntu (writes /etc/shadow); RHEL's setuid unix_update and macOS OpenDirectory allow users to change their own.

PAM service

Start uses the PAM service named by Options.Service, defaulting to pamtester.PamService (passwd on Linux, checkpw on macOS, system on FreeBSD).

On Linux, /etc/pam.d/passwd usually contains only a password stack, so Authenticate/AcctMgmt rely on Linux-PAM falling back to /etc/pam.d/other. That works on Debian/Ubuntu (where other includes common-auth), but fails on systems whose other is pam_deny. If you mainly verify passwords, pick a service with an auth section explicitly, or ship your own:

t, err := pamtester.Start(user, &pamtester.Options{Service: "login"})
# /etc/pam.d/myapp
auth    include system-auth   # or: @include common-auth (Debian)
account include system-auth   # or: @include common-account

Testing

go test ./...                      # unit tests; integration tests skip without pam_wrapper
sudo apt install libpam-wrapper    # cwrap pam_wrapper + pam_matrix
go test -v ./...                   # Linux: sandboxed libpam tests, no root or real accounts
PAMTESTER_LIVE=1 go test ./...     # macOS/FreeBSD/Windows: one failed logon against the current user

PAMTESTER_PAM_WRAPPER_LIB=/path/to/libpam_wrapper.so points the tests at a non-standard location.

CLI

go run ./cmd/pamtester/

# Authenticate through PAM's "login" service and start a login shell.
# Non-root callers may only log in as their current account.
go -C cmd/login run . [-login-name name] [username]

For a non-root caller, -login-name/--login-name (or the LOGIN_NAME environment variable) can provide the name that must be entered at the login prompt while PAM still authenticates the real current account. The command-line option takes precedence over the environment variable:

go -C cmd/login run . --login-name phus.lu
# Equivalent:
LOGIN_NAME=phus.lu go -C cmd/login run .

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

Constants

This section is empty.

Variables

View Source
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

type ConvFunc func(style Style, msg string) (string, error)

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
	ErrAuthinfoUnavail     Error = 9  // PAM_AUTHINFO_UNAVAIL
	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
	ErrCredUnavail         Error = 15 // PAM_CRED_UNAVAIL
	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).

func (Error) Error

func (e Error) Error() string

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址