From da20bbd4ae3cba2a760f752ab25c294e449af20c Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 15 Oct 2026 19:51:33 +0000 Subject: [PATCH] LDAP groups, AD password changes, the time warning, the last callers - LDAP groups for the items' groups =: with [ldap] group_base, a group is an entry there that group_filter finds (groupOfNames, groupOfUniqueNames and posixGroup by default), searched as search_bind_dn or as the caller; each answer kept for the call. - [ldap] password_change = ad: mode = passwd changes an Active Directory password (unicodePwd's old value deleted, the new one added, quoted UTF-16LE), AD having no Password Modify. - time_warning (2m) before the time limit, time_warning_message is written on the line in the middle of a running selection, unless the item says time_warning = no (the sample's PPP does). - mode = callers: the last callers (time, user, rate; no caller ID), each login recorded in state_dir/callers (the latest 200) when there is such an item. - The sample's end has items to copy: ZMODEM uploads (rz -b -R -E), a Kermit server (kermit -Y -x), lynx -anonymous, mutt, tin, irssi, Gopher and the last callers; it loads with all of them on. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RvtV8Dg9kqRaakbTEfyH3f --- README.md | 53 +++++++++++++++++-- access.go | 60 ++++++++++++++++++---- access_test.go | 45 ++++++++++++++++ auth_ldap.go | 83 ++++++++++++++++++++++++++++-- callers.go | 117 ++++++++++++++++++++++++++++++++++++++++++ callers_test.go | 79 ++++++++++++++++++++++++++++ launch.go | 14 +++++ ldap_test.go | 68 ++++++++++++++++++++++++ main.go | 5 ++ modemmenu.conf.sample | 93 +++++++++++++++++++++++++++++++++ session.go | 2 + settings.go | 16 ++++-- 12 files changed, 615 insertions(+), 20 deletions(-) create mode 100644 callers.go create mode 100644 callers_test.go diff --git a/README.md b/README.md index 8df66d7..f61b1df 100644 --- a/README.md +++ b/README.md @@ -266,7 +266,7 @@ by an upstream menu does not say), and the password changes there: |---|---| | 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 | +| ldap | bound as the user, so the server's own password policy and hashing apply: the Password Modify extended operation (RFC 3062; OpenLDAP, 389 DS and most), or with `[ldap] password_change = ad` Active Directory's way, `unicodePwd`'s old value deleted and the new one added (AD takes it only over `ldaps://` or `starttls`) | | 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; @@ -314,13 +314,21 @@ selection to them). All the rules that are set must pass: | item option | | |---|---| | `users = alice bob` | these users ... | -| `groups = sysops` | ... or the members of these groups: `[groups]` (`sysops = alice bob`), or the system's groups for a login by `auth = system` | +| `groups = sysops` | ... or the members of these groups: `[groups]` (`sysops = alice bob`), the system's groups for a login by `auth = system`, or the directory's for a login by LDAP (with `[ldap] group_base`, below) | | `min_baud = 9600` | the connect rate towards the caller at least this; an unknown rate does not pass | | `callerids = 555*` | the caller ID matching one of these patterns | | `guest = yes` | guests see it too (they see nothing else) | An item without `users` or `groups` is for every logged-in caller. +LDAP groups count once `[ldap] group_base` is set: a group is an entry +under it that `group_filter` finds. The default filter, +`(&(cn={group})(|(member={dn})(uniqueMember={dn})(memberUid={user})))`, +takes `groupOfNames`, `groupOfUniqueNames` and `posixGroup` entries; +`{group}` is the item's group, `{dn}` the caller's entry, `{user}` their +name. The search runs as `search_bind_dn` if there is one, else as the +caller. Each group's answer is kept for the rest of the call. + ### Guests and new accounts With `[guest] enabled = yes`, its `name` (`guest`) at the login prompt @@ -372,6 +380,37 @@ connection is closed). `{time_left}` (whole minutes, empty without a limit) shows what is left, e.g. in `[menu] prompt`, and the selection gets it as `MODEM_TIME_LEFT`. +`time_warning` (2 minutes) before the limit, `time_warning_message` is +written on the line in the middle of what a running selection shows, +so that a caller in a BBS or a shell has time to finish. An item with +`time_warning = no` gets none: PPP should not (text between its frames), +and the sample's PPP item says so. + +### Last callers + +A `mode = callers` item shows the last callers (`count`, 10): the time, +the user and the connect rate of each login, the newest first. With +such an item, each login is recorded in `state_dir/callers` (the latest +200); the caller ID is not, since every caller sees the list. + +### More items + +The end of [modemmenu.conf.sample](modemmenu.conf.sample) has items to +copy, each needing its program: + +| item | program | +|---|---| +| upload | `rz -b -R -E` (lrzsz): ZMODEM uploads into the caller's `~/uploads`, binary, restricted, renaming rather than overwriting | +| kermit | `kermit -Y -x` (C-Kermit): a Kermit server in the caller's files; their terminal's Kermit GETs and SENDs | +| web | `lynx -anonymous`: the web as text, without shell or saving | +| mail, news | `mutt`, `tin -r` | +| chat | `irssi` on your own IRC server | +| gopher | lynx on Gopherspace, quick even at 2400 bit/s | +| callers | the last callers (above) | + +They run as the caller (`run_as = {user}`, so modemmenu as root) with a +cooked terminal (`tty = sane`), and return to the menu. + ### What the selection gets | placeholder | environment | | @@ -525,7 +564,10 @@ 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 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 +`allow_users` and its settings. The time warning is tested on a call +(and its absence with `time_warning = no`), the last callers list +(kept to 200, the newest first, no caller ID) on two calls, and Active +Directory's password encoding. The system backend's uid, root and group rules are tested with PAM replaced. Two more tests run when their servers are given: @@ -536,4 +578,7 @@ Two more tests run when their servers are given: - `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`), and that password changed and back (the server - must let users write their own `userPassword`). + must let users write their own `userPassword`); with + `ou=groups,dc=example,dc=com` holding `cn=sysops` (`groupOfNames`, + `member` lduser), `cn=dialup` (`posixGroup`, `memberUid` lduser) and + `cn=other` (without), LDAP groups too. diff --git a/access.go b/access.go index e6bf09f..ed184a9 100644 --- a/access.go +++ b/access.go @@ -1,6 +1,7 @@ package main import ( + "errors" "fmt" "path" "strconv" @@ -79,6 +80,10 @@ type limitSettings struct { timeLimit time.Duration // a call, from the login dailyLimit time.Duration // a user's calls in a day stateDir string // where the daily use is kept + // written to the line this long before the deadline, in a selection + // with time_warning + warning time.Duration + warningMessage string } func loadAccess(c *ini, s *settings) error { @@ -91,6 +96,11 @@ func loadAccess(c *ini, s *settings) error { return err } s.limits.stateDir = g.get("state_dir", "/var/lib/modemmenu") + if s.limits.warning, err = g.duration("time_warning", 2*time.Minute); err != nil { + return err + } + s.limits.warningMessage = unescape(g.get("time_warning_message", + `\r\n\r\n*** {time_left} minute(s) left in this call ***\r\n`)) if s.limits.dailyLimit > 0 && !strings.HasPrefix(s.limits.stateDir, "/") { return fmt.Errorf("[general] state_dir: %q (an absolute path)", s.limits.stateDir) } @@ -172,7 +182,7 @@ func checkAccess(s *settings) error { } for _, it := range s.items { for _, g := range it.access.groups { - if _, ok := s.groups[g]; !ok && !contains(s.auth, "system") && !contains(s.auth, "pam") { + if _, ok := s.groups[g]; !ok && !contains(s.auth, "system") && !contains(s.auth, "pam") && !s.ldapGroups() { return fmt.Errorf("[item %s] groups: no %s in [groups]", it.name, g) } } @@ -229,21 +239,43 @@ func (s *settings) numberRule(number string) *numberRule { return nil } -// inGroup: the session's user is a member of group, by [groups], or for a -// system account (auth = system) by the system's groups +// inGroup: the session's user is a member of group, by [groups]; for a +// system account (auth = system) by the system's groups; for an LDAP one +// by the directory's (with [ldap] group_base). The backends' answers are +// kept for the call. func (s *settings) inGroup(sess *session, group string) bool { if contains(s.groups[group], sess.User) { return true } - if sess.Auth != "system" && sess.Auth != "upstream:system" { + auth := strings.TrimPrefix(sess.Auth, "upstream:") + if auth != "system" && auth != "ldap" { return false } - acct, err := lookupNSS(sess.User) - if err != nil { - return false + if in, ok := sess.groupCache[group]; ok { + return in } - in, err := inGroupsNSS(acct, []string{group}) - return err == nil && in + var in bool + var err error + if auth == "system" { + var acct *account + if acct, err = lookupNSS(sess.User); err == nil { + in, err = inGroupsNSS(acct, []string{group}) + } + } else { + for _, b := range s.backends { + if la, ok := b.(*ldapAuth); ok { + in, err = la.memberOf(sess.User, sess.Password, group) + } + } + } + if err != nil && !errors.Is(err, errNoUser) { + logf("groups: %s in %s: %v", sess.User, group, err) + } + if sess.groupCache == nil { + sess.groupCache = map[string]bool{} + } + sess.groupCache[group] = in && err == nil + return sess.groupCache[group] } // allows: whether the session may see and use the item @@ -284,3 +316,13 @@ func (s *settings) visible(sess *session) []*menuItem { } return items } + +// ldapGroups: whether the LDAP backend has groups ([ldap] group_base) +func (s *settings) ldapGroups() bool { + for _, b := range s.backends { + if la, ok := b.(*ldapAuth); ok && la.groupBase != "" { + return true + } + } + return false +} diff --git a/access_test.go b/access_test.go index 15a014e..499e9da 100644 --- a/access_test.go +++ b/access_test.go @@ -384,3 +384,48 @@ func TestTimeLimits(t *testing.T) { t.Errorf("users file:\n%s", users) } } + +// the time_warning on the line while a selection runs, and not for an +// item with time_warning = no +func TestTimeWarning(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("bob:{PLAIN}secret\n"), 0o600) + conf := filepath.Join(dir, "c.conf") + os.WriteFile(conf, []byte(fmt.Sprintf(` +[general] +log = none +auth = file +time_limit = 4s +time_warning = 2s +time_warning_message = "\r\n*** {time_left} minute(s) left, {user} ***\r\n" +[file] +path = %s +[item nap] +command = exec sleep 30 +[item quiet] +time_warning = no +command = exec sleep 30 +`, users)), 0o600) + for _, c := range []struct { + item string + warn bool + }{{"nap", true}, {"quiet", false}} { + cl, cmd := callAs(t, bin, conf) + cl.expect("login: ") + cl.send("bob\r") + cl.expect("Password: ") + cl.send("secret\r") + cl.expect("Selection: ") + cl.send(c.item + "\r") + got := cl.expect("Your time is up.") + if warned := strings.Contains(got, "*** 0 minute(s) left, bob ***"); warned != c.warn { + t.Errorf("%s: warned %v, want %v:\n%q", c.item, warned, c.warn, got) + } + waitExit(t, cmd) + } +} diff --git a/auth_ldap.go b/auth_ldap.go index 01b228c..7b1d68c 100644 --- a/auth_ldap.go +++ b/auth_ldap.go @@ -10,6 +10,7 @@ import ( "os" "strings" "time" + "unicode/utf16" "github.com/go-ldap/ldap/v3" ) @@ -27,6 +28,13 @@ type ldapAuth struct { filter string searchDN string searchPass string + // groups for the items' groups = (group_base set): a group is an + // entry under group_base that group_filter finds + groupBase string + groupFilter string + // how a password is changed: exop (Password Modify) or ad + // (Active Directory's unicodePwd) + passwordChange string } func newLDAPAuth(s *section) (authenticator, error) { @@ -38,6 +46,13 @@ func newLDAPAuth(s *section) (authenticator, error) { filter: s.get("search_filter", "(uid={user})"), searchDN: s.get("search_bind_dn", ""), searchPass: s.get("search_bind_password", ""), + groupBase: s.get("group_base", ""), + groupFilter: s.get("group_filter", + "(&(cn={group})(|(member={dn})(uniqueMember={dn})(memberUid={user})))"), + passwordChange: strings.ToLower(s.get("password_change", "exop")), + } + if a.passwordChange != "exop" && a.passwordChange != "ad" { + return nil, fmt.Errorf("[ldap] password_change: %q (exop or ad)", a.passwordChange) } if a.startTLS, err = s.bool("starttls", false); err != nil { return nil, err @@ -166,16 +181,78 @@ func (a *ldapAuth) userDN(conn *ldap.Conn, user string) (string, error) { 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 +// changePassword bound as the user, so that the server applies its own +// password policy: by the Password Modify extended operation (RFC 3062), +// or for Active Directory (password_change = ad, which does not have it) +// by replacing unicodePwd, the old value deleted and the new one added +// (which AD takes only over TLS: ldaps:// or starttls) func (a *ldapAuth) changePassword(_ context.Context, _ *term, user, old, new string) error { conn, dn, err := a.bindUser(user, old) if err != nil { return err } defer conn.Close() - if _, err := conn.PasswordModify(ldap.NewPasswordModifyRequest(dn, old, new)); err != nil { + if a.passwordChange == "ad" { + err = conn.Modify(adPasswordChange(dn, old, new)) + } else { + _, err = conn.PasswordModify(ldap.NewPasswordModifyRequest(dn, old, new)) + } + if err != nil { return fmt.Errorf("%w: %v", errRefused, err) } return nil } + +// adPasswordChange: AD's change of a user's own password, unicodePwd's +// old value deleted and the new one added, each in "quotes" as UTF-16LE +func adPasswordChange(dn, old, new string) *ldap.ModifyRequest { + m := ldap.NewModifyRequest(dn, nil) + m.Delete("unicodePwd", []string{adPassword(old)}) + m.Add("unicodePwd", []string{adPassword(new)}) + return m +} + +func adPassword(pw string) string { + u := utf16.Encode([]rune(`"` + pw + `"`)) + b := make([]byte, 2*len(u)) + for i, c := range u { + b[2*i] = byte(c) + b[2*i+1] = byte(c >> 8) + } + return string(b) +} + +// memberOf: whether user is in group, an entry under group_base that +// group_filter ({group}, the user's {dn} and {user}) finds; searched as +// search_bind_dn, else as the user (with their password), else +// anonymously. errNoUser without group_base: LDAP has no groups here. +func (a *ldapAuth) memberOf(user, password, group string) (bool, error) { + if a.groupBase == "" { + return false, errNoUser + } + var conn *ldap.Conn + var dn string + var err error + if a.searchDN == "" && password != "" { + conn, dn, err = a.bindUser(user, password) + } else { + if conn, err = a.dial(); err == nil { + // userDN binds as search_bind_dn when there is one + if dn, err = a.userDN(conn, user); err != nil { + conn.Close() + } + } + } + if err != nil { + return false, err + } + defer conn.Close() + filter := expand(a.groupFilter, map[string]string{"group": group, "dn": dn, "user": user}, ldap.EscapeFilter) + res, err := conn.Search(ldap.NewSearchRequest(a.groupBase, ldap.ScopeWholeSubtree, + ldap.NeverDerefAliases, 1, int(a.timeout/time.Second), false, + filter, []string{"dn"}, nil)) + if err != nil { + return false, fmt.Errorf("group search %s: %v", filter, err) + } + return len(res.Entries) > 0, nil +} diff --git a/callers.go b/callers.go new file mode 100644 index 0000000..8f53454 --- /dev/null +++ b/callers.go @@ -0,0 +1,117 @@ +package main + +import ( + "fmt" + "os" + "path/filepath" + "strings" + "time" + + "golang.org/x/sys/unix" +) + +// The last callers: each login as a line of state_dir/callers (the time, +// the user, the rate; not the caller ID, which other callers would see), +// the latest callersKept of them kept, for mode = callers items. + +const callersKept = 200 + +func callersPath(dir string) string { return filepath.Join(dir, "callers") } + +// recordCaller: sess's login into the list, under a lock (calls at once) +func recordCaller(dir string, sess *session, now time.Time) error { + if err := os.MkdirAll(dir, 0o700); err != nil { + return err + } + f, err := os.OpenFile(callersPath(dir), os.O_RDWR|os.O_CREATE, 0o600) + 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()) + f.ReadAt(b, 0) + clean := func(s string) string { + return strings.Map(func(r rune) rune { + if r == '\t' || r == '\n' || r == '\r' { + return ' ' + } + return r + }, s) + } + lines := strings.Split(strings.TrimRight(string(b), "\n"), "\n") + if lines[0] == "" { + lines = nil + } + lines = append(lines, fmt.Sprintf("%s\t%s\t%s", now.Format(time.RFC3339), clean(sess.User), clean(sess.Baud))) + if len(lines) > callersKept { + lines = lines[len(lines)-callersKept:] + } + out := []byte(strings.Join(lines, "\n") + "\n") + if _, err := f.WriteAt(out, 0); err != nil { + return err + } + return f.Truncate(int64(len(out))) +} + +// lastCallers: the latest n, the newest first +func lastCallers(dir string, n int) ([][3]string, error) { + b, err := os.ReadFile(callersPath(dir)) + if os.IsNotExist(err) { + return nil, nil + } + if err != nil { + return nil, err + } + lines := strings.Split(strings.TrimRight(string(b), "\n"), "\n") + var out [][3]string + for i := len(lines) - 1; i >= 0 && len(out) < n; i-- { + p := strings.SplitN(lines[i], "\t", 3) + if len(p) == 3 { + out = append(out, [3]string{p[0], p[1], p[2]}) + } + } + return out, nil +} + +// callersItem: mode = callers, the last count callers on the line +func callersItem(t *term, s *settings, it *menuItem) error { + list, err := lastCallers(s.limits.stateDir, it.count) + if err != nil { + logf("callers: %v", err) + } + var b strings.Builder + b.WriteString("\r\nLast callers\r\n\r\n") + if len(list) == 0 { + b.WriteString(" (none yet)\r\n") + } + for _, c := range list { + when := c[0] + if tm, err := time.Parse(time.RFC3339, c[0]); err == nil { + when = tm.Local().Format("2006-01-02 15:04") + } + rate := c[2] + if rate != "" { + rate += " bit/s" + } + fmt.Fprintf(&b, " %s %-16s %s\r\n", when, c[1], rate) + } + return t.write(b.String()) +} + +// hasCallers: whether an item shows the last callers (logins are only +// recorded then) +func (s *settings) hasCallers() bool { + for _, it := range s.items { + if it.mode == "callers" { + return true + } + } + return false +} diff --git a/callers_test.go b/callers_test.go new file mode 100644 index 0000000..00d7e24 --- /dev/null +++ b/callers_test.go @@ -0,0 +1,79 @@ +package main + +import ( + "fmt" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func TestCallersList(t *testing.T) { + dir := t.TempDir() + start := time.Date(2026, 10, 15, 20, 0, 0, 0, time.UTC) + for i := 0; i < callersKept+5; i++ { + s := &session{User: fmt.Sprintf("u%d", i), Baud: "33600"} + if i == 3 { + s.User = "tab\tand\nline" + } + if err := recordCaller(dir, s, start.Add(time.Duration(i)*time.Minute)); err != nil { + t.Fatal(err) + } + } + b, _ := os.ReadFile(callersPath(dir)) + if n := strings.Count(string(b), "\n"); n != callersKept { + t.Errorf("%d kept, want %d", n, callersKept) + } + last, err := lastCallers(dir, 3) + if err != nil || len(last) != 3 || last[0][1] != fmt.Sprintf("u%d", callersKept+4) || last[2][1] != fmt.Sprintf("u%d", callersKept+2) { + t.Errorf("last %v %v", last, err) + } + if strings.Contains(string(b), "tab\tand") { + t.Error("a tab in a name made it into the list") + } + if l, err := lastCallers(t.TempDir(), 5); err != nil || len(l) != 0 { + t.Errorf("no list yet: %v %v", l, err) + } +} + +func TestCallersLine(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}secret\nbob:{PLAIN}secret\n"), 0o600) + conf := filepath.Join(dir, "c.conf") + os.WriteFile(conf, []byte(fmt.Sprintf(` +[general] +log = none +auth = file +state_dir = %s +[file] +path = %s +[item callers] +key = LC +mode = callers +count = 5 +`, filepath.Join(dir, "state"), users)), 0o600) + for _, u := range []string{"alice", "bob"} { + c, cmd := callAs(t, bin, conf, "DMODEM_RATE=26400/26400", "DMODEM_CALLERID=5559999") + c.expect("login: ") + c.send(u + "\r") + c.expect("Password: ") + c.send("secret\r") + c.expect("Selection: ") + c.send("lc\r") + got := c.expect("Selection: ") + if u == "bob" { + bi, ai := strings.Index(got, "bob "), strings.Index(got, "alice ") + if bi < 0 || ai < 0 || bi > ai || !strings.Contains(got, "26400 bit/s") || strings.Contains(got, "5559999") { + t.Errorf("bob's list:\n%s", got) + } + } + c.send("g\r") + waitExit(t, cmd) + } +} diff --git a/launch.go b/launch.go index a12cf40..9066541 100644 --- a/launch.go +++ b/launch.go @@ -21,9 +21,23 @@ 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, cfg *settings, it *menuItem, s *session, deadline time.Time, logf func(string, ...any)) error { + // the time_warning before the deadline, on the line in the middle of + // what the selection says + if warn := cfg.limits.warning; warn > 0 && it.timeWarning && !deadline.IsZero() && + time.Until(deadline) > warn { + timer := time.AfterFunc(time.Until(deadline)-warn, func() { + v := s.vars(false) + v["time_left"] = strconv.Itoa(int((time.Until(deadline) + 30*time.Second) / time.Minute)) + t.write(expand(cfg.limits.warningMessage, v, nil)) + logf("%s: time warning user=%s", it.name, s.User) + }) + defer timer.Stop() + } switch it.mode { case "passwd": return changePasswordItem(t, cfg, it, s, deadline) + case "callers": + return callersItem(t, cfg, it) case "exec": return runExec(t, it, s, deadline, logf) default: diff --git a/ldap_test.go b/ldap_test.go index 4cad077..a708930 100644 --- a/ldap_test.go +++ b/ldap_test.go @@ -4,7 +4,11 @@ import ( "context" "errors" "os" + "path/filepath" + "strings" "testing" + + "github.com/go-ldap/ldap/v3" ) // MODEMMENU_TEST_LDAP=ldap://host:port of a server with @@ -37,3 +41,67 @@ func TestLDAP(t *testing.T) { } } } + +func TestADPassword(t *testing.T) { + // "pw" in quotes, UTF-16LE + if got := adPassword("pw"); got != "\x22\x00p\x00w\x00\x22\x00" { + t.Errorf("% x", got) + } + if got := adPassword("é"); got != "\x22\x00\xe9\x00\x22\x00" { + t.Errorf("% x", got) + } + m := adPasswordChange("cn=a,dc=x", "old", "new") + if len(m.Changes) != 2 || m.Changes[0].Operation != ldap.DeleteAttribute || + m.Changes[1].Operation != ldap.AddAttribute || + m.Changes[1].Modification.Vals[0] != adPassword("new") { + t.Errorf("modify %+v", m.Changes) + } +} + +// MODEMMENU_TEST_LDAP, with ou=groups,dc=example,dc=com holding +// cn=sysops (groupOfNames, member lduser) and cn=dialup (posixGroup, +// memberUid lduser) and cn=other (without lduser) +func TestLDAPGroups(t *testing.T) { + url := os.Getenv("MODEMMENU_TEST_LDAP") + if url == "" { + t.Skip("MODEMMENU_TEST_LDAP is not set") + } + for _, vals := range []map[string]string{ + {"url": url, "search_base": "ou=people,dc=example,dc=com", "group_base": "ou=groups,dc=example,dc=com"}, + {"url": url, "bind_dn": "uid={user},ou=people,dc=example,dc=com", "group_base": "ou=groups,dc=example,dc=com"}, + } { + a, err := newLDAPAuth(§ion{name: "ldap", vals: vals}) + if err != nil { + t.Fatal(err) + } + la := a.(*ldapAuth) + for group, want := range map[string]bool{"sysops": true, "dialup": true, "other": false, "nothere": false} { + if in, err := la.memberOf("lduser", "ldpass", group); err != nil || in != want { + t.Errorf("%v: lduser in %s: %v %v, want %v", vals, group, in, err, want) + } + } + } + a, _ := newLDAPAuth(§ion{name: "ldap", vals: map[string]string{"url": url, "search_base": "ou=people,dc=example,dc=com"}}) + if _, err := a.(*ldapAuth).memberOf("lduser", "ldpass", "sysops"); !errors.Is(err, errNoUser) { + t.Errorf("without group_base: %v", err) + } + + // an item for sysops, through settings, a login by ldap + dir := t.TempDir() + p := filepath.Join(dir, "c.conf") + os.WriteFile(p, []byte("[general]\nauth = ldap\n[ldap]\nurl = "+url+ + "\nsearch_base = ou=people,dc=example,dc=com\ngroup_base = ou=groups,dc=example,dc=com\n"+ + "[item ops]\ngroups = sysops\ncommand = true\n[item away]\ngroups = other\ncommand = true\n"), 0o600) + s, err := loadSettings(p) + if err != nil { + t.Fatal(err) + } + sess := &session{User: "lduser", Password: "ldpass", Auth: "ldap"} + var names []string + for _, it := range s.visible(sess) { + names = append(names, it.name) + } + if strings.Join(names, " ") != "ops" { + t.Errorf("lduser sees %v", names) + } +} diff --git a/main.go b/main.go index 05ca76d..0707b40 100644 --- a/main.go +++ b/main.go @@ -206,6 +206,11 @@ func run(t *term, s *settings, sess *session) int { } setAtExit(lim.done) defer lim.done() + if s.hasCallers() { + if err := recordCaller(s.limits.stateDir, sess, time.Now()); err != nil { + logf("callers: %v", err) + } + } sess.TimeLeft = lim.timeLeft(time.Now()) t.write(expand(s.welcome, sess.vars(false), nil)) diff --git a/modemmenu.conf.sample b/modemmenu.conf.sample index 6d4a6d9..57ced81 100644 --- a/modemmenu.conf.sample +++ b/modemmenu.conf.sample @@ -79,6 +79,10 @@ user_pattern = ^[A-Za-z0-9][A-Za-z0-9._@-]{0,63}$ time_limit = 0 daily_limit = 0 state_dir = /var/lib/modemmenu +; this long before the limit, the message is written on the line in the +; middle of a running selection (not one with time_warning = no); 0: none +time_warning = 2m +time_warning_message = "\r\n\r\n*** {time_left} minute(s) left in this call ***\r\n" ; groups of users for the items' groups = (members of system groups count ; too, for logins by auth = system) @@ -142,6 +146,16 @@ search_base = ou=people,dc=example,dc=com search_filter = (&(objectClass=posixAccount)(uid={user})) ;search_bind_dn = cn=modem,ou=services,dc=example,dc=com ;search_bind_password = secret +; groups for the items' groups = (no group_base: LDAP has none): a group +; is an entry under group_base that group_filter finds, {group} the item's +; group, {dn} the caller's entry, {user} their name; searched as +; search_bind_dn, else as the caller +;group_base = ou=groups,dc=example,dc=com +;group_filter = (&(cn={group})(|(member={dn})(uniqueMember={dn})(memberUid={user}))) +; how mode = passwd changes a password: exop (Password Modify, RFC 3062; +; OpenLDAP, 389 DS and most), or ad (Active Directory's unicodePwd, over +; ldaps:// or starttls only) +;password_change = exop ; system: the accounts of this machine, by PAM: the auth and account stacks ; of pam_service (modemmenu.pam.sample as /etc/pam.d/modemmenu), so local @@ -238,6 +252,9 @@ hotkeys = no ; mode = exec a program on the line: command (by /bin/sh -c) ; passwd built in: the caller changes their password ; (min_password = 8 characters) +; callers built in: the last callers (count = 10), the time, +; user and rate of each login (state_dir/callers, +; the latest 200; kept only with such an item) ; 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 @@ -292,6 +309,8 @@ key = P aliases = dialup net min_baud = 9600 label = PPP (dial-up networking) +; no time warning in the middle of PPP's frames +time_warning = no 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} @@ -325,3 +344,77 @@ after = menu ;path = /run/modemmenu/more.sock ;header = yes ;after = menu + +; More items, to copy into items = above. Each needs its program installed; +; run_as = {user} (modemmenu as root) keeps callers in their own accounts. + +; who called last +;[item callers] +;key = LC +;label = Last callers +;mode = callers +;count = 10 + +; files by ZMODEM (lrzsz): rz receives what the caller's terminal sends, +; binary, restricted to the directory, renaming rather than overwriting +;[item upload] +;key = U +;label = Upload a file (ZMODEM) +;run_as = {user} +;command = cd "$HOME/uploads" && exec rz -b -R -E +;after = menu +; files by Kermit (C-Kermit): a Kermit server in the caller's files; their +; terminal's Kermit GETs and SENDs, then FINISH returns to the menu +;[item kermit] +;key = K +;label = Kermit file server +;run_as = {user} +;tty = sane +;command = cd "$HOME" && exec kermit -Y -x +;after = menu + +; the web as text: lynx with the anonymous account's restrictions (no +; shell, no saving files); w3m is the other choice +;[item web] +;key = W +;label = The web (lynx) +;run_as = {user} +;tty = sane +;command = exec lynx -anonymous https://example.org/ +;after = menu + +; mail and news in the caller's account +;[item mail] +;key = M +;label = Mail +;groups = dialup +;run_as = {user} +;tty = sane +;pass_password = no +;command = exec mutt +;after = menu +;[item news] +;key = N +;label = Usenet news +;run_as = {user} +;tty = sane +;command = exec tin -r +;after = menu + +; chat among callers on your own IRC server +;[item chat] +;key = C +;label = Chat (IRC) +;run_as = {user} +;tty = sane +;command = exec irssi -c 127.0.0.1 -n {user} +;after = menu + +; Gopher: quick even at 2400 bit/s +;[item gopher] +;key = GO +;label = Gopherspace +;run_as = {user} +;tty = sane +;command = exec lynx -anonymous gopher://gopher.floodgap.com/ +;after = menu diff --git a/session.go b/session.go index 30a1a69..498eb5f 100644 --- a/session.go +++ b/session.go @@ -26,6 +26,8 @@ type session struct { Connected time.Time `json:"connected"` Selection string `json:"selection"` TimeLeft string `json:"time_left"` // whole minutes; "": no limit + + groupCache map[string]bool // the backends' group answers, for the call } // newSession from app_dmodem's environment (DMODEM_RATE "tx/rx", diff --git a/settings.go b/settings.go index 25df5fe..3669d53 100644 --- a/settings.go +++ b/settings.go @@ -51,7 +51,9 @@ type menuItem struct { after string // hangup, menu timeout time.Duration access itemAccess - minPassword int // mode = passwd + minPassword int // mode = passwd + timeWarning bool // the time_warning is written on the line + count int // mode = callers: how many } // serverSettings: [server], for modemmenu -serve @@ -252,7 +254,7 @@ func loadItem(name string, sec *section) (*menuItem, error) { it.runAs = sec.get("run_as", "") it.tty = strings.ToLower(sec.get("tty", "raw")) defAfter := "hangup" - if strings.EqualFold(sec.get("mode", ""), "passwd") { + if m := strings.ToLower(sec.get("mode", "")); m == "passwd" || m == "callers" { // a password changed is no reason to hang up defAfter = "menu" } @@ -260,6 +262,12 @@ func loadItem(name string, sec *section) (*menuItem, error) { if it.minPassword, err = sec.int("min_password", 8); err != nil { return nil, err } + if it.timeWarning, err = sec.bool("time_warning", true); err != nil { + return nil, err + } + if it.count, err = sec.int("count", 10); err != nil { + return nil, err + } if it.password, err = sec.bool("pass_password", true); err != nil { return nil, err } @@ -284,7 +292,7 @@ func loadItem(name string, sec *section) (*menuItem, error) { return nil, err } switch it.mode { - case "passwd": + case "passwd", "callers": // built in: no command, no server case "exec": if it.command == "" { @@ -301,7 +309,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, rlogin or passwd)", name, it.mode) + return nil, fmt.Errorf("[item %s] mode: %q (exec, tcp, unix, telnet, rlogin, passwd or callers)", name, it.mode) } if it.tty != "raw" && it.tty != "sane" { return nil, fmt.Errorf("[item %s] tty: %q (raw or sane)", name, it.tty)