The auth socket: the BBS's other logins ask modemmenu's backends

From claude/beautiful-pasteur-oz81no (af30cbd), brought onto this
branch without the build output it had committed (pbx-modem, 15 MB, now
in .gitignore).

[authd] listen: a unix socket where a program on this machine (the BBS)
asks modemmenu's backends (file, ldap, sql, system) for a user's
password, so that telnet, SSH and web logins there take the same one.
One JSON line each way: {"user","password"} -> {"ok","auth"} or
{"ok": false, "error": "denied"}.  The backends are asked as at the
login prompt, user_pattern kept, a refusal fail_delay late.

Who may ask: socket_mode (none for others: refused), socket_group, and
allow_users (the peer's uid, SO_PEERCRED); TCP is refused.  -serve
answers it with its sessions; -authd alone
(modemmenu-authd.service.sample).

With this branch's features: settings carry both [authd] and the access
sections; a signup's locked account is refused on the socket too (now
tested), and a password changed from the menu holds there at once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AFQhReUqUc7F5srk2hViqr
Claude-Session: https://claude.ai/code/session_01RvtV8Dg9kqRaakbTEfyH3f
This commit is contained in:
Claude committed 2026-10-15 02:34:28 +00:00
1 parent 329cf02304
commit afbc528dbe
9 files changed
+411 -2

No files matched your search

+1
View File
@@ -1 +1,2 @@
modemmenu
pbx-modem
+39 -2
View File
@@ -444,6 +444,37 @@ socket_mode = 0600
menu's user (`socket_mode`, `socket_group`). Without it, the other menu
asks the caller to log in again.
### The same password elsewhere: the auth socket
Callers who log in here reach the BBS already logged in. The same people
logging in to the BBS another way (telnet, SSH, its web forum) can use
the same password: the BBS asks modemmenu's backends through a unix
socket.
```
[authd]
listen = /run/modemmenu/auth.sock
socket_mode = 0660
socket_group = bbs
; and, closer: only these users' programs (by the peer's uid)
allow_users = bbs
```
`modemmenu -serve` answers it as well as its sessions; `modemmenu -authd`
answers it alone (modemmenu-authd.service.sample). One request a
connection, a JSON line each way:
```
{"user": "alice", "password": "..."}
{"ok": true, "auth": "ldap"} or {"ok": false, "error": "denied"}
```
The backends are asked as at the login prompt, `user_pattern` kept; a
refusal comes after `fail_delay`. Accounts locked in the users file (a
signup the sysop has not unlocked) are refused here too, and a password
changed from the menu (`mode = passwd`) is the one asked for at once. The BBS's side: its `[modemmenu]
auth_socket` (docs/wiki/Modem-Callers.md there).
## Security notes
- Asterisk usually runs as its own user: the users file (and
@@ -468,6 +499,10 @@ asks the caller to log in again.
connect gets a login prompt, and with `trust_user` a login as whoever
they name. Keep `socket_mode` and `socket_group` to Asterisk or the
front menu.
- The auth socket answers whether a password is right: whoever can
connect can guess passwords with it, each wrong one `fail_delay` late.
Keep it to the BBS's user (`socket_mode` 0660 or 0600, `socket_group`,
`allow_users`); a mode open to others is refused, and so is TCP.
- The log (syslog's auth facility by default) gets logins, failures and
selections, never passwords. It is never the line: the caller would
see it.
@@ -488,8 +523,10 @@ pending), refused and known numbers, and a selection hung up at the
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.
change, the next login with it, and a guest. The auth socket is
tested: right and wrong passwords, unknown, malformed and locked users,
`allow_users` and its settings. The system backend's uid, root and
group rules are tested with PAM replaced.
Two more tests run when their servers are given:
+213
View File
@@ -0,0 +1,213 @@
package main
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"os"
"os/signal"
"os/user"
"strconv"
"strings"
"syscall"
"time"
"golang.org/x/sys/unix"
)
// The auth socket: modemmenu's backends (file, ldap, sql, system) asked by
// a program on this machine for a user's password, so that the BBS's
// other logins (telnet, SSH, the web) take the same one. One request a
// connection, a JSON line each way:
//
// {"user": "alice", "password": "..."}
// {"ok": true, "auth": "ldap"} or {"ok": false, "error": "denied"}
//
// The socket's mode and group say who may ask; allow_users narrows it to
// those users (by the peer's uid). A refusal comes after fail_delay, as at
// the login prompt; user_pattern is kept.
// authdSettings: [authd]
type authdSettings struct {
listen string
socketMode os.FileMode
socketGroup string
allowUIDs map[uint32]bool // nil: whoever can connect
maxClients int
}
// authRequest and authReply are the socket's JSON.
type authRequest struct {
User string `json:"user"`
Password string `json:"password"`
}
type authReply struct {
OK bool `json:"ok"`
Auth string `json:"auth,omitempty"` // the backend that took it
Error string `json:"error,omitempty"` // denied, refused, bad request
}
const maxAuthRequest = 4096
func loadAuthd(sec *section) (*authdSettings, error) {
if sec.get("listen", "") == "" {
return nil, nil
}
a := &authdSettings{listen: sec.get("listen", ""), socketGroup: sec.get("socket_group", "")}
if !strings.HasPrefix(a.listen, "/") {
return nil, fmt.Errorf("[authd] listen: %q (an absolute path: a unix socket only, passwords cross it)", a.listen)
}
mode, err := strconv.ParseUint(sec.get("socket_mode", "0660"), 8, 32)
if err != nil || mode > 0o777 {
return nil, fmt.Errorf("[authd] socket_mode: %q (octal, e.g. 0660)", sec.get("socket_mode", ""))
}
if mode&0o007 != 0 {
return nil, fmt.Errorf("[authd] socket_mode: %04o lets anyone ask for passwords", mode)
}
a.socketMode = os.FileMode(mode)
if names := fields(sec.get("allow_users", "")); len(names) > 0 {
a.allowUIDs = map[uint32]bool{}
for _, n := range names {
u, err := user.Lookup(n)
if err != nil {
return nil, fmt.Errorf("[authd] allow_users: %s: %v", n, err)
}
uid, _ := strconv.ParseUint(u.Uid, 10, 32)
a.allowUIDs[uint32(uid)] = true
}
}
if a.maxClients, err = sec.int("max_clients", 16); err != nil {
return nil, err
}
if a.maxClients < 1 {
return nil, fmt.Errorf("[authd] max_clients: %d", a.maxClients)
}
return a, nil
}
// authd: modemmenu -authd, the auth socket alone, until SIGTERM.
func authd(s *settings) int {
if s.authd == nil {
fmt.Fprintln(os.Stderr, "modemmenu: -authd: no [authd] listen")
return 2
}
ln, err := listenAuth(s.authd)
if err != nil {
fmt.Fprintln(os.Stderr, "modemmenu:", err)
return 1
}
ch := make(chan os.Signal, 1)
signal.Notify(ch, syscall.SIGTERM, syscall.SIGINT, syscall.SIGHUP)
go func() {
sig := <-ch
logf("%v: stopping", sig)
ln.Close()
}()
serveAuth(s, ln)
return 0
}
func listenAuth(a *authdSettings) (net.Listener, error) {
ln, err := listen(&serverSettings{listen: a.listen, socketMode: a.socketMode, socketGroup: a.socketGroup})
if err != nil {
return nil, fmt.Errorf("[authd] %v", err)
}
logf("auth socket on %s", a.listen)
return ln, nil
}
// serveAuth answers on ln until it is closed.
func serveAuth(s *settings, ln net.Listener) {
slots := make(chan struct{}, s.authd.maxClients)
for {
conn, err := ln.Accept()
if err != nil {
if errors.Is(err, net.ErrClosed) {
return
}
logf("auth accept: %v", err)
time.Sleep(100 * time.Millisecond)
continue
}
select {
case slots <- struct{}{}:
default:
logf("auth: %d requests at once already, refused", s.authd.maxClients)
conn.Close()
continue
}
go func() {
defer func() { <-slots }()
answerAuth(s, conn)
}()
}
}
// peerUID is the uid of a unix socket's peer.
func peerUID(conn net.Conn) (uint32, bool) {
uc, ok := conn.(*net.UnixConn)
if !ok {
return 0, false
}
raw, err := uc.SyscallConn()
if err != nil {
return 0, false
}
var cred *unix.Ucred
raw.Control(func(fd uintptr) {
cred, _ = unix.GetsockoptUcred(int(fd), unix.SOL_SOCKET, unix.SO_PEERCRED)
})
if cred == nil {
return 0, false
}
return cred.Uid, true
}
func answerAuth(s *settings, conn net.Conn) {
defer conn.Close()
who := peer(conn)
reply := func(r authReply) {
b, _ := json.Marshal(r)
conn.Write(append(b, '\n'))
}
if s.authd.allowUIDs != nil {
if uid, ok := peerUID(conn); !ok || !s.authd.allowUIDs[uid] {
logf("auth request from %s: not an allowed user", who)
reply(authReply{Error: "refused"})
return
}
}
// one line, soon: a client that says less is not waited for
conn.SetReadDeadline(time.Now().Add(10 * time.Second))
line, err := bufio.NewReaderSize(io.LimitReader(conn, maxAuthRequest), maxAuthRequest).ReadSlice('\n')
conn.SetDeadline(time.Now().Add(time.Minute))
var req authRequest
if err != nil || json.Unmarshal(line, &req) != nil || req.User == "" {
logf("auth request from %s: bad request", who)
reply(authReply{Error: "bad request"})
return
}
var auth string
if s.userPattern.MatchString(req.User) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
auth, err = authenticate(ctx, s.backends, req.User, req.Password, logf)
cancel()
} else {
// not a name we take: the same answer, after the same time
burn(req.Password)
err = errNoUser
}
if err != nil {
logf("auth request from %s: user=%q denied (%v)", who, req.User, err)
time.Sleep(s.failDelay)
reply(authReply{Error: "denied"})
return
}
logf("auth request from %s: user=%s auth=%s", who, req.User, auth)
reply(authReply{OK: true, Auth: auth})
}
+108
View File
@@ -0,0 +1,108 @@
package main
import (
"encoding/json"
"fmt"
"net"
"os"
"path/filepath"
"strings"
"testing"
)
func authSettings(t *testing.T, extra string) (*settings, string) {
t.Helper()
dir := t.TempDir()
users := filepath.Join(dir, "users")
// pending: a signup the sysop has not unlocked
os.WriteFile(users, []byte("alice:{PLAIN}secret\npending:!{PLAIN}secret\n"), 0o600)
sock := filepath.Join(dir, "auth.sock")
p := filepath.Join(dir, "c.conf")
os.WriteFile(p, []byte(fmt.Sprintf("[general]\nauth = file\nfail_delay = 0\n[file]\npath = %s\n[authd]\nlisten = %s\nsocket_mode = 0600\n%s"+
"[item x]\nkey = X\ncommand = true\n", users, sock, extra)), 0o600)
s, err := loadSettings(p)
if err != nil {
t.Fatal(err)
}
return s, sock
}
func ask(t *testing.T, sock, body string) authReply {
t.Helper()
c, err := net.Dial("unix", sock)
if err != nil {
t.Fatal(err)
}
defer c.Close()
c.Write([]byte(body + "\n"))
var r authReply
if err := json.NewDecoder(c).Decode(&r); err != nil {
t.Fatalf("%s: %v", body, err)
}
return r
}
// TestAuthd: the auth socket answers by the backends, user_pattern kept.
func TestAuthd(t *testing.T) {
s, sock := authSettings(t, "")
ln, err := listenAuth(s.authd)
if err != nil {
t.Fatal(err)
}
defer ln.Close()
go serveAuth(s, ln)
if fi, err := os.Stat(sock); err != nil || fi.Mode().Perm() != 0o600 {
t.Fatalf("socket %v %v", fi, err)
}
for body, want := range map[string]authReply{
`{"user":"alice","password":"secret"}`: {OK: true, Auth: "file"},
`{"user":"alice","password":"wrong"}`: {Error: "denied"},
`{"user":"bob","password":"secret"}`: {Error: "denied"},
`{"user":"pending","password":"secret"}`: {Error: "denied"},
`{"user":"../etc","password":"secret"}`: {Error: "denied"},
`{"user":"","password":"secret"}`: {Error: "bad request"},
`not json`: {Error: "bad request"},
`{"user":"alice","password":"secret"`: {Error: "bad request"},
} {
if got := ask(t, sock, body); got != want {
t.Errorf("%s: %+v, want %+v", body, got, want)
}
}
}
// TestAuthdAllowUsers: a peer not among allow_users is refused before it
// is heard.
func TestAuthdAllowUsers(t *testing.T) {
if os.Getuid() == 65534 {
t.Skip("running as nobody")
}
s, sock := authSettings(t, "allow_users = nobody\n")
ln, err := listenAuth(s.authd)
if err != nil {
t.Fatal(err)
}
defer ln.Close()
go serveAuth(s, ln)
if got := ask(t, sock, `{"user":"alice","password":"secret"}`); got.OK || got.Error != "refused" {
t.Errorf("%+v", got)
}
}
func TestAuthdSettings(t *testing.T) {
for extra, want := range map[string]string{
"listen = tcp:127.0.0.1:9\n": "a unix socket only",
"socket_mode = 0666\n": "lets anyone ask",
"allow_users = no-such-user\n": "allow_users",
"max_clients = 0\n": "max_clients",
} {
dir := t.TempDir()
users := filepath.Join(dir, "users")
os.WriteFile(users, nil, 0o600)
p := filepath.Join(dir, "c.conf")
os.WriteFile(p, []byte("[general]\nauth = file\n[file]\npath = "+users+"\n[authd]\nlisten = /run/x.sock\n"+extra+
"[item x]\nkey = X\ncommand = true\n"), 0o600)
if _, err := loadSettings(p); err == nil || !strings.Contains(err.Error(), want) {
t.Errorf("%q: %v", extra, err)
}
}
}
+4
View File
@@ -41,6 +41,7 @@ func main() {
serveFlag := flag.Bool("serve", false, "serve sessions on the [server] listen socket")
listenAt := flag.String("listen", "", "with -serve: listen on this unix socket `path` (or tcp:host:port) instead of [server] listen")
upstreamFlag := flag.Bool("upstream", false, "a session of -serve with trust_user (internal)")
authdFlag := flag.Bool("authd", false, "answer the [authd] auth socket alone (with -serve it is answered too)")
flag.Parse()
if *hash {
@@ -58,6 +59,9 @@ func main() {
if err := openLog(s.log); err != nil {
fmt.Fprintln(os.Stderr, "modemmenu: log:", err)
}
if *authdFlag {
os.Exit(authd(s))
}
if *serveFlag {
if *listenAt != "" {
s.server.listen = *listenAt
+18
View File
@@ -0,0 +1,18 @@
# /etc/systemd/system/modemmenu-authd.service - modemmenu's auth socket
# alone ([authd]), for the BBS's other logins, where modemmenu runs from
# app_dmodem a call at a time and not as -serve (which answers it too)
[Unit]
Description=modemmenu: the auth socket for the BBS
Before=bbs.service
[Service]
ExecStart=/usr/local/bin/modemmenu -config /etc/asterisk/modemmenu.conf -authd
RuntimeDirectory=modemmenu
RuntimeDirectoryMode=0755
Restart=on-failure
# root for auth = system (PAM's pam_unix); otherwise a user of its own
# that can read modemmenu.conf and the users file
User=root
[Install]
WantedBy=multi-user.target
+12
View File
@@ -206,6 +206,18 @@ trust_user = no
; connections at once; more are told the lines are busy
max_sessions = 32
; The auth socket: the BBS's other logins (telnet, SSH, the web) ask the
; backends above for a user's password through it, so that it is the same
; one. Answered by -serve, or by -authd alone. Who may ask: socket_mode
; and socket_group, and allow_users (the peer's user)
;[authd]
;listen = /run/modemmenu/auth.sock
;socket_mode = 0660
;socket_group = bbs
;allow_users = bbs
; requests at once
;max_clients = 16
[menu]
title = "\r\nMain menu\r\n"
prompt = "\r\nSelection: "
+12
View File
@@ -127,6 +127,15 @@ func serve(s *settings, config string) int {
return 1
}
logf("serving on %s", srv.listen)
var authLn net.Listener
if s.authd != nil {
if authLn, err = listenAuth(s.authd); err != nil {
ln.Close()
fmt.Fprintln(os.Stderr, "modemmenu:", err)
return 1
}
go serveAuth(s, authLn)
}
var (
mu sync.Mutex
@@ -139,6 +148,9 @@ func serve(s *settings, config string) int {
sig := <-ch
logf("%v: stopping", sig)
ln.Close()
if authLn != nil {
authLn.Close()
}
}()
slots := make(chan struct{}, srv.maxSessions)
+4
View File
@@ -73,6 +73,7 @@ type settings struct {
signup signupSettings
callerID callerIDSettings
limits limitSettings
authd *authdSettings // nil: no auth socket
menuTitle string
menuPrompt string
hangup []string // what hangs up, upper case; the first one shown
@@ -156,6 +157,9 @@ func loadSettings(path string) (*settings, error) {
if err := loadAccess(c, s); err != nil {
return nil, err
}
if s.authd, err = loadAuthd(c.section("authd")); err != nil {
return nil, err
}
m := c.section("menu")
s.menuTitle = unescape(m.get("title", `\r\nMain menu\r\n`))