Callers change their passwords: mode = passwd

A built-in item: the current password (checked against the backends
again, which finds the one that holds the account), then the new one
twice (min_password, not the current one, three tries).  The password
changes where the account is:

- file: the user's line rewritten in place under the lock signups take,
  a note after the hash kept; bcrypt, or text with hash = plain
- sql: update_query with update_args (user, password, old_password) and
  update_hash (bcrypt, or none for a query that hashes it)
- ldap: Password Modify (RFC 3062) bound as the user, the server's own
  policy and hashing applying
- system: PAM's password stack; its messages (a quality module's
  reasons) go to the caller

A refused password leaves the old one; the selections after a change
get the new one.  The PAM sample has the password stack, and says that
pam_unix applies no quality checks for root (pam_pwquality with
enforce_for_root does).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RvtV8Dg9kqRaakbTEfyH3f
This commit is contained in:
Claude committed 2026-10-15 02:30:28 +00:00
1 parent 98755b757b
commit 329cf02304
14 files changed
+721 -46

No files matched your search

+43 -5
View File
@@ -186,6 +186,11 @@ run_as = {user}
tty = sane
pass_password = no
command = exec "$SHELL" -l
[item passwd]
key = PW
label = Change your password
mode = passwd
```
Comments start with `;` or `#`, on a line of their own or after a value
@@ -230,7 +235,8 @@ checks for expired and locked accounts. It needs a build with PAM
1. Install the PAM service: `make install` puts
[modemmenu.pam.sample](modemmenu.pam.sample) in `/etc/pam.d/modemmenu`
(the distribution's `common-auth` and `common-account`).
(the distribution's `common-auth`, `common-account` and, for password
changes, `common-password`).
2. Run Asterisk, and so modemmenu, as root for local accounts:
`pam_unix` checks other users' passwords only for root.
3. Add `system` to `[general] auth`, and in `[system]`:
@@ -246,6 +252,33 @@ An account that these rules keep out is "unknown" to this backend: the
next one is asked, and the reason is logged. With `run_as = {user}`, a
selection such as the shell then runs as the caller's own account.
### Changing passwords
A `mode = passwd` item lets callers change their own password; it needs
no command and returns to the menu (`after = menu`) by default. The
caller gives their current password, then the new one twice (at least
the item's `min_password`, 8 characters, and not the current one; three
tries). The current password is checked against the backends again,
which also finds the one that holds the account (a login by caller ID or
by an upstream menu does not say), and the password changes there:
| backend | how |
|---|---|
| file | the user's line rewritten in place under the file's lock (a note after the hash is kept); bcrypt, or text with `hash = plain` |
| sql | `[sql] update_query` with `update_args` (`user`, `password`, `old_password`, in the order of its placeholders); `update_hash = bcrypt` stores a bcrypt hash, `none` the password as typed, for a query that hashes it. Without `update_query`, SQL passwords cannot be changed here |
| ldap | the Password Modify extended operation (RFC 3062), bound as the user, so the server's own password policy and hashing apply. Active Directory does not support it |
| system | PAM's password stack of `pam_service`; what it says (a quality module's reasons) goes to the caller |
A refused password (the server's or PAM's policy) leaves the old one;
the selections after a change get the new one in `MODEM_PASSWORD`.
Guests have no password to change. The log says who changed their
password where, never the password.
Run as root, `pam_unix` applies no quality checks (its `minlen` and
the like are not for root): for a policy, put `pam_pwquality` before it
with `enforce_for_root`, as
[modemmenu.pam.sample](modemmenu.pam.sample) shows.
### Message of the day
After the welcome and before the menu, modemmenu shows `[general] motd`
@@ -452,13 +485,18 @@ caller hanging up, another modemmenu handing a logged-in caller over by
a `mode = unix` item, and `SIGTERM`. Calls test who sees what (users,
groups, `min_baud`, caller ID), a guest, signups (logged in at once, and
pending), refused and known numbers, and a selection hung up at the
day's limit, then the day's next call refused. The system backend's
uid, root and group rules are tested with PAM replaced.
day's limit, then the day's next call refused. Password changes are
tested in the users file (other lines and notes kept) and in SQLite, and
on a call: a wrong current password, the rules for the new one, the
change, the next login with it, and a guest. The system backend's uid,
root and group rules are tested with PAM replaced.
Two more tests run when their servers are given:
- `MODEMMENU_TEST_PAM=user:password make test`, as root with
`/etc/pam.d/modemmenu`: PAM against a real account.
`/etc/pam.d/modemmenu`: PAM against a real account, and its password
changed and back (the service needs a password stack).
- `MODEMMENU_TEST_LDAP=ldap://host:port make test`: the LDAP backend,
against a server with `uid=lduser,ou=people,dc=example,dc=com`
(password `ldpass`).
(password `ldpass`), and that password changed and back (the server
must let users write their own `userPassword`).
+78 -36
View File
@@ -73,11 +73,49 @@ func newLDAPAuth(s *section) (authenticator, error) {
func (a *ldapAuth) name() string { return "ldap" }
func (a *ldapAuth) authenticate(ctx context.Context, user, password string) error {
conn, _, err := a.bindUser(user, password)
if conn != nil {
conn.Close()
}
return err
}
// bindUser: a connection bound as the user, and the user's DN
func (a *ldapAuth) bindUser(user, password string) (*ldap.Conn, string, error) {
// an empty password would be an unauthenticated bind, which servers
// accept for any DN
if password == "" {
return errBadPassword
return nil, "", errBadPassword
}
conn, err := a.dial()
if err != nil {
return nil, "", err
}
dn, err := a.userDN(conn, user)
if err != nil {
conn.Close()
return nil, "", err
}
err = conn.Bind(dn, password)
var le *ldap.Error
if errors.As(err, &le) && le.ResultCode == ldap.LDAPResultInvalidCredentials {
conn.Close()
if a.bindDN != "" {
// a direct bind cannot tell an unknown DN from a wrong
// password: let the other backends try
return nil, "", errNoUser
}
return nil, "", errBadPassword
}
if err != nil {
conn.Close()
return nil, "", err
}
return conn, dn, nil
}
// dial the server, with StartTLS if configured
func (a *ldapAuth) dial() (*ldap.Conn, error) {
d := &net.Dialer{Timeout: a.timeout}
host := a.url
if i := strings.Index(host, "://"); i >= 0 {
@@ -90,50 +128,54 @@ func (a *ldapAuth) authenticate(ctx context.Context, user, password string) erro
}
conn, err := ldap.DialURL(a.url, ldap.DialWithDialer(d), ldap.DialWithTLSConfig(tc))
if err != nil {
return err
return nil, err
}
defer conn.Close()
conn.SetTimeout(a.timeout)
if a.startTLS {
if err := conn.StartTLS(tc); err != nil {
return fmt.Errorf("starttls: %v", err)
conn.Close()
return nil, fmt.Errorf("starttls: %v", err)
}
}
return conn, nil
}
dn := ""
// userDN: the user's DN, from bind_dn or by the search
func (a *ldapAuth) userDN(conn *ldap.Conn, user string) (string, error) {
if a.bindDN != "" {
dn = expand(a.bindDN, map[string]string{"user": user}, ldap.EscapeDN)
} else {
if a.searchDN != "" {
if err := conn.Bind(a.searchDN, a.searchPass); err != nil {
return fmt.Errorf("bind %s: %v", a.searchDN, err)
}
return expand(a.bindDN, map[string]string{"user": user}, ldap.EscapeDN), nil
}
if a.searchDN != "" {
if err := conn.Bind(a.searchDN, a.searchPass); err != nil {
return "", fmt.Errorf("bind %s: %v", a.searchDN, err)
}
filter := expand(a.filter, map[string]string{"user": user}, ldap.EscapeFilter)
res, err := conn.Search(ldap.NewSearchRequest(a.base, ldap.ScopeWholeSubtree,
ldap.NeverDerefAliases, 2, int(a.timeout/time.Second), false,
filter, []string{"dn"}, nil))
if err != nil {
return fmt.Errorf("search %s: %v", filter, err)
}
switch len(res.Entries) {
case 0:
return errNoUser
case 1:
dn = res.Entries[0].DN
default:
return fmt.Errorf("search %s: more than one entry", filter)
}
}
filter := expand(a.filter, map[string]string{"user": user}, ldap.EscapeFilter)
res, err := conn.Search(ldap.NewSearchRequest(a.base, ldap.ScopeWholeSubtree,
ldap.NeverDerefAliases, 2, int(a.timeout/time.Second), false,
filter, []string{"dn"}, nil))
if err != nil {
return "", fmt.Errorf("search %s: %v", filter, err)
}
switch len(res.Entries) {
case 0:
return "", errNoUser
case 1:
return res.Entries[0].DN, nil
}
return "", fmt.Errorf("search %s: more than one entry", filter)
}
// changePassword by the Password Modify extended operation (RFC 3062),
// bound as the user: the server applies its own password policy
func (a *ldapAuth) changePassword(_ context.Context, _ *term, user, old, new string) error {
conn, dn, err := a.bindUser(user, old)
if err != nil {
return err
}
err = conn.Bind(dn, password)
var le *ldap.Error
if errors.As(err, &le) && le.ResultCode == ldap.LDAPResultInvalidCredentials {
if a.bindDN != "" {
// a direct bind cannot tell an unknown DN from a wrong
// password: let the other backends try
return errNoUser
}
return errBadPassword
defer conn.Close()
if _, err := conn.PasswordModify(ldap.NewPasswordModifyRequest(dn, old, new)); err != nil {
return fmt.Errorf("%w: %v", errRefused, err)
}
return err
return nil
}
+4
View File
@@ -9,3 +9,7 @@ const havePAM = false
func pamAuthenticate(service, user, password string) error {
return errors.New("built without PAM")
}
func pamChangePassword(service, user, old, new string, line *term) error {
return errors.New("built without PAM")
}
+39
View File
@@ -5,6 +5,7 @@ package main
import (
"errors"
"fmt"
"strings"
"github.com/msteinert/pam/v2"
)
@@ -46,3 +47,41 @@ func pamAuthenticate(service, user, password string) error {
}
return nil
}
// pamChangePassword: the PAM service's password stack for the user. Its
// hidden prompts get the current password (asked for "current" or "old")
// or the new one; what it has to say goes to the caller (a quality
// module's reasons).
func pamChangePassword(service, user, old, new string, line *term) error {
t, err := pam.StartFunc(service, user, func(s pam.Style, msg string) (string, error) {
switch s {
case pam.PromptEchoOff:
m := strings.ToLower(msg)
if strings.Contains(m, "current") || strings.Contains(m, "old") {
return old, nil
}
return new, nil
case pam.PromptEchoOn:
return user, nil
case pam.ErrorMsg, pam.TextInfo:
if line != nil && msg != "" {
line.write(crlf(strings.TrimRight(msg, "\n")) + "\r\n")
}
return "", nil
}
return "", fmt.Errorf("unsupported PAM message style %d", s)
})
if err != nil {
return fmt.Errorf("pam %s: %v", service, err)
}
defer t.End()
t.SetItem(pam.Tty, "modem")
if err := t.ChangeAuthTok(0); err != nil {
if errors.Is(err, pam.ErrAuthtok) || errors.Is(err, pam.ErrPermDenied) ||
errors.Is(err, pam.ErrAuthtokRecovery) || errors.Is(err, pam.ErrAuth) {
return fmt.Errorf("%w: pam %s: %v", errRefused, service, err)
}
return fmt.Errorf("pam %s: %v", service, err)
}
return nil
}
+28
View File
@@ -36,3 +36,31 @@ func TestPAM(t *testing.T) {
t.Errorf("root: %v", err)
}
}
// MODEMMENU_TEST_PAM, a password stack in /etc/pam.d/modemmenu: the
// account's password changed and back
func TestPAMChangePassword(t *testing.T) {
cred := os.Getenv("MODEMMENU_TEST_PAM")
if cred == "" {
t.Skip("MODEMMENU_TEST_PAM is not set")
}
user, pw, _ := strings.Cut(cred, ":")
a, err := newSystemAuth(&section{name: "system", vals: map[string]string{}})
if err != nil {
t.Fatal(err)
}
sa := a.(*systemAuth)
ctx := context.Background()
if err := sa.changePassword(ctx, nil, user, pw, pw+"-2"); err != nil {
t.Fatal(err)
}
if err := a.authenticate(ctx, user, pw+"-2"); err != nil {
t.Errorf("the new password: %v", err)
}
if err := a.authenticate(ctx, user, pw); err == nil {
t.Error("the old password still works")
}
if err := sa.changePassword(ctx, nil, user, pw+"-2", pw); err != nil {
t.Errorf("back: %v", err)
}
}
+16
View File
@@ -24,6 +24,11 @@ type sqlAuth struct {
scheme string
timeout time.Duration
db *sql.DB
// changing passwords (mode = passwd items): update_query with
// update_args, the password as update_hash says
updateQuery string
updateArgs []string
updateHash string
}
var sqlDrivers = map[string]string{
@@ -58,6 +63,17 @@ func newSQLAuth(s *section) (authenticator, error) {
if a.timeout, err = s.duration("timeout", 10*time.Second); err != nil {
return nil, err
}
a.updateQuery = s.get("update_query", "")
a.updateArgs = fields(strings.ToLower(s.get("update_args", "password user")))
a.updateHash = strings.ToLower(s.get("update_hash", "bcrypt"))
for _, arg := range a.updateArgs {
if arg != "user" && arg != "password" && arg != "old_password" {
return nil, fmt.Errorf("[sql] update_args: %q (user, password, old_password)", arg)
}
}
if a.updateHash != "bcrypt" && a.updateHash != "none" {
return nil, fmt.Errorf("[sql] update_hash: %q (bcrypt, or none: the password as typed, for a query that hashes it)", a.updateHash)
}
// opening does not connect: a database that is down only fails the
// logins that reach it
if a.db, err = sql.Open(a.driver, a.dsn); err != nil {
+3 -1
View File
@@ -20,8 +20,10 @@ import (
// launch the selection: its error, or nil when it ended by itself;
// errTimeLimit when deadline (if not zero) ended it
func launch(t *term, it *menuItem, s *session, deadline time.Time, logf func(string, ...any)) error {
func launch(t *term, cfg *settings, it *menuItem, s *session, deadline time.Time, logf func(string, ...any)) error {
switch it.mode {
case "passwd":
return changePasswordItem(t, cfg, it, s, deadline)
case "exec":
return runExec(t, it, s, deadline, logf)
default:
+1 -1
View File
@@ -387,7 +387,7 @@ func menu(t *term, s *settings, sess *session, lim *limiter, first *menuItem) er
sess.Selection = it.name
sess.TimeLeft = lim.timeLeft(time.Now())
logf("start %s user=%s mode=%s", it.name, sess.User, it.mode)
err := launch(t, it, sess, lim.deadline, logf)
err := launch(t, s, it, sess, lim.deadline, logf)
if errors.Is(err, errHangup) || terminated.Load() {
return errHangup
}
+23 -1
View File
@@ -166,11 +166,22 @@ dsn = modem:secret@tcp(127.0.0.1:3306)/bbs
query = SELECT password FROM users WHERE username = ? AND enabled = 1
args = user
hash = auto
; mode = passwd items: update_query sets the password, with update_args
; (user, password, old_password, in the order of its placeholders);
; update_hash = bcrypt stores a bcrypt hash, none the password as typed
; (for a query that hashes it). Without update_query, SQL passwords
; cannot be changed from the menu
update_query = UPDATE users SET password = ? WHERE username = ?
update_args = password user
update_hash = bcrypt
;driver = postgres
;dsn = postgres://modem:secret@127.0.0.1/bbs?sslmode=disable
;query = SELECT 1 FROM users WHERE username = $1 AND password = crypt($2, password)
;args = user password
;hash = none
;update_query = UPDATE users SET password = crypt($1, gen_salt('bf')) WHERE username = $2
;update_args = password user
;update_hash = none
;driver = sqlite
;dsn = /var/lib/asterisk/users.db
;query = SELECT password FROM users WHERE username = ?
@@ -199,7 +210,7 @@ max_sessions = 32
title = "\r\nMain menu\r\n"
prompt = "\r\nSelection: "
; the items in order (default: every [item ...] in file order)
items = bbs ppp shell
items = bbs ppp shell passwd
; the caller types a choice and Enter: an item's key, its name or one of
; its aliases, in any case (P, p, ppp). ? shows the menu again. What hangs
; up (the first one is shown in the menu):
@@ -213,6 +224,8 @@ hotkeys = no
; aliases = ... more words that select it (its name always does)
; label = ... its line in the menu
; mode = exec a program on the line: command (by /bin/sh -c)
; passwd built in: the caller changes their password
; (min_password = 8 characters)
; tcp a TCP server, raw: host, port; send is sent first
; unix a server on a unix socket, raw: path; send too
; (tcp, telnet and rlogin take a path as well, for
@@ -270,6 +283,15 @@ label = PPP (dial-up networking)
mode = exec
command = exec /usr/sbin/pppd nodetach noauth local lock passive 192.168.77.1:192.168.77.2 ms-dns 192.168.77.1 ipparam {user}
; the caller's password changed where their account is: the users file,
; SQL (update_query), LDAP (Password Modify, as the user) or the system
; (PAM's password stack). after = menu by default
[item passwd]
key = PW
label = Change your password
mode = passwd
min_password = 8
; a shell of the caller's account (modemmenu runs as root for run_as)
[item shell]
key = S
+9
View File
@@ -2,5 +2,14 @@
#
# pam_unix checks another user's password only for root: run modemmenu
# (Asterisk) as root for local accounts.
#
# The password stack is for mode = passwd items. Run as root, pam_unix
# applies no quality checks of its own (minlen and the like are not for
# root): for a policy, put pam_pwquality before it with enforce_for_root,
# e.g. instead of common-password:
#
# password requisite pam_pwquality.so retry=1 minlen=12 enforce_for_root
# password required pam_unix.so yescrypt use_authtok
@include common-auth
@include common-account
@include common-password
+5
View File
@@ -9,6 +9,7 @@ import (
"encoding/hex"
"errors"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
@@ -222,3 +223,7 @@ func TestMenuSettings(t *testing.T) {
t.Errorf("hotkeys with one-character keys: %v", err)
}
}
func runGo(args ...string) ([]byte, error) {
return exec.Command("go", args...).CombinedOutput()
}
+230
View File
@@ -0,0 +1,230 @@
package main
import (
"context"
"errors"
"fmt"
"io"
"os"
"strings"
"time"
"golang.org/x/crypto/bcrypt"
"golang.org/x/sys/unix"
)
// errRefused: the backend did not take the new password (its policy)
var errRefused = errors.New("new password refused")
// passwordChanger: a backend that can change a user's password; old has
// been checked already. t is the caller's line, for a backend (PAM) that
// has something to tell them.
type passwordChanger interface {
changePassword(ctx context.Context, t *term, user, old, new string) error
}
// changePasswordItem: mode = passwd, the caller's password changed in
// the backend that holds their account
func changePasswordItem(t *term, s *settings, it *menuItem, sess *session, deadline time.Time) error {
if sess.Auth == "guest" {
return t.write("\r\nA guest has no password to change.\r\n")
}
end := time.Now().Add(s.loginTimeout)
if !deadline.IsZero() && deadline.Before(end) {
end = deadline
}
timeUp := func(err error) error {
if errors.Is(err, errTimeout) && !deadline.IsZero() && !time.Now().Before(deadline) {
return errTimeLimit
}
if errors.Is(err, errTimeout) || errors.Is(err, io.EOF) {
t.write("\r\nYour password is as it was.\r\n")
return nil
}
return err
}
if err := t.write("\r\nCurrent password: "); err != nil {
return err
}
old, err := t.readLine(end, s.maxInput*2, false, s.mask)
if err != nil {
return timeUp(err)
}
// which backend holds the account: the one that takes the password
// (a login by caller ID or an upstream menu did not say)
ctx, cancel := context.WithDeadline(context.Background(), end.Add(10*time.Second))
defer cancel()
name, err := authenticate(ctx, s.backends, sess.User, old, logf)
if err != nil {
logf("passwd user=%s: current password wrong (%v)", sess.User, err)
time.Sleep(s.failDelay)
return t.write("That is not your password.\r\n")
}
var changer passwordChanger
for _, b := range s.backends {
if b.name() == name {
changer, _ = b.(passwordChanger)
if sa, ok := b.(*sqlAuth); ok && sa.updateQuery == "" {
changer = nil
}
}
}
if changer == nil {
logf("passwd user=%s: %s cannot change passwords", sess.User, name)
return t.write("Your password cannot be changed here. Ask the sysop.\r\n")
}
var pw string
for try := 0; ; try++ {
if try == 3 {
return t.write("Your password is as it was.\r\n")
}
if err := t.write("New password: "); err != nil {
return err
}
p, err := t.readLine(end, s.maxInput*2, false, s.mask)
if err != nil {
return timeUp(err)
}
switch {
case p == "":
return t.write("Your password is as it was.\r\n")
case len(p) < it.minPassword:
t.write(fmt.Sprintf("At least %d characters, please.\r\n", it.minPassword))
continue
case p == old:
t.write("That is your password now; another one, please.\r\n")
continue
}
if err := t.write("Again: "); err != nil {
return err
}
again, err := t.readLine(end, s.maxInput*2, false, s.mask)
if err != nil {
return timeUp(err)
}
if again != p {
t.write("They differ.\r\n")
continue
}
pw = p
break
}
if err := changer.changePassword(ctx, t, sess.User, old, pw); err != nil {
logf("passwd user=%s auth=%s: %v", sess.User, name, err)
if errors.Is(err, errRefused) {
return t.write("The new password was not accepted. Your password is as it was.\r\n")
}
return t.write("Sorry, your password cannot be changed now.\r\n")
}
sess.Password = pw
logf("passwd user=%s auth=%s: changed", sess.User, name)
return t.write("Your password is changed.\r\n")
}
// changePassword in the users file: the user's line rewritten in place
// (other lines as they are) under the lock signups take, the password as
// bcrypt (as text with hash = plain), a note after it kept
func (a *fileAuth) changePassword(_ context.Context, _ *term, user, old, new string) error {
f, err := os.OpenFile(a.path, os.O_RDWR, 0)
if err != nil {
return err
}
defer f.Close()
if err := unix.Flock(int(f.Fd()), unix.LOCK_EX); err != nil {
return err
}
st, err := f.Stat()
if err != nil {
return err
}
b := make([]byte, st.Size())
if _, err := f.ReadAt(b, 0); err != nil && err != io.EOF {
return err
}
stored := ""
if a.scheme == "plain" {
stored = new
} else {
h, err := bcrypt.GenerateFromPassword([]byte(new), bcrypt.DefaultCost)
if err != nil {
return err
}
stored = string(h)
}
lines := strings.Split(string(b), "\n")
found := false
for i, line := range lines {
t := strings.TrimSpace(line)
if t == "" || t[0] == '#' {
continue
}
name, rest, ok := strings.Cut(t, ":")
if !ok || name != user {
continue
}
// what follows the hash: user:hash:note (not after {SCHEME}text
// or with hash = plain, where the rest is the password)
note := ""
if a.scheme != "plain" && !strings.HasPrefix(rest, "{") {
if _, n, ok := strings.Cut(rest, ":"); ok {
note = ":" + n
}
}
lines[i] = name + ":" + stored + note
found = true
break
}
if !found {
return errNoUser
}
out := []byte(strings.Join(lines, "\n"))
if _, err := f.WriteAt(out, 0); err != nil {
return err
}
if err := f.Truncate(int64(len(out))); err != nil {
return err
}
return f.Sync()
}
// changePassword in the database: update_query with update_args, the
// password as update_hash says
func (a *sqlAuth) changePassword(ctx context.Context, _ *term, user, old, new string) error {
stored := new
if a.updateHash == "bcrypt" {
h, err := bcrypt.GenerateFromPassword([]byte(new), bcrypt.DefaultCost)
if err != nil {
return err
}
stored = string(h)
}
args := make([]any, len(a.updateArgs))
for i, arg := range a.updateArgs {
switch arg {
case "user":
args[i] = user
case "password":
args[i] = stored
case "old_password":
args[i] = old
}
}
ctx, cancel := context.WithTimeout(ctx, a.timeout)
defer cancel()
res, err := a.db.ExecContext(ctx, a.updateQuery, args...)
if err != nil {
return err
}
if n, err := res.RowsAffected(); err == nil && n != 1 {
return fmt.Errorf("update_query changed %d rows, not 1", n)
}
return nil
}
// changePassword by PAM: the service's password stack
func (a *systemAuth) changePassword(_ context.Context, t *term, user, old, new string) error {
return pamChangePassword(a.service, user, old, new, t)
}
+229
View File
@@ -0,0 +1,229 @@
package main
import (
"context"
"database/sql"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
)
func TestFileChangePassword(t *testing.T) {
dir := t.TempDir()
users := filepath.Join(dir, "users")
os.WriteFile(users, []byte("# users\nalice:{PLAIN}old-pw\nbob:{PLAIN}bob-pw\ncarol:$2a$04$abcdefghijklmnopqrstuuJ8Jq7QF7mHNXgNnrBX3/7uJpH9fC2T6:signup 2026-10-12 5551234\n"), 0o600)
fa, err := newFileAuth(&section{name: "file", vals: map[string]string{"path": users}})
if err != nil {
t.Fatal(err)
}
ctx := context.Background()
if err := fa.(*fileAuth).changePassword(ctx, nil, "alice", "old-pw", "new-pw-1"); err != nil {
t.Fatal(err)
}
if err := fa.authenticate(ctx, "alice", "new-pw-1"); err != nil {
t.Errorf("the new password: %v", err)
}
if err := fa.authenticate(ctx, "alice", "old-pw"); !errors.Is(err, errBadPassword) {
t.Errorf("the old password: %v", err)
}
if err := fa.authenticate(ctx, "bob", "bob-pw"); err != nil {
t.Errorf("bob, untouched: %v", err)
}
// a note after the hash stays
if err := fa.(*fileAuth).changePassword(ctx, nil, "carol", "", "carol-new"); err != nil {
t.Fatal(err)
}
b, _ := os.ReadFile(users)
lines := strings.Split(string(b), "\n")
if len(lines) != 5 || lines[0] != "# users" || !strings.HasPrefix(lines[1], "alice:$2a$") ||
lines[2] != "bob:{PLAIN}bob-pw" || !strings.HasSuffix(lines[3], ":signup 2026-10-12 5551234") || lines[4] != "" {
t.Errorf("users file:\n%s", b)
}
if err := fa.(*fileAuth).changePassword(ctx, nil, "dave", "", "x"); !errors.Is(err, errNoUser) {
t.Errorf("dave: %v", err)
}
// hash = plain: the password as text
os.WriteFile(users, []byte("erin:old:x\n"), 0o600)
fp, _ := newFileAuth(&section{name: "file", vals: map[string]string{"path": users, "hash": "plain"}})
fp.(*fileAuth).changePassword(ctx, nil, "erin", "old:x", "new")
if b, _ := os.ReadFile(users); string(b) != "erin:new\n" {
t.Errorf("plain: %q", b)
}
}
func TestSQLChangePassword(t *testing.T) {
dir := t.TempDir()
dbPath := filepath.Join(dir, "users.db")
db, _ := sql.Open("sqlite", dbPath)
if _, err := db.Exec(`CREATE TABLE users (username TEXT, password TEXT);
INSERT INTO users VALUES ('carol', '{PLAIN}pw'), ('dave', '{PLAIN}pw');`); err != nil {
t.Fatal(err)
}
db.Close()
vals := map[string]string{"driver": "sqlite", "dsn": dbPath,
"query": "SELECT password FROM users WHERE username = ?"}
a, err := newSQLAuth(&section{name: "sql", vals: vals})
if err != nil {
t.Fatal(err)
}
ctx := context.Background()
vals["update_query"] = "UPDATE users SET password = ? WHERE username = ?"
a, _ = newSQLAuth(&section{name: "sql", vals: vals})
if err := a.(*sqlAuth).changePassword(ctx, nil, "carol", "pw", "carol-new"); err != nil {
t.Fatal(err)
}
if err := a.authenticate(ctx, "carol", "carol-new"); err != nil {
t.Errorf("the new password: %v", err)
}
if err := a.authenticate(ctx, "dave", "pw"); err != nil {
t.Errorf("dave, untouched: %v", err)
}
if err := a.(*sqlAuth).changePassword(ctx, nil, "nobody", "pw", "x"); err == nil {
t.Error("no row: no error")
}
vals["update_args"] = "user nonsense"
if _, err := newSQLAuth(&section{name: "sql", vals: vals}); err == nil {
t.Error("update_args nonsense: no error")
}
}
func TestPasswdLine(t *testing.T) {
dir := t.TempDir()
bin := filepath.Join(dir, "modemmenu")
if out, err := runGo("build", "-o", bin, "."); err != nil {
t.Fatalf("build: %v\n%s", err, out)
}
users := filepath.Join(dir, "users")
os.WriteFile(users, []byte("alice:{PLAIN}old-password\n"), 0o600)
conf := filepath.Join(dir, "c.conf")
os.WriteFile(conf, []byte(fmt.Sprintf(`
[general]
log = %s
auth = file
fail_delay = 0
[file]
path = %s
[guest]
enabled = yes
[item passwd]
key = PW
label = Change your password
mode = passwd
guest = yes
[item info]
command = echo "PW=$MODEM_PASSWORD"
after = menu
`, filepath.Join(dir, "log"), users)), 0o600)
c, cmd := callAs(t, bin, conf)
c.expect("login: ")
c.send("alice\r")
c.expect("Password: ")
c.send("old-password\r")
c.expect("Selection: ")
c.send("pw\r")
c.expect("Current password: ")
c.send("wrong\r")
c.expect("That is not your password.")
c.expect("Selection: ")
c.send("passwd\r")
c.expect("Current password: ")
c.send("old-password\r")
c.expect("New password: ")
c.send("short\r")
c.expect("At least 8")
c.expect("New password: ")
c.send("old-password\r")
c.expect("another one")
c.expect("New password: ")
c.send("new-password\r")
c.expect("Again: ")
c.send("new-passwork\r")
c.expect("They differ.")
// three tries
c.expect("Your password is as it was.")
c.expect("Selection: ")
c.send("pw\r")
c.expect("Current password: ")
c.send("old-password\r")
c.expect("New password: ")
c.send("new-password\r")
c.expect("Again: ")
c.send("new-password\r")
c.expect("Your password is changed.")
c.expect("Selection: ")
// the selections after it get the new one
c.send("info\r")
c.expect("PW=new-password")
c.send("g\r")
waitExit(t, cmd)
c, cmd = callAs(t, bin, conf)
c.expect("login: ")
c.send("alice\r")
c.expect("Password: ")
c.send("old-password\r")
c.expect("Login incorrect")
c.expect("login: ")
c.send("alice\r")
c.expect("Password: ")
c.send("new-password\r")
c.expect("Selection: ")
c.send("g\r")
waitExit(t, cmd)
// a guest has none
c, cmd = callAs(t, bin, conf)
c.expect("login: ")
c.send("guest\r")
c.expect("Selection: ")
c.send("pw\r")
c.expect("A guest has no password")
c.send("g\r")
waitExit(t, cmd)
log, _ := os.ReadFile(filepath.Join(dir, "log"))
for _, w := range []string{"passwd user=alice: current password wrong", "passwd user=alice auth=file: changed"} {
if !strings.Contains(string(log), w) {
t.Errorf("no %q in the log:\n%s", w, log)
}
}
if strings.Contains(string(log), "new-password") {
t.Errorf("a password in the log:\n%s", log)
}
}
// MODEMMENU_TEST_LDAP (see ldap_test.go), the server letting users write
// their own userPassword: lduser's password changed and back
func TestLDAPChangePassword(t *testing.T) {
url := os.Getenv("MODEMMENU_TEST_LDAP")
if url == "" {
t.Skip("MODEMMENU_TEST_LDAP is not set")
}
a, err := newLDAPAuth(&section{name: "ldap", vals: map[string]string{
"url": url, "search_base": "ou=people,dc=example,dc=com"}})
if err != nil {
t.Fatal(err)
}
la := a.(*ldapAuth)
ctx := context.Background()
if err := la.changePassword(ctx, nil, "lduser", "wrong", "x"); !errors.Is(err, errBadPassword) {
t.Errorf("a wrong current password: %v", err)
}
if err := la.changePassword(ctx, nil, "lduser", "ldpass", "ldpass-2"); err != nil {
t.Fatal(err)
}
if err := a.authenticate(ctx, "lduser", "ldpass-2"); err != nil {
t.Errorf("the new password: %v", err)
}
if err := a.authenticate(ctx, "lduser", "ldpass"); err == nil {
t.Error("the old password still works")
}
if err := la.changePassword(ctx, nil, "lduser", "ldpass-2", "ldpass"); err != nil {
t.Errorf("back: %v", err)
}
}
+13 -2
View File
@@ -51,6 +51,7 @@ type menuItem struct {
after string // hangup, menu
timeout time.Duration
access itemAccess
minPassword int // mode = passwd
}
// serverSettings: [server], for modemmenu -serve
@@ -246,7 +247,15 @@ func loadItem(name string, sec *section) (*menuItem, error) {
it.terminal = sec.get("terminal", "ANSI")
it.runAs = sec.get("run_as", "")
it.tty = strings.ToLower(sec.get("tty", "raw"))
it.after = strings.ToLower(sec.get("after", "hangup"))
defAfter := "hangup"
if strings.EqualFold(sec.get("mode", ""), "passwd") {
// a password changed is no reason to hang up
defAfter = "menu"
}
it.after = strings.ToLower(sec.get("after", defAfter))
if it.minPassword, err = sec.int("min_password", 8); err != nil {
return nil, err
}
if it.password, err = sec.bool("pass_password", true); err != nil {
return nil, err
}
@@ -271,6 +280,8 @@ func loadItem(name string, sec *section) (*menuItem, error) {
return nil, err
}
switch it.mode {
case "passwd":
// built in: no command, no server
case "exec":
if it.command == "" {
return nil, fmt.Errorf("[item %s] mode = exec needs a command", name)
@@ -286,7 +297,7 @@ func loadItem(name string, sec *section) (*menuItem, error) {
return nil, fmt.Errorf("[item %s] path: %q (an absolute path)", name, it.path)
}
default:
return nil, fmt.Errorf("[item %s] mode: %q (exec, tcp, unix, telnet or rlogin)", name, it.mode)
return nil, fmt.Errorf("[item %s] mode: %q (exec, tcp, unix, telnet, rlogin or passwd)", name, it.mode)
}
if it.tty != "raw" && it.tty != "sane" {
return nil, fmt.Errorf("[item %s] tty: %q (raw or sane)", name, it.tty)