Files
login/internal/auth/auth.go
T
Claude 80d0fda167 Split the code into packages: cmd/modemmenu, internal/*, authd
All of modemmenu was one package main in the repository's root.  It is
now one module with the program and the pieces it is made of apart:

  cmd/modemmenu/     the program (the login, the menu, access, limits,
                     the selections, -serve, AutoPPP, drop files, the
                     auth socket's server)
  internal/config/   modemmenu.conf's sections and keys, {name} templates
  internal/term/     the caller's line, terminal detection, PETSCII
  internal/auth/     the backends and password changes
  internal/telnet/   the telnet client of mode = telnet items
  authd/             the auth socket's protocol and a client, for a BBS
                     to import (bbs's internal/menuauth is a copy of it)
  samples/           the .conf, .users, .pam and .service samples

make builds ./cmd/modemmenu and installs the samples from samples/; the
docs, confref and the site's reference follow.  The tests are where
their code is, none lost.  TestSampleHasEveryKey now reads the keys of
internal/ too (and the exported Get, Bool...: it would have found none).
.gitignore's "modemmenu" ignored cmd/modemmenu/ as well: it is
/modemmenu now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B82eRRbjf74j8oq9R3PXhA
2026-11-06 03:12:02 +00:00

143 lines
4.3 KiB
Go

// Copyright (C) 2026 D-Modem Authors
// SPDX-License-Identifier: AGPL-3.0-only
// Package auth checks a user's password with modemmenu's backends (a
// users file, LDAP, SQL, the system's accounts by PAM), in turn, and
// changes it in the backend that holds the account.
package auth
import (
"context"
"crypto/sha256"
"crypto/sha512"
"crypto/subtle"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"strings"
"golang.org/x/crypto/bcrypt"
)
// ErrNoUser: the backend does not know the user (the next one is asked);
// ErrBadPassword: it knows the user, the password is wrong (no other
// backend is asked)
var (
ErrNoUser = errors.New("no such user")
ErrBadPassword = errors.New("wrong password")
)
type Authenticator interface {
Name() string
Authenticate(ctx context.Context, user, password string) error
}
// a hash compared against when the user is unknown, so that the answer
// takes as long either way
var dummyHash, _ = bcrypt.GenerateFromPassword([]byte("dummy password"), bcrypt.DefaultCost)
// CheckPassword against a stored password, in the scheme its prefix or
// scheme (auto: by prefix) names:
//
// $2a$, $2b$, $2y$ ... bcrypt
// {SHA256}hex, {SHA512}hex (or base64), {SSHA256}/{SSHA512}base64(hash+salt)
// {PLAIN}text, or text with scheme = plain
func CheckPassword(stored, password, scheme string) (bool, error) {
if scheme == "" || scheme == "auto" {
scheme = "plain"
switch {
case strings.HasPrefix(stored, "$2a$"), strings.HasPrefix(stored, "$2b$"),
strings.HasPrefix(stored, "$2y$"):
scheme = "bcrypt"
case strings.HasPrefix(stored, "{"):
end := strings.IndexByte(stored, '}')
if end < 0 {
return false, fmt.Errorf("stored password: no } after the scheme")
}
scheme = strings.ToLower(stored[1:end])
stored = stored[end+1:]
default:
// a bare value is plain text only when it is asked for
return false, fmt.Errorf("stored password: unknown scheme (bcrypt, {SHA256}, {SHA512}, {SSHA256}, {SSHA512} or {PLAIN})")
}
}
switch scheme {
case "bcrypt":
err := bcrypt.CompareHashAndPassword([]byte(stored), []byte(password))
if errors.Is(err, bcrypt.ErrMismatchedHashAndPassword) {
return false, nil
}
return err == nil, err
case "sha256":
h := sha256.Sum256([]byte(password))
return equalDigest(stored, h[:]), nil
case "sha512":
h := sha512.Sum512([]byte(password))
return equalDigest(stored, h[:]), nil
case "ssha256", "ssha512":
raw, err := base64.StdEncoding.DecodeString(stored)
size := sha256.Size
if scheme == "ssha512" {
size = sha512.Size
}
if err != nil || len(raw) <= size {
return false, fmt.Errorf("stored password: bad {%s} value", strings.ToUpper(scheme))
}
salt := append([]byte(password), raw[size:]...)
var h []byte
if scheme == "ssha256" {
s := sha256.Sum256(salt)
h = s[:]
} else {
s := sha512.Sum512(salt)
h = s[:]
}
return subtle.ConstantTimeCompare(h, raw[:size]) == 1, nil
case "plain":
return subtle.ConstantTimeCompare([]byte(stored), []byte(password)) == 1, nil
}
return false, fmt.Errorf("unknown password scheme %q", scheme)
}
// equalDigest: a stored digest in hex or base64 against the computed one
func equalDigest(stored string, sum []byte) bool {
if b, err := hex.DecodeString(stored); err == nil && len(b) == len(sum) {
return subtle.ConstantTimeCompare(b, sum) == 1
}
if b, err := base64.StdEncoding.DecodeString(stored); err == nil && len(b) == len(sum) {
return subtle.ConstantTimeCompare(b, sum) == 1
}
return false
}
// Burn: the time a password check takes, for an unknown user
func Burn(password string) {
bcrypt.CompareHashAndPassword(dummyHash, []byte(password))
}
// Authenticate with each backend in turn: the name of the one that
// accepted the user, or why none did
func Authenticate(ctx context.Context, backends []Authenticator, user, password string, logf func(string, ...any)) (string, error) {
for _, a := range backends {
err := a.Authenticate(ctx, user, password)
switch {
case err == nil:
return a.Name(), nil
case errors.Is(err, ErrBadPassword):
return "", err
case errors.Is(err, ErrNoUser):
if err != ErrNoUser {
// known, but not one this backend lets in: why
logf("auth %s: %v", a.Name(), err)
}
continue
default:
// a backend that is down does not stop the others
logf("auth %s: %v", a.Name(), err)
}
}
Burn(password)
return "", ErrNoUser
}