commit f194490fa337b5380bbcba14de86d5431342b265 Author: Claude Date: Sat Oct 10 00:34:46 2026 +0000 modemmenu: a login and menu for dial-up callers A Go program that D-Modem-RE's app_dmodem runs as a mode = exec profile on the caller's line: it asks for a user name and password, checks them with a text file, LDAP (bind as the user, directly or after a search) or an SQL database (MySQL/MariaDB, PostgreSQL, SQLite), then offers a menu of a BBS, PPP and a shell. The selection gets the user name, password, the backend that accepted them, the dialed number, caller ID, connect rate and the connection's date and time: as MODEM_* in its environment, as shell-quoted {placeholders} in its command, in an optional 0600 session file, in the rlogin handshake (the way BBSs log a caller in), or sent after connecting to a raw TCP or telnet server. Moved here from D-Modem-RE's modemmenu/. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RvtV8Dg9kqRaakbTEfyH3f diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8936e6b --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +modemmenu diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..b12a720 --- /dev/null +++ b/Makefile @@ -0,0 +1,31 @@ +# modemmenu: the login and menu of a dial-up line (Go 1.22 or later) +# +# make build +# make test the tests +# make install into $(BINDIR), samples into $(CONF_DIR) + +GO ?= go +BINDIR ?= /usr/local/bin +CONF_DIR ?= /etc/asterisk + +all: modemmenu + +modemmenu: FORCE + $(GO) build -o $@ . + +test: + $(GO) vet ./... + $(GO) test ./... + +install: modemmenu + install -D -m 755 modemmenu $(DESTDIR)$(BINDIR)/modemmenu + [ -e $(DESTDIR)$(CONF_DIR)/modemmenu.conf ] || \ + install -D -m 640 modemmenu.conf.sample $(DESTDIR)$(CONF_DIR)/modemmenu.conf + [ -e $(DESTDIR)$(CONF_DIR)/modemmenu.users ] || \ + install -D -m 600 modemmenu.users.sample $(DESTDIR)$(CONF_DIR)/modemmenu.users + +clean: + rm -f modemmenu + +FORCE: +.PHONY: all test install clean FORCE diff --git a/README.md b/README.md new file mode 100644 index 0000000..bd4b073 --- /dev/null +++ b/README.md @@ -0,0 +1,188 @@ +# modemmenu: a login and menu for dial-up callers + +`modemmenu` is the first thing a caller sees once the modems are +connected. It asks for a user name and password, checks them against a +text file, LDAP or an SQL database (MySQL/MariaDB, PostgreSQL, SQLite), +and then offers a menu: + +``` +Welcome to D-Modem. + +login: alice +Password: ****** + +Hello alice, connected at 33600 bit/s on 2026-10-10 21:05:09. + +Main menu + + [B] Bulletin board + [P] PPP (dial-up networking) + [S] Shell + [G] Goodbye (hang up) + +Selection: +``` + +The selection starts with the caller's credentials and the details of +the call: user name, password, the backend that accepted them, the dialed +number, the caller ID, the connect rate and the date and time of the +connection. + +## Running it from app_dmodem + +`app_dmodem`, the Asterisk module of +[D-Modem-RE](https://github.com/Neo-Desktop/D-Modem-RE) (`asterisk/`), runs +it as a `mode = exec` program on the caller's line: + +``` +; dmodem.conf +[menu] +mode = exec +command = exec /usr/local/bin/modemmenu -config /etc/asterisk/modemmenu.conf + +; extensions.conf +exten => 5551000,1,DModem(menu) + same => n,Hangup() +``` + +It reads the call's details from app_dmodem's environment: +`DMODEM_RATE` (tx/rx bit/s), `DMODEM_CALLERID`, `DMODEM_DIALED`, +`DMODEM_CHANNEL` and `DMODEM_PROFILE` (`DMODEM_DIALED` needs an +app_dmodem that sets it; without it, or under another getty, pass +`-dialed`). `-rate`, `-callerid` and +`-dialed` set them instead, e.g. under a getty on another modem. +The line is raw (app_dmodem's pty): modemmenu echoes and edits what the +caller types itself. Its exit, like the selection's, hangs up the call. + +## Building + +Go 1.22 or later: + +``` +make # or: go build +make test +make install # /usr/local/bin/modemmenu, and the samples into + # /etc/asterisk if there are none +``` + +## Configuration + +[modemmenu.conf.sample](modemmenu.conf.sample) has every option. In +short: + +``` +[general] +auth = file ldap sql ; the backends, asked in this order + +[file] +path = /etc/asterisk/modemmenu.users + +[item bbs] +key = B +label = Bulletin board +mode = rlogin +host = 127.0.0.1 +after = menu + +[item ppp] +key = P +label = PPP +mode = exec +command = exec /usr/sbin/pppd nodetach noauth local lock passive 192.168.77.1:192.168.77.2 ipparam {user} + +[item shell] +key = S +label = Shell +mode = exec +run_as = {user} +tty = sane +command = exec "$SHELL" -l +``` + +`modemmenu -check -config FILE` checks a configuration. + +### Authentication + +A backend that does not know the user hands over to the next; one that +knows the user and finds the password wrong ends the attempt there. A +backend that is down (LDAP unreachable, SQL error) is logged and skipped. + +- **file**: `user:password` lines. The password is a bcrypt hash + (`modemmenu -hash` prints one), `{SHA256}`/`{SHA512}` (hex or base64), + `{SSHA256}`/`{SSHA512}` (salted, base64) or `{PLAIN}text`. The file is + read at each login. +- **ldap**: a bind as the user, either to `bind_dn` with `{user}` in it, + or to the entry `search_filter` finds under `search_base`. ldaps://, + StartTLS and a private CA are supported; a group check goes in the + filter (`memberOf=...`). Values are escaped for DNs and filters. +- **sql**: `query` with the user (and optionally the password) as + arguments returns the stored password, checked like the file's; or with + `hash = none` any row means the login is right, for a database that + checks passwords itself (`crypt()` in PostgreSQL). + +User names must match `user_pattern` (letters, digits, `._@-` by default); +wrong logins wait `fail_delay` seconds, unknown users take as long as +known ones, and the call is hung up after `attempts` tries or +`login_timeout`. + +### What the selection gets + +| placeholder | environment | | +|---|---|---| +| `{user}` | `MODEM_USER` | the user name | +| `{password}` | `MODEM_PASSWORD` | the password (not with `pass_password = no`) | +| `{auth}` | `MODEM_AUTH` | `file`, `ldap` or `sql` | +| `{dialed}` | `MODEM_DIALED` | the number dialed | +| `{callerid}` | `MODEM_CALLERID` | the caller's number | +| `{baud}` | `MODEM_BAUD` | the connect rate towards the caller, bit/s | +| `{rate}`, `{tx_rate}`, `{rx_rate}` | `MODEM_RATE`, `MODEM_TX_RATE`, `MODEM_RX_RATE` | both rates | +| `{date}`, `{time}` | `MODEM_DATE`, `MODEM_TIME` | the connection's date and time | +| `{datetime}`, `{epoch}` | `MODEM_DATETIME`, `MODEM_EPOCH` | the same, RFC 3339 and Unix time | +| `{channel}`, `{profile}` | `MODEM_CHANNEL`, `MODEM_PROFILE` | app_dmodem's channel and profile | +| `{selection}` | `MODEM_SELECTION` | the item chosen | + +How it reaches each kind of selection: + +- **exec** (`command`, by `/bin/sh -c`): the environment, the + placeholders in the command (each one a shell-quoted word already, so + `{user}` and not `"{user}"`), and with `session_file = yes` all of it + as JSON in a 0600 file named by `MODEM_SESSION_FILE`, removed when the + program ends. `run_as` runs it as a system user (modemmenu must be + root), `tty = sane` gives it a cooked terminal. +- **rlogin**: the RFC 1282 handshake; by default the password as the + client user, the user name as the server user and `ansi/{baud}` as the + terminal, which is how Synchronet, Mystic and other BBSs log a caller + in without asking again. +- **tcp** and **telnet**: `send`, e.g. `send = "{user}\r{password}\r"`, + is sent once connected; telnet negotiates binary, echo and the + terminal type. + +`after = menu` returns to the menu when the selection ends, `after = +hangup` (the default) hangs up. + +## Security notes + +- Asterisk usually runs as its own user: the users file (and + modemmenu.conf, which may hold database and LDAP passwords) must be + readable by it, and by no one else. `run_as` needs modemmenu to run as + root, which app_dmodem only does when Asterisk does. + +- The password goes to the selection unless `pass_password = no`. In + the environment it is readable by the same user and root + (`/proc/PID/environ`); `session_file` keeps it out of the environment + if the program reads the file instead. +- Never put `{password}` in a command line: other users see the + arguments of every process. Use `MODEM_PASSWORD` or the session file. +- 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. + +## Tests + +`make test` checks the password schemes, the file and SQLite backends +and the telnet client, and runs modemmenu on a pty as app_dmodem does: a +wrong and a right login, an rlogin BBS and back to the menu, and an exec +selection's environment and session file. +`MODEMMENU_TEST_LDAP=ldap://host:port` also tests the LDAP backend +against a server with `uid=lduser,ou=people,dc=example,dc=com` +(password `ldpass`). diff --git a/auth.go b/auth.go new file mode 100644 index 0000000..bd06d72 --- /dev/null +++ b/auth.go @@ -0,0 +1,132 @@ +package main + +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): + continue + default: + // a backend that is down does not stop the others + logf("auth %s: %v", a.name(), err) + } + } + burn(password) + return "", errNoUser +} diff --git a/auth_file.go b/auth_file.go new file mode 100644 index 0000000..1ed32d1 --- /dev/null +++ b/auth_file.go @@ -0,0 +1,65 @@ +package main + +import ( + "bufio" + "context" + "fmt" + "os" + "strings" +) + +// fileAuth: a text file of user:password lines (the password hashed as +// checkPassword reads it; # comments), read at each login so that edits +// take effect at once +type fileAuth struct { + path string + scheme string +} + +func newFileAuth(s *section) (authenticator, error) { + a := &fileAuth{ + path: s.get("path", "/etc/asterisk/modemmenu.users"), + scheme: strings.ToLower(s.get("hash", "auto")), + } + if _, err := os.Stat(a.path); err != nil { + return nil, fmt.Errorf("[file] path: %v", err) + } + return a, nil +} + +func (a *fileAuth) name() string { return "file" } + +func (a *fileAuth) authenticate(_ context.Context, user, password string) error { + f, err := os.Open(a.path) + if err != nil { + return err + } + defer f.Close() + sc := bufio.NewScanner(f) + for sc.Scan() { + line := strings.TrimSpace(sc.Text()) + if line == "" || line[0] == '#' { + continue + } + name, stored, ok := strings.Cut(line, ":") + if !ok || name != user { + continue + } + // user:hash[:anything else, e.g. a full name] + if a.scheme != "plain" && !strings.HasPrefix(stored, "{") { + stored, _, _ = strings.Cut(stored, ":") + } + ok, err := checkPassword(stored, password, a.scheme) + if err != nil { + return fmt.Errorf("%s: user %s: %v", a.path, user, err) + } + if !ok { + return errBadPassword + } + return nil + } + if err := sc.Err(); err != nil { + return err + } + return errNoUser +} diff --git a/auth_ldap.go b/auth_ldap.go new file mode 100644 index 0000000..4e7fd47 --- /dev/null +++ b/auth_ldap.go @@ -0,0 +1,139 @@ +package main + +import ( + "context" + "crypto/tls" + "crypto/x509" + "errors" + "fmt" + "net" + "os" + "strings" + "time" + + "github.com/go-ldap/ldap/v3" +) + +// ldapAuth: a bind as the user, to bind_dn with {user} in it, or to the +// DN that search_filter finds under search_base (searched as +// search_bind_dn, anonymously if none) +type ldapAuth struct { + url string + startTLS bool + tls *tls.Config + timeout time.Duration + bindDN string + base string + filter string + searchDN string + searchPass string +} + +func newLDAPAuth(s *section) (authenticator, error) { + var err error + a := &ldapAuth{ + url: s.get("url", "ldap://127.0.0.1:389"), + bindDN: s.get("bind_dn", ""), + base: s.get("search_base", ""), + filter: s.get("search_filter", "(uid={user})"), + searchDN: s.get("search_bind_dn", ""), + searchPass: s.get("search_bind_password", ""), + } + if a.startTLS, err = s.bool("starttls", false); err != nil { + return nil, err + } + if a.timeout, err = s.duration("timeout", 10*time.Second); err != nil { + return nil, err + } + skip, err := s.bool("insecure_skip_verify", false) + if err != nil { + return nil, err + } + a.tls = &tls.Config{InsecureSkipVerify: skip} + if ca := s.get("ca_file", ""); ca != "" { + pem, err := os.ReadFile(ca) + if err != nil { + return nil, fmt.Errorf("[ldap] ca_file: %v", err) + } + pool := x509.NewCertPool() + if !pool.AppendCertsFromPEM(pem) { + return nil, fmt.Errorf("[ldap] ca_file: no certificate in %s", ca) + } + a.tls.RootCAs = pool + } + if a.bindDN == "" && a.base == "" { + return nil, fmt.Errorf("[ldap] needs bind_dn or search_base") + } + if a.bindDN != "" && !strings.Contains(a.bindDN, "{user}") { + return nil, fmt.Errorf("[ldap] bind_dn: no {user} in %q", a.bindDN) + } + return a, nil +} + +func (a *ldapAuth) name() string { return "ldap" } + +func (a *ldapAuth) authenticate(ctx context.Context, user, password string) error { + // an empty password would be an unauthenticated bind, which servers + // accept for any DN + if password == "" { + return errBadPassword + } + d := &net.Dialer{Timeout: a.timeout} + host := a.url + if i := strings.Index(host, "://"); i >= 0 { + host = host[i+3:] + } + host, _, _ = strings.Cut(host, "/") + tc := a.tls.Clone() + if tc.ServerName == "" { + tc.ServerName, _, _ = strings.Cut(host, ":") + } + conn, err := ldap.DialURL(a.url, ldap.DialWithDialer(d), ldap.DialWithTLSConfig(tc)) + if err != nil { + return err + } + defer conn.Close() + conn.SetTimeout(a.timeout) + if a.startTLS { + if err := conn.StartTLS(tc); err != nil { + return fmt.Errorf("starttls: %v", err) + } + } + + dn := "" + 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) + } + } + 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) + } + } + 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 + } + return err +} diff --git a/auth_sql.go b/auth_sql.go new file mode 100644 index 0000000..9d9d8e4 --- /dev/null +++ b/auth_sql.go @@ -0,0 +1,116 @@ +package main + +import ( + "context" + "database/sql" + "errors" + "fmt" + "strings" + "time" + + _ "github.com/go-sql-driver/mysql" + _ "github.com/lib/pq" + _ "modernc.org/sqlite" +) + +// sqlAuth: query, with the user (and the password, for args = user +// password) as its arguments, returns the stored password of the user +// (checked as hash says), or with hash = none any row for a valid login +type sqlAuth struct { + driver string + dsn string + query string + args []string + scheme string + timeout time.Duration + db *sql.DB +} + +var sqlDrivers = map[string]string{ + "mysql": "mysql", + "mariadb": "mysql", + "postgres": "postgres", + "postgresql": "postgres", + "sqlite": "sqlite", + "sqlite3": "sqlite", +} + +func newSQLAuth(s *section) (authenticator, error) { + var err error + a := &sqlAuth{ + dsn: s.get("dsn", ""), + query: s.get("query", ""), + args: fields(strings.ToLower(s.get("args", "user"))), + scheme: strings.ToLower(s.get("hash", "auto")), + } + drv := strings.ToLower(s.get("driver", "")) + if a.driver = sqlDrivers[drv]; a.driver == "" { + return nil, fmt.Errorf("[sql] driver: %q (mysql, postgres or sqlite)", drv) + } + if a.dsn == "" || a.query == "" { + return nil, fmt.Errorf("[sql] needs dsn and query") + } + for _, arg := range a.args { + if arg != "user" && arg != "password" { + return nil, fmt.Errorf("[sql] args: %q (user, password)", arg) + } + } + if a.timeout, err = s.duration("timeout", 10*time.Second); err != nil { + return nil, err + } + // 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 { + return nil, fmt.Errorf("[sql] %v", err) + } + a.db.SetMaxOpenConns(1) + return a, nil +} + +func (a *sqlAuth) name() string { return "sql" } + +func (a *sqlAuth) authenticate(ctx context.Context, user, password string) error { + ctx, cancel := context.WithTimeout(ctx, a.timeout) + defer cancel() + args := make([]any, len(a.args)) + for i, arg := range a.args { + if arg == "user" { + args[i] = user + } else { + args[i] = password + } + } + var stored sql.NullString + row := a.db.QueryRowContext(ctx, a.query, args...) + var err error + if a.scheme == "none" { + err = row.Scan(&discard{}) + } else { + err = row.Scan(&stored) + } + if errors.Is(err, sql.ErrNoRows) { + return errNoUser + } + if err != nil { + return err + } + if a.scheme == "none" { + return nil + } + if !stored.Valid { + return errBadPassword + } + ok, err := checkPassword(stored.String, password, a.scheme) + if err != nil { + return fmt.Errorf("user %s: %v", user, err) + } + if !ok { + return errBadPassword + } + return nil +} + +// discard scans and drops a column of any type +type discard struct{} + +func (*discard) Scan(any) error { return nil } diff --git a/config.go b/config.go new file mode 100644 index 0000000..50d5c09 --- /dev/null +++ b/config.go @@ -0,0 +1,178 @@ +package main + +import ( + "bufio" + "fmt" + "os" + "strconv" + "strings" + "time" +) + +// section is one [name] of the configuration, its keys in file order +type section struct { + name string + keys []string + vals map[string]string + line map[string]int +} + +func (s *section) get(key, def string) string { + if v, ok := s.vals[key]; ok { + return v + } + return def +} + +func (s *section) has(key string) bool { + _, ok := s.vals[key] + return ok +} + +func (s *section) bool(key string, def bool) (bool, error) { + v, ok := s.vals[key] + if !ok { + return def, nil + } + switch strings.ToLower(v) { + case "yes", "true", "on", "1": + return true, nil + case "no", "false", "off", "0": + return false, nil + } + return def, fmt.Errorf("[%s] %s: %q is not yes or no", s.name, key, v) +} + +func (s *section) int(key string, def int) (int, error) { + v, ok := s.vals[key] + if !ok { + return def, nil + } + n, err := strconv.Atoi(v) + if err != nil { + return def, fmt.Errorf("[%s] %s: %q is not a number", s.name, key, v) + } + return n, nil +} + +// seconds: a plain number of seconds, or a Go duration (90s, 5m) +func (s *section) duration(key string, def time.Duration) (time.Duration, error) { + v, ok := s.vals[key] + if !ok { + return def, nil + } + if n, err := strconv.Atoi(v); err == nil { + return time.Duration(n) * time.Second, nil + } + d, err := time.ParseDuration(v) + if err != nil { + return def, fmt.Errorf("[%s] %s: %q is not a duration", s.name, key, v) + } + return d, nil +} + +// ini is a dmodem.conf-style file: [sections] of key = value, ';' or '#' +// comments on lines of their own +type ini struct { + path string + sections []*section + byName map[string]*section +} + +func (c *ini) section(name string) *section { + if s, ok := c.byName[name]; ok { + return s + } + return §ion{name: name, vals: map[string]string{}, line: map[string]int{}} +} + +func parseINI(path string) (*ini, error) { + f, err := os.Open(path) + if err != nil { + return nil, err + } + defer f.Close() + c := &ini{path: path, byName: map[string]*section{}} + var cur *section + sc := bufio.NewScanner(f) + for n := 1; sc.Scan(); n++ { + line := strings.TrimSpace(sc.Text()) + if line == "" || line[0] == ';' || line[0] == '#' { + continue + } + if line[0] == '[' { + end := strings.IndexByte(line, ']') + if end < 0 { + return nil, fmt.Errorf("%s:%d: no ] in %q", path, n, line) + } + name := strings.Join(strings.Fields(line[1:end]), " ") + if s, ok := c.byName[name]; ok { + cur = s + continue + } + cur = §ion{name: name, vals: map[string]string{}, line: map[string]int{}} + c.sections = append(c.sections, cur) + c.byName[name] = cur + continue + } + eq := strings.IndexByte(line, '=') + if eq < 0 { + return nil, fmt.Errorf("%s:%d: no = in %q", path, n, line) + } + if cur == nil { + return nil, fmt.Errorf("%s:%d: %q is before any [section]", path, n, line) + } + key := strings.ToLower(strings.TrimSpace(line[:eq])) + val := strings.TrimSpace(line[eq+1:]) + if len(val) >= 2 && val[0] == '"' && val[len(val)-1] == '"' { + val = val[1 : len(val)-1] + } + if _, ok := cur.vals[key]; !ok { + cur.keys = append(cur.keys, key) + } + cur.vals[key] = val + cur.line[key] = n + } + return c, sc.Err() +} + +// unescape turns \r \n \t \e \\ and \xHH of a configured string into +// their bytes +func unescape(s string) string { + var b strings.Builder + for i := 0; i < len(s); i++ { + if s[i] != '\\' || i+1 == len(s) { + b.WriteByte(s[i]) + continue + } + i++ + switch s[i] { + case 'r': + b.WriteByte('\r') + case 'n': + b.WriteByte('\n') + case 't': + b.WriteByte('\t') + case 'e': + b.WriteByte(0x1b) + case 'x': + if i+2 < len(s) { + if v, err := strconv.ParseUint(s[i+1:i+3], 16, 8); err == nil { + b.WriteByte(byte(v)) + i += 2 + continue + } + } + b.WriteString("\\x") + default: + b.WriteByte(s[i]) + } + } + return b.String() +} + +func fields(s string) []string { + return strings.FieldsFunc(s, func(r rune) bool { + return r == ',' || r == ' ' || r == '\t' + }) +} diff --git a/e2e_test.go b/e2e_test.go new file mode 100644 index 0000000..49e3d3d --- /dev/null +++ b/e2e_test.go @@ -0,0 +1,281 @@ +package main + +import ( + "bytes" + "fmt" + "net" + "os" + "os/exec" + "path/filepath" + "strings" + "syscall" + "testing" + "time" + + "golang.org/x/sys/unix" +) + +// openPty: master and slave of a new pty, raw as app_dmodem makes it +func openPty(t *testing.T) (*os.File, *os.File) { + m, err := os.OpenFile("/dev/ptmx", os.O_RDWR|syscall.O_NOCTTY, 0) + if err != nil { + t.Skip("no pty:", err) + } + if err := unix.IoctlSetPointerInt(int(m.Fd()), unix.TIOCSPTLCK, 0); err != nil { + t.Fatal(err) + } + n, err := unix.IoctlGetInt(int(m.Fd()), unix.TIOCGPTN) + if err != nil { + t.Fatal(err) + } + s, err := os.OpenFile(fmt.Sprintf("/dev/pts/%d", n), os.O_RDWR|syscall.O_NOCTTY, 0) + if err != nil { + t.Fatal(err) + } + tio, _ := unix.IoctlGetTermios(int(s.Fd()), unix.TCGETS) + makeRaw(tio) + unix.IoctlSetTermios(int(s.Fd()), unix.TCSETS, tio) + return m, s +} + +// caller: the remote end of the line +type caller struct { + t *testing.T + m *os.File + in chan []byte + buf bytes.Buffer +} + +func newCaller(t *testing.T, m *os.File) *caller { + c := &caller{t: t, m: m, in: make(chan []byte, 64)} + go func() { + for { + b := make([]byte, 1024) + n, err := m.Read(b) + if n > 0 { + c.in <- b[:n] + } + if err != nil { + close(c.in) + return + } + } + }() + return c +} + +func (c *caller) expect(s string) string { + c.t.Helper() + timeout := time.After(10 * time.Second) + for !strings.Contains(c.buf.String(), s) { + select { + case b, ok := <-c.in: + if !ok { + c.t.Fatalf("waiting for %q: hung up; got %q", s, c.buf.String()) + } + c.buf.Write(b) + case <-timeout: + c.t.Fatalf("waiting for %q: timeout; got %q", s, c.buf.String()) + } + } + i := strings.Index(c.buf.String(), s) + len(s) + got := c.buf.String()[:i] + rest := c.buf.String()[i:] + c.buf.Reset() + c.buf.WriteString(rest) + return got +} + +func (c *caller) send(s string) { + c.m.Write([]byte(s)) +} + +func TestLine(t *testing.T) { + dir := t.TempDir() + bin := filepath.Join(dir, "modemmenu") + if out, err := exec.Command("go", "build", "-o", bin, ".").CombinedOutput(); err != nil { + t.Fatalf("build: %v\n%s", err, out) + } + + // an rlogin BBS: checks the handshake, says who logged in, ends on Q + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer ln.Close() + hello := make(chan string, 1) + go func() { + conn, err := ln.Accept() + if err != nil { + return + } + defer conn.Close() + b := make([]byte, 256) + got := "" + for strings.Count(got, "\x00") < 4 { + n, err := conn.Read(b) + if err != nil { + return + } + got += string(b[:n]) + } + hello <- got + parts := strings.Split(got, "\x00") + conn.Write([]byte("\x00Welcome to the BBS, " + parts[2] + "\r\n")) + for { + n, err := conn.Read(b) + if err != nil || bytes.ContainsRune(b[:n], 'Q') { + conn.Write([]byte("Bye from the BBS\r\n")) + return + } + } + }() + + users := filepath.Join(dir, "users") + os.WriteFile(users, []byte("alice:{PLAIN}secret\n"), 0o600) + envOut := filepath.Join(dir, "env") + conf := filepath.Join(dir, "modemmenu.conf") + os.WriteFile(conf, []byte(fmt.Sprintf(` +[general] +log = %s +auth = file +fail_delay = 0 +banner = "Test line\r\n" +[file] +path = %s +[item bbs] +key = B +label = BBS +mode = rlogin +host = 127.0.0.1 +port = %d +after = menu +[item shell] +key = S +label = Shell +mode = exec +tty = sane +after = menu +command = PS1='sh> ' exec sh -i +[item info] +key = I +label = Info +mode = exec +session_file = yes +tty = sane +command = env > %s; cat "$MODEM_SESSION_FILE" >> %s; echo args: {user} {baud} {dialed}; read x; echo "read $x" +`, filepath.Join(dir, "log"), users, ln.Addr().(*net.TCPAddr).Port, envOut, envOut)), 0o600) + + m, s := openPty(t) + defer m.Close() + cmd := exec.Command(bin, "-config", conf) + cmd.Stdin, cmd.Stdout, cmd.Stderr = s, s, s + cmd.Env = append(os.Environ(), "DMODEM_RATE=33600/31200", "DMODEM_CALLERID=5559999", + "DMODEM_DIALED=5551000", "DMODEM_CHANNEL=Local/s@test", "TMPDIR="+dir) + cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true, Setctty: true} + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + s.Close() + defer cmd.Process.Kill() + + c := newCaller(t, m) + c.expect("Test line") + c.expect("login: ") + c.send("alice\r") + c.expect("alice\r\nPassword: ") + c.send("wrong\r") + c.expect("*****\r\n") + c.expect("Login incorrect") + c.expect("login: ") + c.send("alice\r\n") + c.expect("Password: ") + c.send("secret\r") + c.expect("Welcome, alice.") + c.expect("Selection: ") + + c.send("b\r") + c.expect("Welcome to the BBS, alice") + if h := <-hello; h != "\x00secret\x00alice\x00ansi/33600\x00" { + t.Errorf("rlogin handshake %q", h) + } + c.send("Q") + c.expect("Bye from the BBS") + c.expect("Selection: ") + + // a cooked shell: ^C stops its command, not the session + c.send("S") + c.expect("sh> ") + c.send("sleep 30\r") + c.expect("sleep 30") + time.Sleep(300 * time.Millisecond) + c.send("\x03") + c.expect("sh> ") + c.send("echo alive $MODEM_USER\r") + c.expect("alive alice") + c.send("exit\r") + c.expect("Selection: ") + + c.send("I") + c.expect("args: alice 33600 5551000") + c.send("typed\r") + c.expect("read typed") + c.expect("Goodbye") + cmd.Wait() + + env, _ := os.ReadFile(envOut) + for _, w := range []string{"MODEM_USER=alice", "MODEM_PASSWORD=secret", "MODEM_BAUD=33600", + "MODEM_DIALED=5551000", "MODEM_CALLERID=5559999", "MODEM_SELECTION=info", + "MODEM_AUTH=file", "MODEM_CHANNEL=Local/s@test", "MODEM_DATETIME=", `"user": "alice"`, + `"password": "secret"`, `"dialed": "5551000"`} { + if !bytes.Contains(env, []byte(w)) { + t.Errorf("no %s in the environment and session file:\n%s", w, env) + } + } + if matches, _ := filepath.Glob(filepath.Join(dir, "modemmenu-*.json")); len(matches) > 0 { + t.Errorf("session files left: %v", matches) + } + log, _ := os.ReadFile(filepath.Join(dir, "log")) + for _, w := range []string{`failed login user="alice"`, "login user=alice auth=file", "start bbs", "end info"} { + if !bytes.Contains(log, []byte(w)) { + t.Errorf("no %q in the log:\n%s", w, log) + } + } + if bytes.Contains(log, []byte("secret")) { + t.Errorf("the password in the log:\n%s", log) + } +} + +// the caller hanging up at the login ends modemmenu +func TestHangup(t *testing.T) { + dir := t.TempDir() + bin := filepath.Join(dir, "modemmenu") + if out, err := exec.Command("go", "build", "-o", bin, ".").CombinedOutput(); err != nil { + t.Fatalf("build: %v\n%s", err, out) + } + users := filepath.Join(dir, "users") + os.WriteFile(users, nil, 0o600) + conf := filepath.Join(dir, "modemmenu.conf") + os.WriteFile(conf, []byte("[general]\nlog = none\n[file]\npath = "+users+ + "\n[item ppp]\ncommand = exec true\n"), 0o600) + m, s := openPty(t) + cmd := exec.Command(bin, "-config", conf) + cmd.Stdin, cmd.Stdout, cmd.Stderr = s, s, s + cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true, Setctty: true} + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + s.Close() + c := newCaller(t, m) + c.expect("login: ") + c.send("ali") + m.Close() + done := make(chan error, 1) + go func() { done <- cmd.Wait() }() + select { + case <-done: + case <-time.After(5 * time.Second): + cmd.Process.Kill() + t.Fatal("modemmenu is still running after the hangup") + } +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..70510fb --- /dev/null +++ b/go.mod @@ -0,0 +1,31 @@ +module github.com/Neo-Desktop/pbx-modem + +go 1.22 + +require ( + github.com/go-ldap/ldap/v3 v3.4.8 + github.com/go-sql-driver/mysql v1.8.1 + github.com/lib/pq v1.10.9 + golang.org/x/crypto v0.31.0 + golang.org/x/sys v0.28.0 + golang.org/x/term v0.27.0 + modernc.org/sqlite v1.33.1 +) + +require ( + filippo.io/edwards25519 v1.1.0 // indirect + github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358 // indirect + github.com/dustin/go-humanize v1.0.1 // indirect + github.com/go-asn1-ber/asn1-ber v1.5.5 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/ncruces/go-strftime v0.1.9 // indirect + github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect + modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 // indirect + modernc.org/libc v1.55.3 // indirect + modernc.org/mathutil v1.6.0 // indirect + modernc.org/memory v1.8.0 // indirect + modernc.org/strutil v1.2.0 // indirect + modernc.org/token v1.1.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..76338c5 --- /dev/null +++ b/go.sum @@ -0,0 +1,147 @@ +filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= +filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= +github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358 h1:mFRzDkZVAjdal+s7s0MwaRv9igoPqLRdzOLzw/8Xvq8= +github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358/go.mod h1:chxPXzSsl7ZWRAuOIE23GDNzjWuZquvFlgA8xmpunjU= +github.com/alexbrainman/sspi v0.0.0-20231016080023-1a75b4708caa h1:LHTHcTQiSGT7VVbI0o4wBRNQIgn917usHWOd6VAffYI= +github.com/alexbrainman/sspi v0.0.0-20231016080023-1a75b4708caa/go.mod h1:cEWa1LVoE5KvSD9ONXsZrj0z6KqySlCCNKHlLzbqAt4= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/go-asn1-ber/asn1-ber v1.5.5 h1:MNHlNMBDgEKD4TcKr36vQN68BA00aDfjIt3/bD50WnA= +github.com/go-asn1-ber/asn1-ber v1.5.5/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0= +github.com/go-ldap/ldap/v3 v3.4.8 h1:loKJyspcRezt2Q3ZRMq2p/0v8iOurlmeXDPw6fikSvQ= +github.com/go-ldap/ldap/v3 v3.4.8/go.mod h1:qS3Sjlu76eHfHGpUdWkAXQTw4beih+cHsco2jXlIXrk= +github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y= +github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg= +github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd h1:gbpYu9NMq8jhDVbvlGkMFWCjLFlqqEZjEmObmhUy6Vo= +github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4= +github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM= +github.com/hashicorp/go-uuid v1.0.2/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/Co8= +github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= +github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= +github.com/jcmturner/aescts/v2 v2.0.0 h1:9YKLH6ey7H4eDBXW8khjYslgyqG2xZikXP0EQFKrle8= +github.com/jcmturner/aescts/v2 v2.0.0/go.mod h1:AiaICIRyfYg35RUkr8yESTqvSy7csK90qZ5xfvvsoNs= +github.com/jcmturner/dnsutils/v2 v2.0.0 h1:lltnkeZGL0wILNvrNiVCR6Ro5PGU/SeBvVO/8c/iPbo= +github.com/jcmturner/dnsutils/v2 v2.0.0/go.mod h1:b0TnjGOvI/n42bZa+hmXL+kFJZsFT7G4t3HTlQ184QM= +github.com/jcmturner/gofork v1.7.6 h1:QH0l3hzAU1tfT3rZCnW5zXl+orbkNMMRGJfdJjHVETg= +github.com/jcmturner/gofork v1.7.6/go.mod h1:1622LH6i/EZqLloHfE7IeZ0uEJwMSUyQ/nDd82IeqRo= +github.com/jcmturner/goidentity/v6 v6.0.1 h1:VKnZd2oEIMorCTsFBnJWbExfNN7yZr3EhJAxwOkZg6o= +github.com/jcmturner/goidentity/v6 v6.0.1/go.mod h1:X1YW3bgtvwAXju7V3LCIMpY0Gbxyjn/mY9zx4tFonSg= +github.com/jcmturner/gokrb5/v8 v8.4.4 h1:x1Sv4HaTpepFkXbt2IkL29DXRf8sOfZXo8eRKh687T8= +github.com/jcmturner/gokrb5/v8 v8.4.4/go.mod h1:1btQEpgT6k+unzCwX1KdWMEwPPkkgBtP+F6aCACiMrs= +github.com/jcmturner/rpc/v2 v2.0.3 h1:7FXXj8Ti1IaVFpSAziCZWNzbNuZmnvw/i6CqLNdWfZY= +github.com/jcmturner/rpc/v2 v2.0.3/go.mod h1:VUJYCIDm3PVOEHw8sgt091/20OJjskO/YJki3ELg/Hc= +github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= +github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4= +github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58= +golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= +golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs= +golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U= +golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/mod v0.16.0 h1:QX4fJ0Rr5cPQCF7O9lh9Se4pmwfwskqZfq5moyldzic= +golang.org/x/mod v0.16.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= +golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44= +golang.org/x/net v0.22.0 h1:9sGLhx7iRIHEiX0oAJ3MRZMUCElJgy7Br1nO+AMN3Tc= +golang.org/x/net v0.22.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA= +golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= +golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= +golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk= +golang.org/x/term v0.18.0/go.mod h1:ILwASektA3OnRv7amZ1xhE/KTR+u50pbXfZ03+6Nx58= +golang.org/x/term v0.27.0 h1:WP60Sv1nlK1T6SupCHbXzSaN0b9wUmsPoRS9b61A23Q= +golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= +golang.org/x/tools v0.19.0 h1:tfGCXNR1OsFG+sVdLAitlpjAvD/I6dHDKnYrpEZUHkw= +golang.org/x/tools v0.19.0/go.mod h1:qoJWxmGSIBmAeriMx19ogtrEPrGtDbPK634QFIcLAhc= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +modernc.org/cc/v4 v4.21.4 h1:3Be/Rdo1fpr8GrQ7IVw9OHtplU4gWbb+wNgeoBMmGLQ= +modernc.org/cc/v4 v4.21.4/go.mod h1:HM7VJTZbUCR3rV8EYBi9wxnJ0ZBRiGE5OeGXNA0IsLQ= +modernc.org/ccgo/v4 v4.19.2 h1:lwQZgvboKD0jBwdaeVCTouxhxAyN6iawF3STraAal8Y= +modernc.org/ccgo/v4 v4.19.2/go.mod h1:ysS3mxiMV38XGRTTcgo0DQTeTmAO4oCmJl1nX9VFI3s= +modernc.org/fileutil v1.3.0 h1:gQ5SIzK3H9kdfai/5x41oQiKValumqNTDXMvKo62HvE= +modernc.org/fileutil v1.3.0/go.mod h1:XatxS8fZi3pS8/hKG2GH/ArUogfxjpEKs3Ku3aK4JyQ= +modernc.org/gc/v2 v2.4.1 h1:9cNzOqPyMJBvrUipmynX0ZohMhcxPtMccYgGOJdOiBw= +modernc.org/gc/v2 v2.4.1/go.mod h1:wzN5dK1AzVGoH6XOzc3YZ+ey/jPgYHLuVckd62P0GYU= +modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 h1:5D53IMaUuA5InSeMu9eJtlQXS2NxAhyWQvkKEgXZhHI= +modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6/go.mod h1:Qz0X07sNOR1jWYCrJMEnbW/X55x206Q7Vt4mz6/wHp4= +modernc.org/libc v1.55.3 h1:AzcW1mhlPNrRtjS5sS+eW2ISCgSOLLNyFzRh/V3Qj/U= +modernc.org/libc v1.55.3/go.mod h1:qFXepLhz+JjFThQ4kzwzOjA/y/artDeg+pcYnY+Q83w= +modernc.org/mathutil v1.6.0 h1:fRe9+AmYlaej+64JsEEhoWuAYBkOtQiMEU7n/XgfYi4= +modernc.org/mathutil v1.6.0/go.mod h1:Ui5Q9q1TR2gFm0AQRqQUaBWFLAhQpCwNcuhBOSedWPo= +modernc.org/memory v1.8.0 h1:IqGTL6eFMaDZZhEWwcREgeMXYwmW83LYW8cROZYkg+E= +modernc.org/memory v1.8.0/go.mod h1:XPZ936zp5OMKGWPqbD3JShgd/ZoQ7899TUuQqxY+peU= +modernc.org/opt v0.1.3 h1:3XOZf2yznlhC+ibLltsDGzABUGVx8J6pnFMS3E4dcq4= +modernc.org/opt v0.1.3/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0= +modernc.org/sortutil v1.2.0 h1:jQiD3PfS2REGJNzNCMMaLSp/wdMNieTbKX920Cqdgqc= +modernc.org/sortutil v1.2.0/go.mod h1:TKU2s7kJMf1AE84OoiGppNHJwvB753OYfNl2WRb++Ss= +modernc.org/sqlite v1.33.1 h1:trb6Z3YYoeM9eDL1O8do81kP+0ejv+YzgyFo+Gwy0nM= +modernc.org/sqlite v1.33.1/go.mod h1:pXV2xHxhzXZsgT/RtTFAPY6JJDEvOTcTdwADQCCWD4k= +modernc.org/strutil v1.2.0 h1:agBi9dp1I+eOnxXeiZawM8F4LawKv4NzGWSaLfyeNZA= +modernc.org/strutil v1.2.0/go.mod h1:/mdcBmfOibveCTBxUl5B5l6W+TTH1FXPLHZE6bTosX0= +modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= +modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= diff --git a/launch.go b/launch.go new file mode 100644 index 0000000..d115085 --- /dev/null +++ b/launch.go @@ -0,0 +1,403 @@ +package main + +import ( + "bufio" + "fmt" + "io" + "net" + "os" + "os/exec" + "os/user" + "strconv" + "strings" + "sync" + "syscall" + "time" + + "golang.org/x/sys/unix" +) + +// launch the selection: its error, or nil when it ended by itself +func launch(t *term, it *menuItem, s *session, logf func(string, ...any)) error { + switch it.mode { + case "exec": + return runExec(t, it, s, logf) + default: + return runTCP(t, it, s) + } +} + +// runExec: the command under /bin/sh -c on the caller's line, the +// session in MODEM_* of its environment, {placeholders} of the command +// as quoted shell words +func runExec(t *term, it *menuItem, s *session, logf func(string, ...any)) error { + v := s.vars(it.password) + cmd := exec.Command("/bin/sh", "-c", expand(it.command, v, shellQuote)) + cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stdout + + env := make([]string, 0, 32) + for _, e := range os.Environ() { + if !strings.HasPrefix(e, "MODEM_") { + env = append(env, e) + } + } + env = append(env, s.environ(it.password)...) + + uid, gid := -1, -1 + if it.runAs != "" { + name := expand(it.runAs, v, nil) + u, err := user.Lookup(name) + if err != nil { + return fmt.Errorf("run_as %s: %v", name, err) + } + cred, err := credential(u) + if err != nil { + return fmt.Errorf("run_as %s: %v", name, err) + } + uid, gid = int(cred.Uid), int(cred.Gid) + cmd.SysProcAttr = &syscall.SysProcAttr{Credential: cred} + cmd.Dir = u.HomeDir + env = setEnv(env, "HOME", u.HomeDir) + env = setEnv(env, "USER", u.Username) + env = setEnv(env, "LOGNAME", u.Username) + if sh := loginShell(u.Username); sh != "" { + env = setEnv(env, "SHELL", sh) + } + } + if it.sessionFile { + path, err := s.writeFile(it.password, uid, gid) + if err != nil { + return fmt.Errorf("session file: %v", err) + } + defer os.Remove(path) + env = append(env, "MODEM_SESSION_FILE="+path) + } + cmd.Env = env + + before := t.setMode(it.tty) + defer t.restoreMode(before) + if err := cmd.Start(); err != nil { + return err + } + running(cmd.Process) + err := cmd.Wait() + running(nil) + // the line's foreground is ours again, whatever a shell did with it + unix.IoctlSetPointerInt(t.in, unix.TIOCSPGRP, unix.Getpgrp()) + if ee, ok := err.(*exec.ExitError); ok { + logf("%s: %s", it.name, ee.ProcessState) + return nil + } + return err +} + +func credential(u *user.User) (*syscall.Credential, error) { + uid, err := strconv.ParseUint(u.Uid, 10, 32) + if err != nil { + return nil, err + } + gid, err := strconv.ParseUint(u.Gid, 10, 32) + if err != nil { + return nil, err + } + c := &syscall.Credential{Uid: uint32(uid), Gid: uint32(gid)} + if ids, err := u.GroupIds(); err == nil { + for _, id := range ids { + if g, err := strconv.ParseUint(id, 10, 32); err == nil { + c.Groups = append(c.Groups, uint32(g)) + } + } + } + return c, nil +} + +// loginShell of a user in /etc/passwd +func loginShell(name string) string { + f, err := os.Open("/etc/passwd") + if err != nil { + return "" + } + defer f.Close() + sc := bufio.NewScanner(f) + for sc.Scan() { + p := strings.Split(sc.Text(), ":") + if len(p) == 7 && p[0] == name { + return p[6] + } + } + return "" +} + +func setEnv(env []string, k, v string) []string { + for i, e := range env { + if strings.HasPrefix(e, k+"=") { + env[i] = k + "=" + v + return env + } + } + return append(env, k+"="+v) +} + +// the program of the selection, for the signal handler +var ( + childMu sync.Mutex + child *os.Process +) + +func running(p *os.Process) { + childMu.Lock() + child = p + childMu.Unlock() +} + +// runTCP: the caller's line to a server: raw TCP, telnet or rlogin +func runTCP(t *term, it *menuItem, s *session) error { + v := s.vars(it.password) + addr := net.JoinHostPort(it.host, strconv.Itoa(it.port)) + conn, err := net.DialTimeout("tcp", addr, it.timeout) + if err != nil { + return err + } + defer conn.Close() + + var tn *telnet + switch it.mode { + case "rlogin": + // RFC 1282: \0 client-user \0 server-user \0 terminal/speed \0; + // BBSs (Synchronet, Mystic) take the password as the client + // user and log the caller in at once + hello := "\x00" + expand(it.rloginLocal, v, nil) + "\x00" + + expand(it.rloginUser, v, nil) + "\x00" + + expand(it.rloginTerm, v, nil) + "\x00" + conn.SetDeadline(time.Now().Add(it.timeout)) + if _, err := io.WriteString(conn, hello); err != nil { + return err + } + var ack [1]byte + if _, err := io.ReadFull(conn, ack[:]); err != nil { + return fmt.Errorf("rlogin: %v", err) + } + conn.SetDeadline(time.Time{}) + if ack[0] != 0 { + // not the ack: the server's first byte of output + t.write(string(ack[:])) + } + case "telnet": + tn = &telnet{conn: conn, term: expand(it.terminal, v, nil), + local: map[byte]bool{}, remote: map[byte]bool{}} + } + if it.send != "" { + b := []byte(expand(unescape(it.send), v, nil)) + if tn != nil { + b = tn.encode(b) + } + if _, err := conn.Write(b); err != nil { + return err + } + } + + // the server to the caller + done := make(chan error, 1) + go func() { + buf := make([]byte, 4096) + for { + n, err := conn.Read(buf) + if n > 0 { + out := buf[:n] + if tn != nil { + out = tn.decode(out) + } + if werr := t.write(string(out)); werr != nil { + done <- werr + return + } + } + if err != nil { + done <- nil + return + } + } + }() + + // the caller to the server, until either goes away; stdin is polled + // so that nothing is read from it once the server is gone + buf := make([]byte, 4096) + for { + select { + case err := <-done: + return err + default: + } + ok, err := pollOne(t.in, unix.POLLIN, 200*time.Millisecond) + if err != nil { + return errHangup + } + if !ok { + continue + } + n, err := unix.Read(t.in, buf) + if err == unix.EINTR || err == unix.EAGAIN { + continue + } + if n <= 0 || err != nil { + return errHangup + } + b := buf[:n] + if tn != nil { + b = tn.encode(b) + } + if _, err := tn.writeTo(conn, b); err != nil { + <-done + return nil + } + } +} + +// telnet: just enough of a telnet client for a BBS: binary, suppress go +// ahead and the server's echo, and the terminal type +type telnet struct { + mu sync.Mutex + conn io.Writer + term string + state int + cmd byte + sb []byte + local map[byte]bool // options we do + remote map[byte]bool // options the server does +} + +const ( + iac = 255 + dont = 254 + do = 253 + wont = 252 + will = 251 + sb = 250 + se = 240 + + optBinary = 0 + optEcho = 1 + optSGA = 3 + optTType = 24 +) + +func (tn *telnet) writeTo(w io.Writer, b []byte) (int, error) { + if tn == nil { + return w.Write(b) + } + tn.mu.Lock() + defer tn.mu.Unlock() + return w.Write(b) +} + +func (tn *telnet) send(b ...byte) { + tn.writeTo(tn.conn, b) +} + +// encode the caller's bytes: IAC doubled, CR as CR NUL unless binary +func (tn *telnet) encode(b []byte) []byte { + tn.mu.Lock() + bin := tn.local[optBinary] + tn.mu.Unlock() + out := make([]byte, 0, len(b)+8) + for _, c := range b { + out = append(out, c) + if c == iac { + out = append(out, iac) + } else if c == '\r' && !bin { + out = append(out, 0) + } + } + return out +} + +// decode the server's bytes: its data, the commands answered +func (tn *telnet) decode(b []byte) []byte { + out := b[:0:0] + for _, c := range b { + switch tn.state { + case 0: + if c == iac { + tn.state = 1 + } else { + out = append(out, c) + } + case 1: + switch c { + case iac: + out = append(out, iac) + tn.state = 0 + case will, wont, do, dont: + tn.cmd, tn.state = c, 2 + case sb: + tn.sb, tn.state = tn.sb[:0], 3 + default: + tn.state = 0 + } + case 2: + tn.option(tn.cmd, c) + tn.state = 0 + case 3: + if c == iac { + tn.state = 4 + } else if len(tn.sb) < 256 { + tn.sb = append(tn.sb, c) + } + case 4: + if c == se { + tn.subneg() + tn.state = 0 + } else { + if c == iac && len(tn.sb) < 256 { + tn.sb = append(tn.sb, iac) + } + tn.state = 3 + } + } + } + return out +} + +func (tn *telnet) option(cmd, opt byte) { + switch cmd { + case will: + ok := opt == optEcho || opt == optSGA || opt == optBinary + if ok && !tn.remote[opt] { + tn.remote[opt] = true + tn.send(iac, do, opt) + } else if !ok { + tn.send(iac, dont, opt) + } + case wont: + if tn.remote[opt] { + tn.remote[opt] = false + tn.send(iac, dont, opt) + } + case do: + ok := opt == optSGA || opt == optBinary || opt == optTType + if ok && !tn.local[opt] { + tn.mu.Lock() + tn.local[opt] = true + tn.mu.Unlock() + tn.send(iac, will, opt) + } else if !ok { + tn.send(iac, wont, opt) + } + case dont: + if tn.local[opt] { + tn.mu.Lock() + tn.local[opt] = false + tn.mu.Unlock() + tn.send(iac, wont, opt) + } + } +} + +func (tn *telnet) subneg() { + // TTYPE SEND: TTYPE IS + if len(tn.sb) >= 2 && tn.sb[0] == optTType && tn.sb[1] == 1 { + msg := []byte{iac, sb, optTType, 0} + msg = append(msg, []byte(tn.term)...) + tn.send(append(msg, iac, se)...) + } +} diff --git a/ldap_test.go b/ldap_test.go new file mode 100644 index 0000000..4cad077 --- /dev/null +++ b/ldap_test.go @@ -0,0 +1,39 @@ +package main + +import ( + "context" + "errors" + "os" + "testing" +) + +// MODEMMENU_TEST_LDAP=ldap://host:port of a server with +// uid=lduser,ou=people,dc=example,dc=com, password ldpass +func TestLDAP(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"}, + {"url": url, "bind_dn": "uid={user},ou=people,dc=example,dc=com"}, + } { + a, err := newLDAPAuth(§ion{name: "ldap", vals: vals}) + if err != nil { + t.Fatal(err) + } + ctx := context.Background() + if err := a.authenticate(ctx, "lduser", "ldpass"); err != nil { + t.Errorf("%v: right password: %v", vals, err) + } + if err := a.authenticate(ctx, "lduser", "wrong"); err == nil { + t.Errorf("%v: wrong password accepted", vals) + } + if err := a.authenticate(ctx, "lduser", ""); err == nil { + t.Errorf("%v: empty password accepted", vals) + } + if err := a.authenticate(ctx, "nobody*)(uid=*", "ldpass"); !errors.Is(err, errNoUser) { + t.Errorf("%v: unknown user: %v", vals, err) + } + } +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..ea983d0 --- /dev/null +++ b/main.go @@ -0,0 +1,280 @@ +// modemmenu: the login and menu of a dial-up line. app_dmodem (or any +// getty) runs it on the caller's line once the modems are connected; it +// asks for a user name and password, checks them with a text file, LDAP +// or an SQL database, and offers a menu (a BBS, PPP, a shell...) whose +// selection it starts with the caller's credentials and the call's +// details: dialed number, rate, caller ID and the time of the connection. +package main + +import ( + "bufio" + "context" + "errors" + "flag" + "fmt" + "io" + "log" + "log/syslog" + "os" + "os/signal" + "strings" + "sync/atomic" + "syscall" + "time" + + "golang.org/x/crypto/bcrypt" + xterm "golang.org/x/term" +) + +var logger = log.New(io.Discard, "", 0) + +func logf(format string, args ...any) { logger.Printf(format, args...) } + +func main() { + config := flag.String("config", "/etc/asterisk/modemmenu.conf", "the configuration `file`") + rate := flag.String("rate", os.Getenv("DMODEM_RATE"), "the connect `rate`, tx/rx bit/s (default $DMODEM_RATE)") + dialed := flag.String("dialed", os.Getenv("DMODEM_DIALED"), "the dialed `number` (default $DMODEM_DIALED)") + callerID := flag.String("callerid", os.Getenv("DMODEM_CALLERID"), "the caller's `number` (default $DMODEM_CALLERID)") + check := flag.Bool("check", false, "check the configuration and exit") + hash := flag.Bool("hash", false, "read a password, print its bcrypt hash for the users file and exit") + flag.Parse() + + if *hash { + os.Exit(printHash()) + } + s, err := loadSettings(*config) + if err != nil { + fmt.Fprintln(os.Stderr, "modemmenu:", err) + os.Exit(2) + } + if *check { + fmt.Printf("%s: %d menu items, auth %s\n", *config, len(s.items), strings.Join(s.auth, ", ")) + return + } + if err := openLog(s.log); err != nil { + fmt.Fprintln(os.Stderr, "modemmenu: log:", err) + } + sess := newSession(*rate, *dialed, *callerID, time.Now()) + t := newTerm(os.Stdin, os.Stdout) + code := run(t, s, sess) + t.close() + os.Exit(code) +} + +// terminated: SIGTERM or SIGHUP came +var terminated atomic.Bool + +func init() { + // a selection on a cooked line gets ^C and ^\ from the terminal, and + // so would we: caught (not ignored, which the selection would inherit) + // and dropped. A shell that took the terminal for a job of its own + // gives it back while we are in the background: no stop for that + signal.Ignore(syscall.SIGTTOU) + ch := make(chan os.Signal, 1) + signal.Notify(ch, syscall.SIGHUP, syscall.SIGTERM, syscall.SIGINT, syscall.SIGQUIT) + go func() { + for sig := range ch { + if sig == syscall.SIGINT || sig == syscall.SIGQUIT { + continue + } + terminated.Store(true) + childMu.Lock() + p := child + childMu.Unlock() + if p == nil { + os.Exit(1) + } + // the program ends, its session file is removed, then us + p.Signal(sig) + } + }() +} + +func openLog(dest string) error { + switch dest { + case "", "none": + return nil + case "syslog": + w, err := syslog.New(syslog.LOG_AUTH|syslog.LOG_INFO, "modemmenu") + if err != nil { + return err + } + logger = log.New(w, "", 0) + default: + f, err := os.OpenFile(dest, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0o640) + if err != nil { + return err + } + logger = log.New(f, fmt.Sprintf("modemmenu[%d]: ", os.Getpid()), log.LstdFlags) + } + return nil +} + +func printHash() int { + fmt.Fprint(os.Stderr, "Password: ") + var pw []byte + var err error + if xterm.IsTerminal(int(os.Stdin.Fd())) { + pw, err = xterm.ReadPassword(int(os.Stdin.Fd())) + fmt.Fprintln(os.Stderr) + } else { + var line string + line, err = bufio.NewReader(os.Stdin).ReadString('\n') + if err == io.EOF && line != "" { + err = nil + } + pw = []byte(strings.TrimRight(line, "\r\n")) + } + if err != nil { + fmt.Fprintln(os.Stderr, "modemmenu:", err) + return 1 + } + h, err := bcrypt.GenerateFromPassword(pw, bcrypt.DefaultCost) + if err != nil { + fmt.Fprintln(os.Stderr, "modemmenu:", err) + return 1 + } + fmt.Println(string(h)) + return 0 +} + +// the call: who and where from, for the log +func (s *session) String() string { + return fmt.Sprintf("callerid=%q dialed=%q rate=%q channel=%q", s.CallerID, s.Dialed, s.Rate, s.Channel) +} + +// run the login and the menu: the exit status +func run(t *term, s *settings, sess *session) int { + logf("connect %v", sess) + if t.write(expand(s.banner, sess.vars(false), nil)) != nil { + return 1 + } + if err := login(t, s, sess); err != nil { + if !errors.Is(err, errHangup) { + t.write("\r\n") + } + logf("no login: %v (%v)", err, sess) + return 1 + } + t.write(expand(s.welcome, sess.vars(false), nil)) + err := menu(t, s, sess) + switch { + case err == nil: + t.write(expand(s.goodbye, sess.vars(false), nil)) + case errors.Is(err, errTimeout): + t.write("\r\nIdle too long.\r\n") + } + logf("logout user=%s: %v", sess.User, describe(err)) + return 0 +} + +func describe(err error) string { + if err == nil { + return "done" + } + return err.Error() +} + +// login: the user name and password until one is right, attempts tries +// or the login timeout +func login(t *term, s *settings, sess *session) error { + deadline := time.Now().Add(s.loginTimeout) + for try := 1; try <= s.attempts; try++ { + if err := t.write(s.loginPrompt); err != nil { + return err + } + name, err := t.readLine(deadline, s.maxInput, true, "") + if err != nil { + return err + } + name = strings.TrimSpace(name) + if name == "" { + try-- + continue + } + if err := t.write(s.passwordPrompt); err != nil { + return err + } + pw, err := t.readLine(deadline, s.maxInput*2, false, s.mask) + if err != nil { + return err + } + auth := "" + if s.userPattern.MatchString(name) { + ctx, cancel := context.WithDeadline(context.Background(), deadline.Add(10*time.Second)) + auth, err = authenticate(ctx, s.backends, name, pw, logf) + cancel() + } else { + // not a name we take: the same answer, after the same time + burn(pw) + err = errNoUser + } + if err == nil { + sess.User, sess.Password, sess.Auth = name, pw, auth + logf("login user=%s auth=%s %v", name, auth, sess) + return nil + } + logf("failed login user=%q (%v) %v", name, err, sess) + time.Sleep(s.failDelay) + if err := t.write("\r\nLogin incorrect\r\n"); err != nil { + return err + } + if terminated.Load() { + return errHangup + } + } + return errors.New("too many attempts") +} + +// menu until the caller hangs up, says goodbye or a selection ends with +// after = hangup +func menu(t *term, s *settings, sess *session) error { + for { + var b strings.Builder + b.WriteString(expand(s.menuTitle, sess.vars(false), nil)) + for _, it := range s.items { + fmt.Fprintf(&b, "\r\n [%s] %s", it.key, it.label) + } + fmt.Fprintf(&b, "\r\n [%s] Goodbye (hang up)\r\n", s.hangupKey) + b.WriteString(s.menuPrompt) + if err := t.write(b.String()); err != nil { + return err + } + + var it *menuItem + for it == nil { + key, err := t.readKey(time.Now().Add(s.idleTimeout)) + if err == io.EOF || key == s.hangupKey { + t.write(s.hangupKey + "\r\n") + return nil + } + if err != nil { + return err + } + for _, i := range s.items { + if i.key == key { + it = i + } + } + } + // what the caller types from here on is the selection's (a line + // end after the key too: nothing is read ahead) + t.write(it.key + "\r\n") + + sess.Selection = it.name + logf("start %s user=%s mode=%s", it.name, sess.User, it.mode) + err := launch(t, it, sess, logf) + if errors.Is(err, errHangup) || terminated.Load() { + return errHangup + } + if err != nil { + logf("%s: %v", it.name, err) + t.write("\r\n\r\n" + it.label + " is not available now.\r\n") + continue + } + logf("end %s user=%s", it.name, sess.User) + if it.after == "hangup" { + return nil + } + } +} diff --git a/modemmenu.conf.sample b/modemmenu.conf.sample new file mode 100644 index 0000000..07c7f1a --- /dev/null +++ b/modemmenu.conf.sample @@ -0,0 +1,166 @@ +; +; modemmenu.conf - the login and menu of a dial-up line +; +; app_dmodem runs it on the caller's line (dmodem.conf): +; +; [menu] +; mode = exec +; command = exec /usr/local/bin/modemmenu -config /etc/asterisk/modemmenu.conf +; +; Values may be "quoted" to keep spaces at their ends; \r \n \t \e and \xHH +; are those bytes in the texts of [general] and [menu] and in send. +; +; The selection gets the session as {placeholders} in its command, send, +; run_as and the rlogin fields, and as MODEM_* in its environment. In a +; command a placeholder is a quoted shell word already: write {user}, not +; "{user}" (or "$MODEM_USER" from the environment). +; +; {user} MODEM_USER the user name the caller logged in with +; {password} MODEM_PASSWORD their password (pass_password = no: empty +; and not in the environment) +; {auth} MODEM_AUTH the backend that accepted it: file, ldap, sql +; {dialed} MODEM_DIALED the number the caller dialed +; {callerid} MODEM_CALLERID the caller's number +; {baud} MODEM_BAUD the connect rate towards the caller, bit/s +; {rate} MODEM_RATE both rates, tx/rx bit/s (app_dmodem's) +; {tx_rate} MODEM_TX_RATE to the caller +; {rx_rate} MODEM_RX_RATE from the caller +; {date} MODEM_DATE the date of the connection, 2006-01-02 +; {time} MODEM_TIME its time, 15:04:05 (local) +; {datetime} MODEM_DATETIME both, RFC 3339 with the zone +; {epoch} MODEM_EPOCH seconds since 1970 +; {channel} MODEM_CHANNEL the Asterisk channel +; {profile} MODEM_PROFILE the dmodem.conf profile +; {selection} MODEM_SELECTION the [item ...] chosen +; +; The rate, dialed number and caller ID come from app_dmodem's DMODEM_RATE, +; DMODEM_DIALED and DMODEM_CALLERID, or -rate, -dialed and -callerid. + +[general] +; syslog (auth facility), a file, or none. Never the line: stderr is the +; caller's screen +log = syslog +; the backends, asked in this order: file, ldap, sql. A backend that does +; not know the user passes to the next; a wrong password stops there +auth = file +banner = "\r\nWelcome to D-Modem.\r\n" +;banner_file = /etc/asterisk/modemmenu.banner +login_prompt = "\r\nlogin: " +password_prompt = "Password: " +welcome = "\r\nHello {user}, connected at {baud} bit/s on {date} {time}.\r\n" +goodbye = "\r\nGoodbye.\r\n" +; the echo of each password character, or none +password_echo = * +; logins before the call is hung up, seconds after a wrong one +attempts = 3 +fail_delay = 3 +; seconds to log in, to choose in the menu +login_timeout = 90 +idle_timeout = 300 +; user names taken (others are refused without asking a backend) +user_pattern = ^[A-Za-z0-9][A-Za-z0-9._@-]{0,63}$ + +; users in a text file: user:hash, # comments. hash: bcrypt ($2b$..., +; modemmenu -hash makes one), {SHA256}hex, {SHA512}hex, {SSHA256}base64, +; {SSHA512}base64 or {PLAIN}text (hash = plain: the rest of the line, as is) +[file] +path = /etc/asterisk/modemmenu.users +hash = auto + +; LDAP: a bind as the user. Either bind_dn with {user} in it, or a search +; for the user's entry (search_base, search_filter) as search_bind_dn, then +; a bind as the entry found. Restrict who may log in in the filter, e.g. +; (&(uid={user})(memberOf=cn=dialup,ou=groups,dc=example,dc=com)) +[ldap] +url = ldaps://ldap.example.com +;url = ldap://ldap.example.com:389 +;starttls = yes +;ca_file = /etc/ssl/certs/example-ca.pem +;insecure_skip_verify = no +timeout = 10 +;bind_dn = uid={user},ou=people,dc=example,dc=com +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 + +; SQL: query gets args (user, password, in that order of placeholders) and +; returns one column: the stored password, checked as hash says (auto: by +; its prefix as in [file]; or bcrypt, sha256, sha512, plain). hash = none: +; any row means the login is right (the query checks the password itself) +[sql] +; mysql (or mariadb), postgres, sqlite +driver = mysql +dsn = modem:secret@tcp(127.0.0.1:3306)/bbs +query = SELECT password FROM users WHERE username = ? AND enabled = 1 +args = user +hash = auto +;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 +;driver = sqlite +;dsn = /var/lib/asterisk/users.db +;query = SELECT password FROM users WHERE username = ? + +[menu] +title = "\r\nMain menu\r\n" +prompt = "\r\nSelection: " +; the items in order (default: every [item ...] in file order) +items = bbs ppp shell +hangup_key = G + +; An item: +; key = B its key in the menu (default: its name's first letter) +; label = ... its line in the menu +; mode = exec a program on the line: command (by /bin/sh -c) +; tcp a TCP server, raw: host, port; send is sent first +; telnet a telnet server: host, port (23), terminal (ANSI) +; rlogin an rlogin server: host, port (513), and +; rlogin_client_user ({password}), rlogin_server_user +; ({user}), rlogin_terminal (ansi/{baud}) +; run_as = {user} exec as this system user (modemmenu must be root) +; tty = raw the line as app_dmodem has it; sane: cooked, echo, +; CR to LF, for programs that want a terminal +; pass_password = yes the password in {password} and MODEM_PASSWORD +; session_file = no yes: the session as JSON in a 0600 file, its path +; in MODEM_SESSION_FILE (removed after) +; after = hangup when the item ends: hang up, or back to the menu +; connect_timeout = 10 seconds to reach a server + +; A BBS by rlogin: Synchronet and Mystic log the caller in with the user +; name as the server user and the password as the client user +[item bbs] +key = B +label = Bulletin board +mode = rlogin +host = 127.0.0.1 +port = 513 +rlogin_client_user = {password} +rlogin_server_user = {user} +rlogin_terminal = ansi/{baud} +after = menu +; or a BBS that reads its login from the line: +;mode = tcp +;port = 2323 +;send = "{user}\r{password}\r" + +; PPP: pppd on the line. The caller is logged in already: noauth, and +; ipparam hands the user to /etc/ppp/ip-up (as $6), which also sees MODEM_* +[item ppp] +key = P +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} + +; a shell of the caller's account (modemmenu runs as root for run_as) +[item shell] +key = S +label = Shell +mode = exec +run_as = {user} +tty = sane +pass_password = no +command = exec "$SHELL" -l +after = menu diff --git a/modemmenu.users.sample b/modemmenu.users.sample new file mode 100644 index 0000000..be79916 --- /dev/null +++ b/modemmenu.users.sample @@ -0,0 +1,6 @@ +# modemmenu.users - user:password, one per line (mode 0600) +# +# modemmenu -hash prints the bcrypt hash of a password +# +# guest:{PLAIN}guest +# alice:$2a$10$... diff --git a/modemmenu_test.go b/modemmenu_test.go new file mode 100644 index 0000000..9d85f36 --- /dev/null +++ b/modemmenu_test.go @@ -0,0 +1,187 @@ +package main + +import ( + "context" + "crypto/sha256" + "crypto/sha512" + "database/sql" + "encoding/base64" + "encoding/hex" + "errors" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "golang.org/x/crypto/bcrypt" +) + +func TestCheckPassword(t *testing.T) { + bc, _ := bcrypt.GenerateFromPassword([]byte("pw"), bcrypt.MinCost) + s256 := sha256.Sum256([]byte("pw")) + s512 := sha512.Sum512([]byte("pw")) + salted := sha256.Sum256([]byte("pwSALT")) + ssha := base64.StdEncoding.EncodeToString(append(salted[:], "SALT"...)) + for _, c := range []struct { + stored, scheme string + ok bool + }{ + {string(bc), "auto", true}, + {string(bc), "bcrypt", true}, + {"{SHA256}" + hex.EncodeToString(s256[:]), "auto", true}, + {"{SHA256}" + base64.StdEncoding.EncodeToString(s256[:]), "auto", true}, + {"{SHA512}" + hex.EncodeToString(s512[:]), "auto", true}, + {"{SSHA256}" + ssha, "auto", true}, + {"{PLAIN}pw", "auto", true}, + {"{PLAIN}px", "auto", false}, + {"pw", "plain", true}, + {hex.EncodeToString(s256[:]), "sha256", true}, + } { + for _, pw := range []string{"pw", "wrong"} { + ok, err := checkPassword(c.stored, pw, c.scheme) + if err != nil { + t.Errorf("%s (%s): %v", c.stored, c.scheme, err) + } + if want := c.ok && pw == "pw"; ok != want { + t.Errorf("%s (%s) %s: %v, want %v", c.stored, c.scheme, pw, ok, want) + } + } + } + if _, err := checkPassword("pw", "pw", "auto"); err == nil { + t.Error("a bare password with hash = auto: no error") + } +} + +func TestExpand(t *testing.T) { + v := map[string]string{"user": "o'neil; rm -rf /", "baud": "33600"} + got := expand("login {user} {baud} {unknown} {", v, shellQuote) + want := `login 'o'\''neil; rm -rf /' '33600' {unknown} {` + if got != want { + t.Errorf("got %q, want %q", got, want) + } + if got := expand("{USER}/{baud}", v, nil); got != v["user"]+"/33600" { + t.Errorf("got %q", got) + } + if got := unescape(`a\r\n\x41\\b`); got != "a\r\nA\\b" { + t.Errorf("unescape: %q", got) + } +} + +func TestSession(t *testing.T) { + now := time.Date(2026, 10, 10, 21, 5, 9, 0, time.UTC) + s := newSession("50666/31200", "5551000", "5559999", now) + s.User, s.Password = "alice", "secret" + env := strings.Join(s.environ(true), "\n") + for _, w := range []string{"MODEM_USER=alice", "MODEM_PASSWORD=secret", "MODEM_BAUD=50666", + "MODEM_RX_RATE=31200", "MODEM_DIALED=5551000", "MODEM_CALLERID=5559999", + "MODEM_DATE=2026-10-10", "MODEM_TIME=21:05:09", "MODEM_EPOCH=" + "1791666309"} { + if !strings.Contains(env, w+"\n") && !strings.HasSuffix(env, w) { + t.Errorf("no %s in\n%s", w, env) + } + } + if strings.Contains(strings.Join(s.environ(false), "\n"), "secret") { + t.Error("the password without pass_password") + } +} + +func TestTelnetDecode(t *testing.T) { + var sent []byte + tn := &telnet{conn: nil, term: "ANSI", local: map[byte]bool{}, remote: map[byte]bool{}} + tn.conn = &recorder{b: &sent} + in := []byte{'h', iac, will, optEcho, 'i', iac, iac, iac, do, optTType, + iac, sb, optTType, 1, iac, se, iac, do, 31, '!'} + out := tn.decode(in) + if string(out) != "hi\xff!" { + t.Errorf("data %q", out) + } + want := []byte{iac, do, optEcho, iac, will, optTType, iac, sb, optTType, 0, 'A', 'N', 'S', 'I', iac, se, iac, wont, 31} + if string(sent) != string(want) { + t.Errorf("replies % x, want % x", sent, want) + } + if got := tn.encode([]byte{'a', '\r', iac}); string(got) != "a\r\x00\xff\xff" { + t.Errorf("encode % x", got) + } +} + +func TestINI(t *testing.T) { + dir := t.TempDir() + p := filepath.Join(dir, "c.conf") + os.WriteFile(p, []byte("; comment\n[general]\nauth = file, sql\nbanner = \" hi \"\n[item bbs]\nKey = b\n"), 0o600) + c, err := parseINI(p) + if err != nil { + t.Fatal(err) + } + if g := c.section("general"); g.get("banner", "") != " hi " || len(fields(g.get("auth", ""))) != 2 { + t.Errorf("general: %v", g.vals) + } + if c.section("item bbs").get("key", "") != "b" { + t.Errorf("item: %v", c.section("item bbs").vals) + } +} + +func TestBackends(t *testing.T) { + dir := t.TempDir() + users := filepath.Join(dir, "users") + bc, _ := bcrypt.GenerateFromPassword([]byte("secret"), bcrypt.MinCost) + os.WriteFile(users, []byte("# users\nalice:"+string(bc)+":Alice\nbob:{PLAIN}a:b\n"), 0o600) + fa, err := newFileAuth(§ion{name: "file", vals: map[string]string{"path": users}}) + if err != nil { + t.Fatal(err) + } + + dbPath := filepath.Join(dir, "users.db") + db, err := sql.Open("sqlite", dbPath) + if err != nil { + t.Fatal(err) + } + if _, err := db.Exec(`CREATE TABLE users (username TEXT, password TEXT); + INSERT INTO users VALUES ('carol', '{PLAIN}pw'), ('alice', '{PLAIN}other');`); err != nil { + t.Fatal(err) + } + db.Close() + sa, err := newSQLAuth(§ion{name: "sql", vals: map[string]string{ + "driver": "sqlite", "dsn": dbPath, + "query": "SELECT password FROM users WHERE username = ?"}}) + if err != nil { + t.Fatal(err) + } + sn, err := newSQLAuth(§ion{name: "sql", vals: map[string]string{ + "driver": "sqlite", "dsn": dbPath, "args": "user password", "hash": "none", + "query": "SELECT 1 FROM users WHERE username = ? AND password = '{PLAIN}' || ?"}}) + if err != nil { + t.Fatal(err) + } + + backends := []authenticator{fa, sa} + nolog := func(string, ...any) {} + for _, c := range []struct { + user, pw, auth string + err error + }{ + {"alice", "secret", "file", nil}, + {"alice", "other", "", errBadPassword}, // the file knows alice: not asked further + {"bob", "a:b", "file", nil}, + {"carol", "pw", "sql", nil}, + {"carol", "px", "", errBadPassword}, + {"dave", "pw", "", errNoUser}, + } { + auth, err := authenticate(context.Background(), backends, c.user, c.pw, nolog) + if auth != c.auth || !errors.Is(err, c.err) && !(err == nil && c.err == nil) { + t.Errorf("%s/%s: %q %v, want %q %v", c.user, c.pw, auth, err, c.auth, c.err) + } + } + if err := sn.authenticate(context.Background(), "carol", "pw"); err != nil { + t.Errorf("hash = none: %v", err) + } + if err := sn.authenticate(context.Background(), "carol", "px"); !errors.Is(err, errNoUser) { + t.Errorf("hash = none, wrong password: %v", err) + } +} + +type recorder struct{ b *[]byte } + +func (r *recorder) Write(p []byte) (int, error) { + *r.b = append(*r.b, p...) + return len(p), nil +} diff --git a/session.go b/session.go new file mode 100644 index 0000000..b319b24 --- /dev/null +++ b/session.go @@ -0,0 +1,158 @@ +package main + +import ( + "encoding/json" + "os" + "sort" + "strconv" + "strings" + "time" +) + +// session is what is known of the call and the caller, handed to the +// selection in its environment, its command line and its session file +type session struct { + User string `json:"user"` + Password string `json:"password,omitempty"` + Auth string `json:"auth"` + Dialed string `json:"dialed"` + CallerID string `json:"callerid"` + Baud string `json:"baud"` + Rate string `json:"rate"` + TxRate string `json:"tx_rate"` + RxRate string `json:"rx_rate"` + Channel string `json:"channel"` + Profile string `json:"profile"` + Connected time.Time `json:"connected"` + Selection string `json:"selection"` +} + +// newSession from app_dmodem's environment (DMODEM_RATE "tx/rx", +// DMODEM_CALLERID, DMODEM_DIALED, DMODEM_CHANNEL, DMODEM_PROFILE), what the +// command line overrides of it +func newSession(rate, dialed, callerID string, now time.Time) *session { + s := &session{ + Dialed: dialed, + CallerID: callerID, + Channel: os.Getenv("DMODEM_CHANNEL"), + Profile: os.Getenv("DMODEM_PROFILE"), + Connected: now, + } + s.Rate = rate + tx, rx, ok := strings.Cut(rate, "/") + if !ok { + rx = tx + } + if _, err := strconv.Atoi(tx); err == nil { + s.TxRate, s.RxRate = tx, rx + // the speed the caller's modem reports: what reaches it + s.Baud = tx + } + return s +} + +// vars: the placeholders of templates and the environment, by name +func (s *session) vars(withPassword bool) map[string]string { + v := map[string]string{ + "user": s.User, + "auth": s.Auth, + "dialed": s.Dialed, + "callerid": s.CallerID, + "baud": s.Baud, + "rate": s.Rate, + "tx_rate": s.TxRate, + "rx_rate": s.RxRate, + "channel": s.Channel, + "profile": s.Profile, + "selection": s.Selection, + "date": s.Connected.Format("2006-01-02"), + "time": s.Connected.Format("15:04:05"), + "datetime": s.Connected.Format(time.RFC3339), + "epoch": strconv.FormatInt(s.Connected.Unix(), 10), + "password": "", + } + if withPassword { + v["password"] = s.Password + } + return v +} + +// environ: MODEM_ for every placeholder +func (s *session) environ(withPassword bool) []string { + v := s.vars(withPassword) + names := make([]string, 0, len(v)) + for k := range v { + names = append(names, k) + } + sort.Strings(names) + env := make([]string, 0, len(v)) + for _, k := range names { + if k == "password" && !withPassword { + continue + } + env = append(env, "MODEM_"+strings.ToUpper(k)+"="+v[k]) + } + return env +} + +// writeFile: the session as JSON in a file only its owner reads +func (s *session) writeFile(withPassword bool, uid, gid int) (string, error) { + c := *s + if !withPassword { + c.Password = "" + } + b, err := json.MarshalIndent(&c, "", " ") + if err != nil { + return "", err + } + f, err := os.CreateTemp("", "modemmenu-*.json") + if err != nil { + return "", err + } + if _, err = f.Write(append(b, '\n')); err == nil && uid >= 0 { + err = f.Chown(uid, gid) + } + if cerr := f.Close(); err == nil { + err = cerr + } + if err != nil { + os.Remove(f.Name()) + return "", err + } + return f.Name(), nil +} + +// expand replaces {name} by its value, quote() of it (nil: as is); +// unknown names stay as they are +func expand(t string, v map[string]string, quote func(string) string) string { + var b strings.Builder + for { + i := strings.IndexByte(t, '{') + if i < 0 { + break + } + j := strings.IndexByte(t[i:], '}') + if j < 0 { + break + } + name := t[i+1 : i+j] + val, ok := v[strings.ToLower(name)] + b.WriteString(t[:i]) + switch { + case !ok: + b.WriteString(t[i : i+j+1]) + case quote != nil: + b.WriteString(quote(val)) + default: + b.WriteString(val) + } + t = t[i+j+1:] + } + b.WriteString(t) + return b.String() +} + +// shellQuote: a value as one word of /bin/sh +func shellQuote(s string) string { + return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" +} diff --git a/settings.go b/settings.go new file mode 100644 index 0000000..8e4337b --- /dev/null +++ b/settings.go @@ -0,0 +1,219 @@ +package main + +import ( + "fmt" + "os" + "regexp" + "strings" + "time" +) + +type general struct { + log string + banner string + loginPrompt string + passwordPrompt string + welcome string + goodbye string + attempts int + failDelay time.Duration + loginTimeout time.Duration + idleTimeout time.Duration + userPattern *regexp.Regexp + maxInput int + mask string + auth []string +} + +type menuItem struct { + name string + key string + label string + mode string // exec, tcp, rlogin, telnet + command string + host string + port int + send string + rloginLocal string + rloginUser string + rloginTerm string + terminal string + runAs string + tty string // raw, sane + password bool + sessionFile bool + after string // hangup, menu + timeout time.Duration +} + +type settings struct { + general + menuTitle string + menuPrompt string + hangupKey string + items []*menuItem + backends []authenticator +} + +func loadSettings(path string) (*settings, error) { + c, err := parseINI(path) + if err != nil { + return nil, err + } + s := &settings{} + g := c.section("general") + s.log = g.get("log", "syslog") + s.banner = unescape(g.get("banner", `\r\nD-Modem\r\n`)) + if f := g.get("banner_file", ""); f != "" { + b, err := os.ReadFile(f) + if err != nil { + return nil, fmt.Errorf("[general] banner_file: %v", err) + } + s.banner = crlf(string(b)) + } + s.loginPrompt = unescape(g.get("login_prompt", `\r\nlogin: `)) + s.passwordPrompt = unescape(g.get("password_prompt", "Password: ")) + s.welcome = unescape(g.get("welcome", `\r\nWelcome, {user}.\r\n`)) + s.goodbye = unescape(g.get("goodbye", `\r\nGoodbye.\r\n`)) + s.mask = g.get("password_echo", "*") + if s.mask == "none" { + s.mask = "" + } + if s.attempts, err = g.int("attempts", 3); err != nil { + return nil, err + } + if s.maxInput, err = g.int("max_input", 64); err != nil { + return nil, err + } + if s.failDelay, err = g.duration("fail_delay", 3*time.Second); err != nil { + return nil, err + } + if s.loginTimeout, err = g.duration("login_timeout", 90*time.Second); err != nil { + return nil, err + } + if s.idleTimeout, err = g.duration("idle_timeout", 5*time.Minute); err != nil { + return nil, err + } + pat := g.get("user_pattern", `^[A-Za-z0-9][A-Za-z0-9._@-]{0,63}$`) + if s.userPattern, err = regexp.Compile(pat); err != nil { + return nil, fmt.Errorf("[general] user_pattern: %v", err) + } + s.auth = fields(strings.ToLower(g.get("auth", "file"))) + if len(s.auth) == 0 { + return nil, fmt.Errorf("[general] auth: no authentication backend") + } + for _, name := range s.auth { + var a authenticator + switch name { + case "file": + a, err = newFileAuth(c.section("file")) + case "ldap": + a, err = newLDAPAuth(c.section("ldap")) + case "sql": + a, err = newSQLAuth(c.section("sql")) + default: + err = fmt.Errorf("[general] auth: unknown backend %q (file, ldap, sql)", name) + } + if err != nil { + return nil, err + } + s.backends = append(s.backends, a) + } + + m := c.section("menu") + s.menuTitle = unescape(m.get("title", `\r\nMain menu\r\n`)) + s.menuPrompt = unescape(m.get("prompt", `\r\nSelection: `)) + s.hangupKey = strings.ToUpper(m.get("hangup_key", "G")) + var names []string + if m.has("items") { + names = fields(m.get("items", "")) + } else { + for _, sec := range c.sections { + if strings.HasPrefix(sec.name, "item ") { + names = append(names, strings.TrimPrefix(sec.name, "item ")) + } + } + } + keys := map[string]string{s.hangupKey: "hangup_key"} + for _, name := range names { + sec, ok := c.byName["item "+name] + if !ok { + return nil, fmt.Errorf("[menu] items: no [item %s]", name) + } + it, err := loadItem(name, sec) + if err != nil { + return nil, err + } + if prev, dup := keys[it.key]; dup { + return nil, fmt.Errorf("[item %s] key %s: also the key of %s", name, it.key, prev) + } + keys[it.key] = "[item " + name + "]" + s.items = append(s.items, it) + } + if len(s.items) == 0 { + return nil, fmt.Errorf("%s: no [item ...] in the menu", path) + } + return s, nil +} + +func loadItem(name string, sec *section) (*menuItem, error) { + var err error + it := &menuItem{name: name} + it.key = strings.ToUpper(sec.get("key", name[:1])) + if len(it.key) != 1 { + return nil, fmt.Errorf("[item %s] key: one character", name) + } + it.label = sec.get("label", name) + it.mode = strings.ToLower(sec.get("mode", "exec")) + it.command = sec.get("command", "") + it.host = sec.get("host", "127.0.0.1") + it.send = sec.get("send", "") + it.rloginLocal = sec.get("rlogin_client_user", "{password}") + it.rloginUser = sec.get("rlogin_server_user", "{user}") + it.rloginTerm = sec.get("rlogin_terminal", "ansi/{baud}") + 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")) + if it.password, err = sec.bool("pass_password", true); err != nil { + return nil, err + } + if it.sessionFile, err = sec.bool("session_file", false); err != nil { + return nil, err + } + if it.timeout, err = sec.duration("connect_timeout", 10*time.Second); err != nil { + return nil, err + } + defPort := map[string]int{"tcp": 23, "telnet": 23, "rlogin": 513}[it.mode] + if it.port, err = sec.int("port", defPort); err != nil { + return nil, err + } + switch it.mode { + case "exec": + if it.command == "" { + return nil, fmt.Errorf("[item %s] mode = exec needs a command", name) + } + case "tcp", "telnet", "rlogin": + if it.port <= 0 || it.port > 65535 { + return nil, fmt.Errorf("[item %s] port: %d", name, it.port) + } + if it.runAs != "" { + return nil, fmt.Errorf("[item %s] run_as is for mode = exec", name) + } + default: + return nil, fmt.Errorf("[item %s] mode: %q (exec, tcp, telnet or rlogin)", name, it.mode) + } + if it.tty != "raw" && it.tty != "sane" { + return nil, fmt.Errorf("[item %s] tty: %q (raw or sane)", name, it.tty) + } + if it.after != "hangup" && it.after != "menu" { + return nil, fmt.Errorf("[item %s] after: %q (hangup or menu)", name, it.after) + } + return it, nil +} + +// crlf: the line ends of a text file as the terminal wants them +func crlf(s string) string { + s = strings.ReplaceAll(s, "\r\n", "\n") + return strings.ReplaceAll(s, "\n", "\r\n") +} diff --git a/term.go b/term.go new file mode 100644 index 0000000..79d1e15 --- /dev/null +++ b/term.go @@ -0,0 +1,228 @@ +package main + +import ( + "errors" + "io" + "os" + "time" + + "golang.org/x/sys/unix" +) + +var ( + errTimeout = errors.New("timeout") + errHangup = errors.New("hangup") +) + +// term: the caller's line on stdin and stdout. app_dmodem's pty is raw +// (no echo, no line editing, no CR/LF translation): the menu echoes and +// edits lines itself. Reads poll stdin and take no more than they need, +// so that what the caller types after the menu goes to the selection. +type term struct { + in, out int + saved *unix.Termios + lastCR bool +} + +func newTerm(in, out *os.File) *term { + t := &term{in: int(in.Fd()), out: int(out.Fd())} + // a terminal of our own (a getty, a test from a console): raw as the + // pty of app_dmodem is + if tio, err := unix.IoctlGetTermios(t.in, unix.TCGETS); err == nil { + saved := *tio + t.saved = &saved + makeRaw(tio) + unix.IoctlSetTermios(t.in, unix.TCSETS, tio) + } + return t +} + +func makeRaw(t *unix.Termios) { + t.Iflag &^= unix.IGNBRK | unix.BRKINT | unix.PARMRK | unix.ISTRIP | + unix.INLCR | unix.IGNCR | unix.ICRNL | unix.IXON + t.Oflag &^= unix.OPOST + t.Lflag &^= unix.ECHO | unix.ECHONL | unix.ICANON | unix.ISIG | unix.IEXTEN + t.Cflag &^= unix.CSIZE | unix.PARENB + t.Cflag |= unix.CS8 + t.Cc[unix.VMIN] = 1 + t.Cc[unix.VTIME] = 0 +} + +// makeSane: a cooked line for programs that expect one (a shell, login) +func makeSane(t *unix.Termios) { + t.Iflag |= unix.BRKINT | unix.ICRNL | unix.IXON + t.Iflag &^= unix.INLCR | unix.IGNCR + t.Oflag |= unix.OPOST | unix.ONLCR + t.Lflag |= unix.ECHO | unix.ECHOE | unix.ECHOK | unix.ICANON | unix.ISIG | unix.IEXTEN + t.Cflag |= unix.CS8 + t.Cc[unix.VERASE] = 0x7f + t.Cc[unix.VKILL] = 'U' & 0x1f + t.Cc[unix.VINTR] = 'C' & 0x1f + t.Cc[unix.VEOF] = 'D' & 0x1f +} + +// setMode: the line raw or sane for a selection; the mode before, to +// restore (nil when stdin is no terminal) +func (t *term) setMode(mode string) *unix.Termios { + tio, err := unix.IoctlGetTermios(t.in, unix.TCGETS) + if err != nil { + return nil + } + before := *tio + if mode == "sane" { + makeSane(tio) + } else { + makeRaw(tio) + } + unix.IoctlSetTermios(t.in, unix.TCSETS, tio) + return &before +} + +func (t *term) restoreMode(tio *unix.Termios) { + if tio != nil { + unix.IoctlSetTermios(t.in, unix.TCSETS, tio) + } +} + +func (t *term) close() { + if t.saved != nil { + unix.IoctlSetTermios(t.in, unix.TCSETSW, t.saved) + } +} + +func (t *term) write(s string) error { + b := []byte(s) + for len(b) > 0 { + n, err := unix.Write(t.out, b) + if err == unix.EINTR || err == unix.EAGAIN { + pollOne(t.out, unix.POLLOUT, time.Second) + continue + } + if err != nil { + return errHangup + } + b = b[n:] + } + return nil +} + +// pollOne: whether fd is ready for ev within d (d < 0: no limit) +func pollOne(fd int, ev int16, d time.Duration) (bool, error) { + ms := -1 + if d >= 0 { + ms = int(d / time.Millisecond) + } + fds := []unix.PollFd{{Fd: int32(fd), Events: ev}} + for { + n, err := unix.Poll(fds, ms) + if err == unix.EINTR { + continue + } + if err != nil { + return false, err + } + if n == 0 { + return false, nil + } + return true, nil + } +} + +// readByte within d, or errTimeout; errHangup when the line is gone +func (t *term) readByte(d time.Duration) (byte, error) { + deadline := time.Now().Add(d) + var b [1]byte + for { + left := time.Until(deadline) + if left <= 0 { + return 0, errTimeout + } + ok, err := pollOne(t.in, unix.POLLIN, left) + if err != nil { + return 0, errHangup + } + if !ok { + return 0, errTimeout + } + n, err := unix.Read(t.in, b[:]) + if err == unix.EINTR || err == unix.EAGAIN { + continue + } + if n <= 0 || err != nil { + return 0, errHangup + } + return b[0], nil + } +} + +// readLine of at most max bytes until deadline, echoing it (or mask for +// each byte; "" for nothing). CR, LF or CR LF end it; BS and DEL erase, +// ^U the line, ^D or ^C on an empty line hang up. +func (t *term) readLine(deadline time.Time, max int, echo bool, mask string) (string, error) { + var line []byte + for { + c, err := t.readByte(time.Until(deadline)) + if err != nil { + return "", err + } + if c == '\n' && t.lastCR { + t.lastCR = false + continue + } + t.lastCR = c == '\r' + switch { + case c == '\r' || c == '\n': + return string(line), t.write("\r\n") + case c == 0x08 || c == 0x7f: + if len(line) > 0 { + line = line[:len(line)-1] + if echo || mask != "" { + t.write("\b \b") + } + } + case c == 0x15: + for range line { + if echo || mask != "" { + t.write("\b \b") + } + } + line = line[:0] + case (c == 0x03 || c == 0x04) && len(line) == 0: + return "", io.EOF + case c < 0x20 || c == 0xff: + // other control bytes, telnet IAC: not part of a name + case len(line) < max: + line = append(line, c) + switch { + case echo: + t.write(string(c)) + case mask != "": + t.write(mask) + } + } + } +} + +// readKey: one key, upper case, until deadline +func (t *term) readKey(deadline time.Time) (string, error) { + for { + c, err := t.readByte(time.Until(deadline)) + if err != nil { + return "", err + } + if c == '\n' && t.lastCR { + t.lastCR = false + continue + } + t.lastCR = c == '\r' + if c == 0x04 { + return "", io.EOF + } + if c > 0x20 && c < 0x7f { + if c >= 'a' && c <= 'z' { + c -= 'a' - 'A' + } + return string(c), nil + } + } +}