From 237ea990a556bf491ce4129dfb00f684f013b4b8 Mon Sep 17 00:00:00 2001 From: Neo <321592+Neo-Desktop@users.noreply.github.com> Date: Sun, 8 Nov 2026 05:03:36 -0800 Subject: [PATCH] CompuServe: CIM's way in (Secure Login, B+ Transport Layer, HMI pages) (#22) A CIM client (AP in its ESC I answer) now gets the GUI service instead of "?LOG CAI", following what 24high/CompuServe-Emulator recovered from WinCIM 3.0.2: - Secure Login (+ before the User ID): RA:/RB:/UR:/HR:, checked against a key kept from the password (cis_keys, bound to the password hash, kept only while a compuserve listener runs), "No." on failure - the terminal-mode trade: ESC [ > 0 q, ESC [ > 3;3 p, the parameter line's sum checked, ACK (NAK and again if wrong) - xfer.BTransport: the B Plus Transport Layer, counters per direction, 1 KB blocks, messages as M packets and a final L - HMI: session open, pages (menus as 0x27, articles as 0x28 and their text in pieces), the rest of a menu, Find, the directory lookup, acks, logoff; CIS:/HOM: names on the ASCII service's page tree Forums, Mail and CB in CIM say to use a terminal for now. Claude-Session: https://claude.ai/code/session_01B82eRRPWCkk1Ro91AuzXFM Co-authored-by: Claude --- docs/cis/04-cim-hmi.md | 20 +- docs/wiki/CompuServe.md | 44 ++- internal/bbs/bbs.go | 12 + internal/cis/cis.go | 10 +- internal/cis/hmi.go | 513 +++++++++++++++++++++++++++++++++++ internal/cis/login.go | 26 +- internal/cis/slp.go | 205 ++++++++++++++ internal/cis/slp_test.go | 40 +++ internal/server/cis_test.go | 125 ++++++++- internal/server/server.go | 4 + internal/store/cis.go | 69 +++++ internal/store/cis_test.go | 42 +++ internal/store/copy.go | 2 +- internal/store/schema.go | 5 + internal/store/store.go | 7 + internal/xfer/cisbtl.go | 260 ++++++++++++++++++ internal/xfer/cisbtl_test.go | 102 +++++++ 17 files changed, 1455 insertions(+), 31 deletions(-) create mode 100644 internal/cis/hmi.go create mode 100644 internal/cis/slp.go create mode 100644 internal/cis/slp_test.go create mode 100644 internal/store/cis.go create mode 100644 internal/store/cis_test.go create mode 100644 internal/xfer/cisbtl.go create mode 100644 internal/xfer/cisbtl_test.go diff --git a/docs/cis/04-cim-hmi.md b/docs/cis/04-cim-hmi.md index 9f59ee5..3e11e60 100644 --- a/docs/cis/04-cim-hmi.md +++ b/docs/cis/04-cim-hmi.md @@ -137,7 +137,7 @@ Server rule: | 4 | 4 | 2 (256-byte blocks) | 0 (checksum) | 0 | **1** | This is consistent with [R]: windows can exceed 1, and **TL=1 must be set for HMI**. E's own field labels differ; trust Ranshaw's order and check on the wire. -- E recommends BS = 8 (1024-byte blocks). +- E recommends BS = 8 (1024-byte blocks), and this server sends that (§4a). - Sequence counters are separate per direction. That matches [R]'s rule for the Transport Layer, as opposed to Classic B's single shared counter. - **Quirk:** WinCIM drops the first host message after B+ setup, so E sends the first ack twice. - `HMIMaxTime` in CIS.INI defaults to 120 s. Send a keepalive or ack before then. @@ -189,6 +189,24 @@ This matters for the design: **HMI and ASCII share one page/menu tree.** HMI jus --- +## 4a. What this server does (as built, milestone 7) [RE, E; tested against a fake CIM only] + +Code: `internal/cis/slp.go`, `internal/cis/hmi.go`, `internal/xfer/cisbtl.go`. Test: `TestCompuServeCIM` in `internal/server`. None of it has met a real WinCIM yet; that is milestone 9. + +- **Secure Login.** `+` at `User ID:` starts it. The host sends a random 64 to 512-byte challenge. It checks UR against the account's kept K and answers `HR:`, or `No.` on failure. K is kept (bound to the password hash, like the OSCAR keys) whenever the user logs on with a password, or sets one, while a `compuserve` listener runs. A user with no kept K logs on once with a password (WinCIM: `DisableSecureLogin=ON` in CIS.INI, or any terminal), and is logged as such. +- **After the login:** `ESC I`, the banner (which has `CompuServe` in it), `ESC [ > 0 q`, then `ESC [ > n ; n p` with mode 3 if offered (then 2, 1, 6, 8, 10). A parameter line whose sum is wrong gets NAK and the `p` again, up to three times. A good one gets ACK. +- **Transport Layer:** ENQ (up to 5 times) until `DLE + + DLE 0`. Then the host's `+` packet `04 04 08 00 00 01` (BS 8, 1 KB blocks, as E recommends, and TL=1). The counters are separate per direction. Messages over 1023 bytes go as `M` packets and a final `L`. An `F` packet ends the session. +- **HMI:** + - `0x20` gets `0x21`. The date is in standard DOS format; E's own packing differs, so check it on the wire. + - `0x24` and `0x25` give a menu as `0x27`, with item kind 0 and no title or extra blocks. An article goes as `0x28`, and its text is fetched with `0x29`/`0x2A`: 700-byte `0x04` pieces, then `0x2B`. Every line starts with a space and lines are joined with CR LF. + - `0x34` returns the rest of the items, 15 at a time. + - `0x22` (Find) returns `0x23`: up to 12 pairs of (title, page name) from the page tree's FIND. + - `0x0D` gets empty `0x0E` records. + - `0x07` hangs up. + - Everything else gets an ack on stream 1. + - The first message after the Transport Layer starts is sent twice, 300 ms apart. Every answer waits 120 ms first, as E's does. +- **Page names:** `CIS:` and `HOM:` both resolve through the ASCII service's page tree (`pages.txt`, IDs and GO words). Aliases: `NEWPAGE` → `NEW`, `CONTENTS` → `TOP`, `MAILHMI` → `MAIL`. Pages go out as `CIS:`, numbered with a 24-bit hash of the ID. `CIS:FORUMS` is the forum list. A forum, `MAIL` and `CB` are, for now, articles that say to use a terminal (milestone 8). An unknown name gets an article saying so, never nothing. + ## 5. Reverse-engineering plan for the gaps 1. **Rig.** Run WinCIM 2.x and 3.0.x under Wine or in a Win9x VM, set `CommType=WINSOCK` and point it at our server. Log every byte in both directions, with B+ decoded (doc 05 §7 calls for a wire tap in the server). diff --git a/docs/wiki/CompuServe.md b/docs/wiki/CompuServe.md index 39d204e..8b858d4 100644 --- a/docs/wiki/CompuServe.md +++ b/docs/wiki/CompuServe.md @@ -3,8 +3,8 @@ A listener with `frontend = compuserve` serves a recreation of the CompuServe Information Service instead of the BBS's menus. It runs on the BBS's own users, and it aims to work with the real CompuServe software: -terminal programs, offline readers (TAPCIS, AutoSIG, OzCIS) and, later, -the CompuServe Information Manager (WinCIM, DOSCIM, MacCIM). Their +terminal programs, offline readers (TAPCIS, AutoSIG, OzCIS) and the +CompuServe Information Manager (WinCIM, DOSCIM, MacCIM). Their scripts look for the period's exact prompts, so the service keeps them. ```ini @@ -41,9 +41,41 @@ Password: addresses get CompuServe's `?LOG` codes. After the logon the host sends `ESC I`. Terminals that know it answer -with their identification, which shows in who's online. CIM clients -(`AP` in their reply) are told `?LOG CAI` for now, because the graphical -(HMI) service is not built yet. +with their identification, which shows in who's online. A CIM client +(`AP` in its reply) gets the graphical service instead; see below. + +## CIM (WinCIM) + +CIM clients speak HMI, a binary protocol inside B Plus packets. The +service follows what 24high/CompuServe-Emulator recovered from WinCIM +3.0.2: the Secure Login, the terminal-mode trade after it, the B Plus +Transport Layer, and the HMI messages for pages. WinCIM can show the main +menu, the menus and articles of `pages.txt`, What's New and the Table of +Contents, and use Find. Forums, Mail and the CB are not in CIM yet; their +pages say to use a terminal program for now. + +Point WinCIM at the listener over TCP. In CIS.INI, the connector's +`CommType=WINSOCK`, `WinsockCommType=Local` and `HostIPAddress` set +this. CompuServe's own port for that was 4144: + +```ini +[listen wincim] +type = raw +address = :4144 +frontend = compuserve +connect = 9600 +``` + +**Secure Login.** CIM logs on with the Secure Login Protocol (`+` before +the User ID), which never sends the password. The host checks it against +a key it keeps from the password. That key is kept only while a +`compuserve` listener runs, the next time the user logs on with their +password or sets one. Until then a Secure Login fails with `No.`, and the +log says why. Log on once from a terminal, or set +`DisableSecureLogin=ON` in CIS.INI for one plain login. + +None of this has met a real WinCIM yet; that is the next round of +testing. ## Commands @@ -218,7 +250,7 @@ so only callers using the same key read each other. | Libraries on the file areas, with B+ downloads and uploads | | | CompuServe Mail on the BBS's private mail | A kept address book, binary mail | | The CB Simulator on the chat rooms | Forum conferences (CO) | -| | CIM's HMI service | +| CIM: Secure Login, the B Plus Transport Layer, HMI pages, menus, articles and Find | Forums, Mail, libraries and CB in CIM | The research behind all this, with sources, is in [docs/cis](https://github.com/D-Modem/bbs/tree/main/docs/cis). diff --git a/internal/bbs/bbs.go b/internal/bbs/bbs.go index ba504bd..57ae18e 100644 --- a/internal/bbs/bbs.go +++ b/internal/bbs/bbs.go @@ -621,9 +621,21 @@ func (b *BBS) menuLogin(who, name, pw string) (*store.User, error) { } b.Log.Printf("%s: %s's password by modemmenu (%s)", who, u.Name, backend) b.Store.KeepOSCARKeys(u.ID, pw) // for AIM's digest logins, if kept + b.Store.KeepCISKey(u.ID, pw) // and CompuServe's return u, nil } +// LoginWith logs in the account check vouches for (how, for the log), +// throttled, delayed and counted as a password login is: check returns +// store.ErrNotFound for a failure. CompuServe's Secure Login is one. +func (n *Node) LoginWith(name, how string, check func() (*store.User, error)) (*store.User, error) { + u, err := n.b.authenticate(fmt.Sprintf("node %d", n.Num), n.Caller.Source, name, check) + if err != nil { + return nil, err + } + return n.loggedIn(u, how) +} + // LoginTrusted logs in a user an upstream menu vouched for (Caller's // TrustedUser). With create, a user unknown here gets an external account. func (n *Node) LoginTrusted(name string, create bool) (*store.User, error) { diff --git a/internal/cis/cis.go b/internal/cis/cis.go index bcac0b0..e5886dd 100644 --- a/internal/cis/cis.go +++ b/internal/cis/cis.go @@ -6,8 +6,9 @@ // match these strings, so they keep the period's wording. // // Users are the BBS's: a User ID is the account's number written as a -// CompuServe ID (PPN), or its name. The GUI service (CIM's HMI, over B -// Plus) is not here yet: a CIM client is told "?LOG CAI". +// CompuServe ID (PPN), or its name. A CIM client (one whose ESC I answer +// has AP) gets the GUI service instead: HMI over the B Plus Transport +// Layer (hmi.go). package cis import ( @@ -102,10 +103,7 @@ func (s *session) run() error { return err } if s.caps.AP() { - // a CIM client: its HMI service is to come - s.b.Log.Printf("node %d: CompuServe: %s is a CIM client (%s); HMI not yet served", s.node.Num, u.Name, s.caps.Raw) - s.out("\n?LOG CAI\n") - return errHangup + return s.hmi() // a CIM client } err = s.ascii() if !errors.Is(err, errRelog) { diff --git a/internal/cis/hmi.go b/internal/cis/hmi.go new file mode 100644 index 0000000..496ef80 --- /dev/null +++ b/internal/cis/hmi.go @@ -0,0 +1,513 @@ +package cis + +// CIM's service: the Host-Micro Interface (HMI) over the B Plus Transport +// Layer, as WinCIM 3.0.2 speaks it (recovered by 24high/CompuServe-Emulator, +// HMI-PROTOKOLL.md, and checked there against the real client). After the +// login and ESC I: +// +// H→C text with "CompuServe" in it (the banner) +// H→C ESC [ > 0 q C→H "#1,2,3,6,8,10" CR (its modes) +// H→C ESC [ > 3 ; 3 p C→H "#3,2,1,4,2,0;614" CR +// H→C ACK (NAK: the line's sum was wrong) +// ... the Transport Layer (xfer.BTransport), then HMI messages: +// +// +// Fields are bytes, words and 24-bit numbers (low byte first), varints (a +// byte, or b1|0x80 and b2 for b2<<7 | b1&0x7F), NUL-ended text (never +// empty where the client needs one: WinCIM crashes on a null name) and DOS +// dates. What this serves: the session's opening, the pages (menus as +// 0x27, articles as 0x28 and their text in pieces), the rest of a menu's +// items (0x34), Find (0x22), the directory lookup (0x0D), acks for the +// rest, and the logoff. Forums, Mail and the CB in CIM are still to come: +// their pages say so. + +import ( + "errors" + "fmt" + "hash/fnv" + "strconv" + "strings" + "time" + + "github.com/D-Modem/bbs/internal/xfer" +) + +// HMI message types +const ( + hmiAck = 0x01 + hmiText = 0x04 // a piece of an article's text + hmiLogoff = 0x07 + hmiLookup = 0x0D + hmiLookupAns = 0x0E + hmiOpen = 0x20 + hmiOpenAns = 0x21 + hmiFind = 0x22 + hmiFindAns = 0x23 + hmiGet = 0x24 + hmiSelect = 0x25 + hmiPage = 0x27 + hmiArticle = 0x28 + hmiTextFirst = 0x29 + hmiTextNext = 0x2A + hmiTextEnd = 0x2B + hmiGetItems = 0x34 + hmiItems = 0x35 +) + +// hmiBatch is the most items a 0x35 carries: the client asks again only +// when it gets this many. +const hmiBatch = 15 + +// hmiPiece is the most text a 0x04 carries (WinCIM asks for 1500; it must +// fit a packet). +const hmiPiece = 700 + +// hmiW builds a message's fields. +type hmiW []byte + +func (w hmiW) byte(v int) hmiW { return append(w, byte(v)) } +func (w hmiW) word(v int) hmiW { return append(w, byte(v), byte(v>>8)) } +func (w hmiW) triple(v int) hmiW { return append(w, byte(v), byte(v>>8), byte(v>>16)) } +func (w hmiW) varint(v int) hmiW { + if v < 0x80 { + return append(w, byte(v)) + } + return append(w, byte(v)|0x80, byte(v>>7)) +} + +// text is s in Latin-1, NUL-ended; "" is a space, never a null name. +func (w hmiW) text(s string) hmiW { + if s == "" { + s = " " + } + for _, r := range s { + if r > 0xFF || r == 0 { + r = '?' + } + w = append(w, byte(r)) + } + return append(w, 0) +} + +// date is t as DOS's date and time words. +func (w hmiW) date(t time.Time) hmiW { + y := max(t.Year()-1980, 0) + return w.word(t.Day() | int(t.Month())<<5 | (y&0x7F)<<9). + word(t.Second()/2 | t.Minute()<<5 | t.Hour()<<11) +} + +// hmiR reads a message's fields; past the end it gives zeros. +type hmiR struct { + b []byte + i int +} + +func (r *hmiR) byte() int { + if r.i >= len(r.b) { + return 0 + } + r.i++ + return int(r.b[r.i-1]) +} +func (r *hmiR) word() int { return r.byte() | r.byte()<<8 } +func (r *hmiR) varint() int { + b := r.byte() + if b&0x80 == 0 { + return b + } + return r.byte()<<7 | b&0x7F +} +func (r *hmiR) text() string { + j := r.i + for j < len(r.b) && r.b[j] != 0 { + j++ + } + s := make([]rune, 0, j-r.i) + for _, c := range r.b[r.i:j] { + s = append(s, rune(c)) + } + r.i = min(j+1, len(r.b)) + return string(s) +} + +// hmi is a CIM's session, from the banner to its logoff. +func (s *session) hmi() error { + s.node.Doing("CompuServe: CIM") + s.banner() + mode, params, err := s.negotiate() + if err != nil { + return err + } + s.b.Log.Printf("node %d: CompuServe: %s's CIM (%s) in mode %d (%s)", s.node.Num, s.user.Name, s.caps.Raw, mode, params) + t, err := xfer.NewBTransport(port{s}, 5*time.Second) + if err != nil { + return fmt.Errorf("cis: CIM's Transport Layer: %w", err) + } + h := &hmiSession{s: s, t: t, made: map[string]*Page{}} + return h.run() +} + +// negotiate is the terminal mode's trade after the login: the modes the +// client has, the one chosen, its parameters and their sum. +func (s *session) negotiate() (mode int, params string, err error) { + s.out("\x1b[>0q") + modes, err := s.hashLine(8 * time.Second) + if err != nil { + return 0, "", err + } + mode = pickMode(modes) + if mode < 0 { + return 0, "", fmt.Errorf("cis: no CIM mode in %q", modes) + } + for try := 0; try < 3; try++ { + s.outf("\x1b[>%d;%dp", mode, mode) + params, err = s.hashLine(10 * time.Second) + if err != nil { + return 0, "", err + } + if paramsOK(params) { + s.line.Write([]byte{0x06}) + return mode, params, nil + } + s.line.Write([]byte{0x15}) + } + return 0, "", fmt.Errorf("cis: CIM's parameters %q: their sum is wrong", params) +} + +// hashLine reads the client's next line that begins with '#', within d. +// The CR LF after its Secure Login's last block comes first, so a line +// without the '#' is passed over. +func (s *session) hashLine(d time.Duration) (string, error) { + deadline := time.Now().Add(d) + var b []byte + for { + left := time.Until(deadline) + if left <= 0 { + return "", errHangup + } + c, err := s.getc(left) + if errors.Is(err, errIdle) { + return "", errHangup + } + if err != nil { + return "", err + } + switch { + case c == '\r' || c == '\n': + if len(b) > 0 && b[0] == '#' { + s.cr = c == '\r' + return string(b), nil + } + b = b[:0] + case c >= 0x20 && len(b) < 200: + b = append(b, c) + } + } +} + +// pickMode is the mode to use of the client's "#1,2,3,6,8,10": 3, the one +// WinCIM 3.0.2 is known to work in, if it is there. +func pickMode(line string) int { + var have []int + for _, f := range strings.Split(strings.TrimPrefix(line, "#"), ",") { + if n, err := strconv.Atoi(strings.TrimSpace(f)); err == nil { + have = append(have, n) + } + } + for _, want := range []int{3, 2, 1, 6, 8, 10} { + for _, n := range have { + if n == want { + return n + } + } + } + if len(have) > 0 { + return have[0] + } + return -1 +} + +// paramsOK checks "#3,2,1,4,2,0;614": the number is the sum of the +// characters through the ';'. +func paramsOK(line string) bool { + i := strings.LastIndexByte(line, ';') + if i < 0 { + return false + } + n, err := strconv.Atoi(strings.TrimSpace(line[i+1:])) + if err != nil { + return false + } + sum := 0 + for j := 0; j <= i; j++ { + sum += int(line[j]) + } + return sum&0xFFFF == n +} + +// hmiSession is the HMI's state: the article being fetched, and the pages +// made for names that are no page of the service's. +type hmiSession struct { + s *session + t *xfer.BTransport + settled bool // the first message has gone (twice) + text []byte + made map[string]*Page + // delay is the wait before each answer, as the emulator that was + // checked against WinCIM waits. + delay time.Duration +} + +func (h *hmiSession) run() error { + s := h.s + if h.delay == 0 { + h.delay = 120 * time.Millisecond + } + idle := s.b.Conf().IdleTimeout + if idle <= 0 { + idle = 5 * time.Minute + } + for { + m, err := h.t.Recv(idle) + if errors.Is(err, xfer.ErrTimeout) { + s.b.Log.Printf("node %d: CompuServe: %s's CIM went quiet", s.node.Num, s.user.Name) + return errHangup + } + if errors.Is(err, xfer.ErrTLFailed) { + return errHangup + } + if err != nil { + return err + } + if len(m) < 2 { + continue + } + stream, typ := int(m[0]), m[1] + if typ == hmiLogoff { + s.b.Log.Printf("node %d: CompuServe: %s's CIM logged off", s.node.Num, s.user.Name) + return errHangup + } + reply := h.answer(stream, typ, &hmiR{b: m[2:]}) + if reply == nil { + continue + } + time.Sleep(h.delay) + if err := h.t.Send(reply); err != nil { + return err + } + if !h.settled { + // WinCIM drops the first message after the Transport Layer's + // start, however long the wait: it is sent again, once (more + // would be taken for the answers to come) + h.settled = true + time.Sleep(300 * time.Millisecond) + if err := h.t.Send(reply); err != nil { + return err + } + } + } +} + +// answer is the reply to a message: stream, type, fields. +func (h *hmiSession) answer(stream int, typ byte, r *hmiR) []byte { + msg := func(t byte, w hmiW) []byte { return append([]byte{byte(stream), t}, w...) } + switch typ { + case hmiOpen: + r.word() + p := h.lookup(r.text()) + return msg(hmiOpenAns, hmiW{}.word(0).date(h.s.now()). + text("CompuServe Information Service").text("CIS").text(p.Title).varint(0)) + case hmiGet: + return h.deliver(stream, h.lookup(r.text())) + case hmiSelect: + p := h.lookup(r.text()) + i := r.varint() + if i >= 1 && i <= len(p.Items) { + p = h.lookup(p.Items[i-1].Target) + } + return h.deliver(stream, p) + case hmiGetItems: + p := h.lookup(r.text()) + r.byte() + from := r.varint() + var w hmiW + n := 0 + for i := max(from-1, 0); i < len(p.Items) && n < hmiBatch; i++ { + w = w.byte(i + 1).byte(0).text(p.Items[i].Text) + n++ + } + return msg(hmiItems, append(hmiW{}.byte(n), w...)) + case hmiTextFirst: + p := h.lookup(r.text()) + r.word() + h.text = articleText(p) + return h.piece(stream, hmiTextFirst, r.word()) + case hmiTextNext: + return h.piece(stream, hmiTextNext, r.word()) + case hmiFind: + r.byte() + var w hmiW + n := 0 + for _, p := range h.s.pages.Find(r.text()) { + if n == 12 { // one message, in one packet + break + } + w = w.text(p.Title + " - " + p.ID).text(hmiName(p)) + n++ + } + return msg(hmiFindAns, append(hmiW{}.byte(n), w...)) + case hmiLookup: + if r.byte()&0x80 != 0 { + r.word() + } + // an empty record for each name asked for + return msg(hmiLookupAns, make(hmiW, r.byte())) + } + // the keep-alive (0x0F), the session request (0x0B) and the rest: an + // ack, always on stream 1 (the only one open from the start) + return []byte{1, hmiAck, typ} +} + +// deliver is a page as the client takes it: a menu's description, or an +// article's header (the client then fetches its text). +func (h *hmiSession) deliver(stream int, p *Page) []byte { + if !p.Menu() { + h.text = articleText(p) + return append([]byte{byte(stream), hmiArticle}, + hmiW{}.text(hmiName(p)).triple(pageNumber(p)).byte(0).word(0)...) + } + n := min(len(p.Items), 255) + w := hmiW{}.byte(0).text(hmiName(p)).triple(pageNumber(p)).byte(n). + varint(0).word(0).byte(0).byte(0) + for i, it := range p.Items[:n] { + w = w.byte(i + 1).byte(0).text(it.Text) + } + return append([]byte{byte(stream), hmiPage}, w...) +} + +// piece is the next piece of the article being fetched, or its end. +func (h *hmiSession) piece(stream int, asked byte, most int) []byte { + if len(h.text) == 0 { + h.text = nil + return []byte{byte(stream), hmiTextEnd, 0} + } + if most <= 0 || most > hmiPiece { + most = hmiPiece + } + n := min(most, len(h.text)) + part := h.text[:n] + h.text = h.text[n:] + w := append(hmiW{}.byte(int(asked)), part...) + return append([]byte{byte(stream), hmiText}, append(w, 0)...) +} + +// articleText is a page's text as WinCIM's text window wants it: Latin-1, +// lines joined by CR LF, each starting with a space (a line that does not +// is run on to the one before). +func articleText(p *Page) []byte { + lines := p.Text + if p.Menu() { + lines = append(append([]string{}, lines...), "") + for i, it := range p.Items { + lines = append(lines, fmt.Sprintf("%2d %s", i+1, it.Text)) + } + } + if len(lines) == 0 { + lines = []string{p.Title} + } + var b hmiW + for i, l := range lines { + if i > 0 { + b = append(b, '\r', '\n') + } + if !strings.HasPrefix(l, " ") { + b = append(b, ' ') + } + b = b.text(l) + b = b[:len(b)-1] // its NUL + } + return b +} + +// hmiName is a page's name in HMI: CIS: and its ID. +func hmiName(p *Page) string { return "CIS:" + p.ID } + +// pageNumber is a page's number: a hash of its ID, never 0. +func pageNumber(p *Page) int { + f := fnv.New32a() + f.Write([]byte(p.ID)) + n := int(f.Sum32() & 0xFFFFFF) + if n == 0 { + n = 1 + } + return n +} + +// hmiAliases are the names WinCIM's buttons and GO box ask for that are a +// page of the service's under another ID: CIS:NEWPAGE is What's New, +// CIS:CONTENTS the Table of Contents, HOM:MAILHMI the mail (GO MAIL in +// the box). +var hmiAliases = map[string]string{ + "NEWPAGE": "NEW", + "CONTENTS": "TOP", + "MAILHMI": "MAIL", + "HOME": "TOP", +} + +// lookup is the page a name stands for: "CIS:TOP", "HOM:FORUMS", a GO +// word. A name that is none gets a page saying so: the client must never +// be left without one. +func (h *hmiSession) lookup(name string) *Page { + name = strings.ToUpper(strings.TrimSpace(name)) + if name == "" { + name = "CIS:TOP" + } + if p := h.made[name]; p != nil { + return p + } + w := name + if i := strings.IndexByte(w, ':'); i >= 0 && i <= 3 { + w = w[i+1:] + } + if a, ok := hmiAliases[w]; ok && h.s.pages.Get(w) == nil { + w = a + } + s := h.s + var p *Page + if f := s.forum(w); f != nil && s.pages.Get(w) == nil { + p = &Page{ID: f.Go, Title: f.Name, Text: []string{ + " " + f.Name, + "", + " Forums are not in CIM here yet: a terminal program reaches", + " this one with GO " + f.Go + ".", + }} + } else if p = s.pages.Get(w); p != nil { + switch p.ID { + case "FORUMS": + p = s.forumsPage() + if !p.Menu() { + p.Text = []string{" There are no forums here yet."} + } + case "MAIL", "CB": + what := map[string]string{"MAIL": "CompuServe Mail", "CB": "The CB Simulator"}[p.ID] + p = &Page{ID: p.ID, Title: p.Title, Text: []string{ + " " + what + " is not in CIM here yet: a terminal program", + " reaches it with GO " + p.ID + ".", + }} + } + } else { + p = &Page{ID: w, Title: "CompuServe", Text: []string{ + " " + w + " is not a service here.", + "", + " GO TOP, or Find, leads to what there is.", + }} + } + if p.ID == "" { + p.ID = "TOP" + } + if p.Title == "" { + p.Title = "CompuServe" + } + h.made[name] = p + return p +} diff --git a/internal/cis/login.go b/internal/cis/login.go index e6c5452..8011edf 100644 --- a/internal/cis/login.go +++ b/internal/cis/login.go @@ -151,14 +151,6 @@ func (s *session) login() (*store.User, error) { try-- continue } - s.out("Password: ") - pw, err := s.input(false, s.b.Conf().LoginTimeout) - if errors.Is(err, errAbort) { - continue - } - if err != nil { - return nil, s.loginErr(err) - } name := id.ID s.byName = true if n, ok := ParsePPN(id.ID); ok { @@ -166,13 +158,29 @@ func (s *session) login() (*store.User, error) { name, s.byName = u.Name, false } } - u, err := s.node.Login(name, pw) + var u *store.User + if id.Secure { + u, err = s.secureLogin(name) + } else { + s.out("Password: ") + var pw string + pw, err = s.input(false, s.b.Conf().LoginTimeout) + if errors.Is(err, errAbort) { + continue + } + if err != nil { + return nil, s.loginErr(err) + } + u, err = s.node.Login(name, pw) + } switch { case err == nil: if id.Go != "" { s.firstGo = id.Go } return u, nil + case errors.Is(err, bbs.ErrBadLogin) && id.Secure: + s.out("No.\n") // CIM's script says "Incorrect User ID or password" case errors.Is(err, bbs.ErrBadLogin): s.out("\n?? LOGINE - Invalid entry - try again\n") case errors.Is(err, bbs.ErrLocked): diff --git a/internal/cis/slp.go b/internal/cis/slp.go new file mode 100644 index 0000000..d1bb371 --- /dev/null +++ b/internal/cis/slp.go @@ -0,0 +1,205 @@ +package cis + +import ( + "crypto/md5" + "crypto/rand" + "crypto/subtle" + "encoding/base64" + "errors" + mrand "math/rand/v2" + "strings" + "time" + + "github.com/D-Modem/bbs/internal/store" +) + +// CompuServe's Secure Login Protocol, as WinCIM 3.0.2 does it (recovered +// from CCTN240C.DLL by 24high/CompuServe-Emulator, SECURE-LOGIN.md, with +// its test vectors): +// +// H→C "RA:" CR LF HostChallenge "." CR LF +// C→H "RB:" CR LF MicroChallenge "." CR LF +// C→H "UR:" CR LF UserResponse "." CR LF +// H→C "HR:" CR LF HostResponse "." CR LF (or "No.") +// +// Each value is Base64 of its bytes and a checksum byte, in lines of 76 +// split by a CR. K = MD5(UTF-16BE(lowercase password)) (store.CISKeyOf), +// Z 48 zero bytes: +// +// UserResponse = MD5(K Z H M K) +// HostResponse = MD5(K Z M H K) + +// slpSum is the checksum: a 16-bit ones'-complement sum of little-endian +// words, folded to 8 bits and inverted. +func slpSum(data []byte) byte { + var sum uint32 + i := 0 + for ; len(data)-i > 1; i += 2 { + sum += uint32(data[i]) | uint32(data[i+1])<<8 + } + if i < len(data) { + sum += uint32(data[i]) + } + for sum&0xFFFF0000 != 0 { + sum = sum>>16 + sum&0xFFFF + } + for sum&0xFFFFFF00 != 0 { + sum = sum&0xFF + sum>>8 + } + return ^byte(sum) +} + +// slpEncode is data and its checksum in Base64, CR every 76. +func slpEncode(data []byte) string { + s := base64.StdEncoding.EncodeToString(append(append([]byte{}, data...), slpSum(data))) + var b strings.Builder + for len(s) > 76 { + b.WriteString(s[:76] + "\r") + s = s[76:] + } + b.WriteString(s) + return b.String() +} + +var errSLP = errors.New("cis: bad Secure Login value") + +// slpDecode is a value's bytes, its checksum checked. White space is +// skipped, and "." ends it. +func slpDecode(s string) ([]byte, error) { + if i := strings.IndexByte(s, '.'); i >= 0 { + s = s[:i] + } + s = strings.Map(func(r rune) rune { + if r == ' ' || r == '\r' || r == '\n' || r == '\t' { + return -1 + } + return r + }, s) + if len(s) == 0 || len(s) > 1000 || len(s)%4 != 0 { + return nil, errSLP + } + b, err := base64.StdEncoding.DecodeString(s) + if err != nil || len(b) < 2 || slpSum(b[:len(b)-1]) != b[len(b)-1] { + return nil, errSLP + } + return b[:len(b)-1], nil +} + +func slpDigest(parts ...[]byte) []byte { + h := md5.New() + for _, p := range parts { + h.Write(p) + } + return h.Sum(nil) +} + +var slpZ = make([]byte, 48) + +// slpUser is the UserResponse the client must send. +func slpUser(k, host, micro []byte) []byte { return slpDigest(k, slpZ, host, micro, k) } + +// slpHost is the HostResponse that proves the host knows K. +func slpHost(k, host, micro []byte) []byte { return slpDigest(k, slpZ, micro, host, k) } + +// secureLogin is the Secure Login of name, through the BBS's login (its +// throttling and delays). The account needs its key kept: a password +// login, or a password set, while a CompuServe listener ran. +func (s *session) secureLogin(name string) (*store.User, error) { + return s.node.LoginWith(name, "CompuServe Secure Login", func() (*store.User, error) { + host := make([]byte, 64+mrand.IntN(0x201-64)) + rand.Read(host) + s.out("RA:\n" + slpEncode(host) + ".\n") + micro, user, err := s.readSecure() + if err != nil { + if errors.Is(err, errSLP) { + return nil, store.ErrNotFound + } + return nil, err + } + u, err := s.b.Store.UserByName(name) + if err != nil { + return nil, err // not found: a failure + } + k, ok, err := s.b.Store.CISKey(u.ID) + if err != nil { + return nil, err + } + if !ok { + s.b.Log.Printf("node %d: CompuServe: no Secure Login key kept for %s: they log on once with their password (CIM: DisableSecureLogin=ON)", s.node.Num, u.Name) + return nil, store.ErrNotFound + } + if subtle.ConstantTimeCompare(user, slpUser(k, host, micro)) != 1 { + return nil, store.ErrNotFound + } + s.out("HR:\n" + slpEncode(slpHost(k, host, micro)) + ".\n") + return u, nil + }) +} + +// readSecure reads the client's RB: and UR: blocks; an ETX instead is its +// script giving up (errSLP). +func (s *session) readSecure() (micro, user []byte, err error) { + var b []byte + deadline := time.Now().Add(60 * time.Second) + for time.Now().Before(deadline) { + c, err := s.getc(time.Until(deadline)) + if err != nil { + if errors.Is(err, errIdle) { + break + } + return nil, nil, err + } + if c == 3 { + return nil, nil, errSLP + } + b = append(b, c) + if len(b) > 4096 { + return nil, nil, errSLP + } + t := string(b) + rb := strings.Index(t, "RB:") + if rb < 0 { + continue + } + d1 := strings.IndexByte(t[rb:], '.') + if d1 < 0 { + continue + } + ur := strings.Index(t[rb+d1:], "UR:") + if ur < 0 { + continue + } + ur += rb + d1 + d2 := strings.IndexByte(t[ur:], '.') + if d2 < 0 { + continue + } + s.cr = false + if micro, err = slpDecode(t[rb+3 : rb+d1]); err != nil { + return nil, nil, err + } + if user, err = slpDecode(t[ur+3 : ur+d2]); err != nil { + return nil, nil, err + } + return micro, user, nil + } + return nil, nil, errSLP +} + +// SecureAnswer is the client's side of the Secure Login, for tests: from +// the host's RA: value, the RB: and UR: values a CIM sends, and a check of +// the host's HR: value. +func SecureAnswer(password, ra string) (rb, ur string, hostOK func(hr string) bool, err error) { + host, err := slpDecode(ra) + if err != nil { + return "", "", nil, err + } + micro := make([]byte, 64+mrand.IntN(0x201-64)) + rand.Read(micro) + k := store.CISKeyOf(password) + want := slpHost(k, host, micro) + return slpEncode(micro), slpEncode(slpUser(k, host, micro)), func(hr string) bool { + got, err := slpDecode(hr) + return err == nil && subtle.ConstantTimeCompare(got, want) == 1 + }, nil +} diff --git a/internal/cis/slp_test.go b/internal/cis/slp_test.go new file mode 100644 index 0000000..5a47559 --- /dev/null +++ b/internal/cis/slp_test.go @@ -0,0 +1,40 @@ +package cis + +import ( + "testing" + + "github.com/D-Modem/bbs/internal/store" +) + +// TestSLP: the vectors of SECURE-LOGIN.md, checked there against WinCIM +// 3.0.2's own routines. +func TestSLP(t *testing.T) { + k := store.CISKeyOf("Test123") + host := make([]byte, 96) + for i := range host { + host[i] = byte(i*3 + 1) + } + micro := make([]byte, 130) + for i := range micro { + micro[i] = byte(255 - i*5) + } + if got := slpEncode(slpUser(k, host, micro)); got != "Np0kkHKUf23uvI403FLnxDk=" { + t.Errorf("UserResponse %s", got) + } + if got := slpEncode(slpHost(k, host, micro)); got != "oGVMq5T24l/3+UTs2i1QiS8=" { + t.Errorf("HostResponse %s", got) + } + enc := slpEncode(micro) + if len(enc) < 77 || enc[76] != '\r' { + t.Errorf("not split at 76: %q", enc) + } + back, err := slpDecode(enc + ".") + if err != nil || string(back) != string(micro) { + t.Errorf("decoded %v", err) + } + bad := []byte(enc) + bad[3] ^= 1 + if _, err := slpDecode(string(bad)); err == nil { + t.Error("a bad checksum passed") + } +} diff --git a/internal/server/cis_test.go b/internal/server/cis_test.go index ed1d72c..9787a5a 100644 --- a/internal/server/cis_test.go +++ b/internal/server/cis_test.go @@ -1,12 +1,15 @@ package server import ( + "bytes" "strconv" "strings" "testing" "time" "github.com/D-Modem/bbs/internal/bbs" + "github.com/D-Modem/bbs/internal/cis" + "github.com/D-Modem/bbs/internal/xfer" ) func cisListener() *Listener { @@ -80,8 +83,44 @@ func TestCompuServe(t *testing.T) { // TestCompuServeCIM: a CIM client (AP in its identification) is turned // away with ?LOG CAI until the HMI service is here. +// cimReply is a CIM's ESC I answer, its sum after the '+'. +func cimReply() string { + reply := "#WINCIM:3.0.1:WN6,PB,DT,CA,GF,GJ,GP,+,MS,AP,PB,LA1,CH1,CO0,+" + sum := 0 + for i := 0; i < len(reply); i++ { + sum += int(reply[i]) + } + return reply + strconv.Itoa(sum) + "\r" +} + +// cimStart is a CIM's side after its login: the ESC I answer, the terminal +// mode's trade (once with a bad sum), the Transport Layer. +func cimStart(t *testing.T, d *dialog) *xfer.BTransport { + t.Helper() + d.expect("\x1bI") + d.send(cimReply()) + d.expect("CompuServe Information Service") + d.expect("\x1b[>0q") + d.send("#1,2,3,6,8,10\r") + d.expect("\x1b[>3;3p") + d.send("#3,2,1,4,2,0;613\r") + d.expect("\x15") + d.expect("\x1b[>3;3p") + d.send("#3,2,1,4,2,0;614\r") + d.expect("\x06") + tl, err := xfer.AnswerTL(d.port(), []byte{4, 4, 8, 0, 0, 1}, 2*time.Second) + if err != nil { + t.Fatalf("Transport Layer: %v", err) + } + return tl +} + +// TestCompuServeCIM: WinCIM's way in, as recovered from it: a password +// login (which keeps the Secure Login key), the mode's trade, the B Plus +// Transport Layer, and HMI to the main menu, an article and the rest; +// then a Secure Login. func TestCompuServeCIM(t *testing.T) { - e := start(t, nil, cisListener()) + e := start(t, func(s *bbs.Settings) { s.FailDelay = 0 }, cisListener()) d := e.dial("cis.sock") d.expect("Host Name: ") d.send("CPS\r") @@ -89,14 +128,54 @@ func TestCompuServeCIM(t *testing.T) { d.send("alice\r") d.expect("Password: ") d.send("alicepass1\r") - d.expect("\x1bI") - reply := "#WINCIM:3.0.1:WN6,PB,DT,CA,GF,AP,+" - sum := 0 - for i := 0; i < len(reply); i++ { - sum += int(reply[i]) + tl := cimStart(t, d) + + ask := func(m []byte, want ...byte) []byte { + t.Helper() + if err := tl.Send(m); err != nil { + t.Fatalf("send % x: %v", m, err) + } + got, err := tl.Recv(5 * time.Second) + if err != nil { + t.Fatalf("after % x: %v", m, err) + } + if !bytes.HasPrefix(got, want) { + t.Fatalf("after % x: got % x, want % x...", m, got, want) + } + return got + } + // the first answer comes twice + ask([]byte{3, 0x0F}, 1, 1, 0x0F) + if got, err := tl.Recv(5 * time.Second); err != nil || !bytes.Equal(got, []byte{1, 1, 0x0F}) { + t.Fatalf("the first ack again: % x %v", got, err) + } + ask([]byte{1, 0x0B}, 1, 1, 0x0B) + got := ask(append([]byte{1, 0x20, 0, 0}, "CIS:TOP\x00"...), 1, 0x21, 0, 0) + if !bytes.Contains(got, []byte("\x00CIS\x00")) { + t.Errorf("open: % x", got) + } + got = ask(append([]byte{1, 0x24}, "CIS:TOP\x00"...), append([]byte{1, 0x27, 0}, "CIS:TOP\x00"...)...) + if got[3+8+3] != 12 || !bytes.Contains(got, []byte("\x01\x00Member Assistance (FREE)\x00")) { + t.Errorf("TOP: %q", got) + } + ask(append([]byte{1, 0x34}, "CIS:TOP\x00\x00\x0D"...), 1, 0x35, 0) + got = ask(append([]byte{1, 0x25}, "CIS:TOP\x00\x01"...), append([]byte{1, 0x27, 0}, "CIS:MEMBER\x00"...)...) + ask(append([]byte{1, 0x24}, "HOM:MAILHMI\x00"...), append([]byte{1, 0x28}, "CIS:MAIL\x00"...)...) + got = ask(append([]byte{1, 0x29}, "CIS:MAIL\x00\x00\x00\xDC\x05"...), 1, 0x04, 0x29, ' ') + if !bytes.Contains(got, []byte("CompuServe Mail")) { + t.Errorf("mail's text: %q", got) + } + ask([]byte{1, 0x2A, 0xDC, 0x05}, 1, 0x2B, 0) + ask(append([]byte{1, 0x24}, "CIS:NEWPAGE\x00"...), append([]byte{1, 0x28}, "CIS:NEW\x00"...)...) + ask(append([]byte{1, 0x24}, "HOM:XYZZY\x00"...), append([]byte{1, 0x28}, "CIS:XYZZY\x00"...)...) + got = ask(append([]byte{1, 0x22, 0x14}, "rates\x00"...), 1, 0x23) + if got[2] == 0 || !bytes.Contains(got, []byte("CIS:RATES\x00")) { + t.Errorf("find: %q", got) + } + ask(append([]byte{1, 0x0D, 0xBF, 4, 0, 2}, "CSRV\x00HRB\x00"...), 1, 0x0E, 0, 0) + if err := tl.Send([]byte{1, 0x07}); err != nil { + t.Fatal(err) } - d.send(reply + strconv.Itoa(sum) + "\r") - d.expect("?LOG CAI") d.c.SetReadDeadline(time.Now().Add(5 * time.Second)) buf := make([]byte, 64) for { @@ -104,4 +183,34 @@ func TestCompuServeCIM(t *testing.T) { break // hung up } } + + // the Secure Login, with the key the password login kept + secure := func(pw string) *dialog { + d := e.dial("cis.sock") + d.expect("Host Name: ") + d.send("CPS\r") + d.expect("User ID: ") + d.send("+72000,1/INT:60\r") + d.expect("RA:\r\n") + d.expect(".\r\n") + rb, ur, hostOK, err := cis.SecureAnswer(pw, string(d.before)) + if err != nil { + t.Fatal(err) + } + d.send("RB:\r\n" + rb + ".\r\nUR:\r\n" + ur + ".\r\n") + if pw != "alicepass1" { + d.expect("No.\r\n") + return d + } + d.expect("HR:\r\n") + d.expect(".\r\n") + if !hostOK(string(d.before)) { + t.Errorf("the host's HR: %q", d.before) + } + return d + } + secure("wrong") + d = secure("alicepass1") + tl = cimStart(t, d) + ask([]byte{3, 0x0F}, 1, 1, 0x0F) } diff --git a/internal/server/server.go b/internal/server/server.go index d02a764..3571d39 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -118,6 +118,10 @@ func (s *Server) Run(ctx context.Context) error { } } for _, l := range s.Listeners { + if l.Frontend == "compuserve" { + // CIM's Secure Login needs a key made from each password + s.B.Store.SetKeepCIS(true) + } if l.Kind == "ssh" { if err := s.sshSetup(l); err != nil { closeAll() diff --git a/internal/store/cis.go b/internal/store/cis.go new file mode 100644 index 0000000..eca2e24 --- /dev/null +++ b/internal/store/cis.go @@ -0,0 +1,69 @@ +package store + +import ( + "crypto/md5" + "database/sql" + "errors" + "unicode" +) + +// CompuServe's Secure Login (WinCIM's "+" User ID) proves the password by +// MD5 digests of a key made from it, K = MD5(UTF-16BE(lowercase password)), +// which a bcrypt hash cannot give. So K is kept, like the AIM digests +// (oscar.go): whenever the password is known in the clear, and bound to +// the password hash it was made with, so a password changed some other way +// leaves it stale and unused. + +// CISKeyOf is the Secure Login key of a password. +func CISKeyOf(pw string) []byte { + var b []byte + for _, r := range pw { + r = unicode.ToLower(r) + if r > 0xFFFF { + r = 0xFFFD + } + b = append(b, byte(r>>8), byte(r)) + } + k := md5.Sum(b) + return k[:] +} + +// SetKeepCIS says whether to keep the keys: only with a CompuServe +// listener, as they would let anyone who read the database log in by CIM. +func (s *Store) SetKeepCIS(on bool) { s.keepCIS.Store(on) } + +// CISKey is the account's Secure Login key, if a current one is kept. +func (s *Store) CISKey(id int64) (k []byte, ok bool, err error) { + var bound, hash string + err = s.db.QueryRow(`SELECT c.k, c.bound, u.password FROM cis_keys c + JOIN users u ON u.id = c.user_id WHERE c.user_id = ?`, id).Scan(&k, &bound, &hash) + if errors.Is(err, sql.ErrNoRows) { + return nil, false, nil + } + if err != nil { + return nil, false, err + } + return k, bound == hash && len(k) == md5.Size, nil +} + +// KeepCISKey keeps the account's key of pw (its password, just checked or +// set), bound to its password hash now, if the store keeps them. +func (s *Store) KeepCISKey(id int64, pw string) error { + if !s.keepCIS.Load() || pw == "" { + return nil + } + var hash string + if err := s.db.QueryRow(`SELECT password FROM users WHERE id = ?`, id).Scan(&hash); err != nil { + if errors.Is(err, sql.ErrNoRows) { + return ErrNotFound + } + return err + } + k := CISKeyOf(pw) + if old, ok, err := s.CISKey(id); err == nil && ok && string(old) == string(k) { + return nil + } + _, err := s.db.Exec(`INSERT INTO cis_keys (user_id, k, bound) VALUES (?, ?, ?) + ON CONFLICT (user_id) DO UPDATE SET k = excluded.k, bound = excluded.bound`, id, k, hash) + return err +} diff --git a/internal/store/cis_test.go b/internal/store/cis_test.go new file mode 100644 index 0000000..22a4354 --- /dev/null +++ b/internal/store/cis_test.go @@ -0,0 +1,42 @@ +package store + +import ( + "encoding/hex" + "path/filepath" + "testing" +) + +func TestCISKey(t *testing.T) { + // the vector recovered from WinCIM 3.0.2's CCTN240C.DLL + if k := hex.EncodeToString(CISKeyOf("Test123")); k != "70ab737140a38266c9d3bfc2aae504ae" { + t.Errorf("K = %s", k) + } + BcryptCost = 4 + s, err := Open(filepath.Join(t.TempDir(), "bbs.db")) + if err != nil { + t.Fatal(err) + } + defer s.Close() + u, _ := s.CreateUser("alice", "password1", "", false) + if _, ok, _ := s.CISKey(u.ID); ok { + t.Fatal("kept without SetKeepCIS") + } + s.SetKeepCIS(true) + if _, err := s.CheckPassword("alice", "password1"); err != nil { + t.Fatal(err) + } + if k, ok, err := s.CISKey(u.ID); err != nil || !ok || string(k) != string(CISKeyOf("PASSWORD1")) { + t.Fatalf("key %x %v %v", k, ok, err) + } + if err := s.SetPassword(u.ID, "password2"); err != nil { + t.Fatal(err) + } + if k, ok, _ := s.CISKey(u.ID); !ok || string(k) != string(CISKeyOf("password2")) { + t.Error("not kept on a change") + } + // changed behind the store's back: stale + s.db.Exec(`UPDATE users SET password = 'x' WHERE id = ?`, u.ID) + if _, ok, _ := s.CISKey(u.ID); ok { + t.Error("a stale key is current") + } +} diff --git a/internal/store/copy.go b/internal/store/copy.go index c5c031d..96e89f5 100644 --- a/internal/store/copy.go +++ b/internal/store/copy.go @@ -13,7 +13,7 @@ import ( // copyOrder is the tables in an order their references allow. var copyOrder = []string{"users", "areas", "messages", "votes", "poll_answers", "poll_votes", "lastread", "scan_off", "mail", "file_areas", "files", "history", "peer_groups", "peer_push", "netmail_out", "api_tokens", "ssh_keys", "script_data", "calls", "qwk_seen", "qwk_msgs", "chat_rooms", "topic_read", "fido_subs", - "chan_boards", "chan_posts", "chan_bans", "chan_reports", "oscar_keys", "feedbag"} + "chan_boards", "chan_posts", "chan_bans", "chan_reports", "oscar_keys", "feedbag", "cis_keys"} var columnPat = regexp.MustCompile(`(?m)^\s*("?\w+"?)\s+(\{\w+\})`) diff --git a/internal/store/schema.go b/internal/store/schema.go index b15176f..83c53be 100644 --- a/internal/store/schema.go +++ b/internal/store/schema.go @@ -227,6 +227,11 @@ CREATE TABLE IF NOT EXISTS ssh_keys ( created {int} NOT NULL, last_used {int} NOT NULL DEFAULT 0 )`, ` +CREATE TABLE IF NOT EXISTS cis_keys ( + user_id {int} NOT NULL PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE, + k {blob} NOT NULL, + bound {str} NOT NULL +)`, ` CREATE TABLE IF NOT EXISTS oscar_keys ( user_id {int} NOT NULL PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE, auth_key {str} NOT NULL, diff --git a/internal/store/store.go b/internal/store/store.go index 9c09937..88b022b 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -117,6 +117,8 @@ type Store struct { dummy []byte // keepOSCAR: passwords set or checked keep their AIM digests (oscar.go) keepOSCAR atomic.Bool + // keepCIS: and their CompuServe Secure Login keys (cis.go) + keepCIS atomic.Bool } // Open opens (and makes, if need be) the database at addr: a file's path @@ -253,6 +255,7 @@ func (s *Store) CreateUser(name, password, location string, sysop bool) (*User, } if password != "" { s.KeepOSCARKeys(id, password) + s.KeepCISKey(id, password) } return s.UserByID(id) } @@ -285,6 +288,7 @@ func (s *Store) CheckPassword(name, pw string) (*User, error) { return nil, ErrNotFound } s.KeepOSCARKeys(u.ID, pw) // best effort: the login stands without them + s.KeepCISKey(u.ID, pw) return u, nil } @@ -297,6 +301,9 @@ func (s *Store) SetPassword(id int64, pw string) error { if err := s.exec1(`UPDATE users SET password = ? WHERE id = ?`, h, id); err != nil { return err } + if err := s.KeepCISKey(id, pw); err != nil { + return err + } return s.KeepOSCARKeys(id, pw) } diff --git a/internal/xfer/cisbtl.go b/internal/xfer/cisbtl.go new file mode 100644 index 0000000..38cca20 --- /dev/null +++ b/internal/xfer/cisbtl.go @@ -0,0 +1,260 @@ +package xfer + +// The B Plus Transport Layer: what CompuServe's HMI (CIM's binary service) +// runs on. Packets are B Plus's, but each side numbers its own (0-9, the +// ENQ answer's DLE '0' standing for the host's 0, so its first is 1), and +// messages travel as 'M' packets (more follows) ended by an 'L' packet. +// As WinCIM 3.0.2 does it, recovered by 24high/CompuServe-Emulator +// (HMI-PROTOKOLL.md, SECURE-LOGIN.md): +// +// H→C ENQ +// C→H DLE '+' '+' DLE '0' +// H→C '+' 04 04 08 00 00 01 (TL, the last, must be set; a short block) +// C→H ACK, then its own '+' +// ... 'M'/'L' packets both ways, each ACKed + +import ( + "errors" + "time" +) + +// TLParams are the '+' packet the host sends a CIM: windows of 4, 1 KB +// blocks, the checksum, the Transport Layer. It must be short: before +// the trade, WinCIM refuses packets of more than about 8 bytes. +var TLParams = []byte{4, 4, 8, CheckSum, 0, 1} + +// ErrTLFailed is an 'F' packet from the other side. +var ErrTLFailed = errors.New("cisb: the transport layer was ended") + +// BTransport is the Transport Layer on a line. +type BTransport struct { + k *BLink + tx byte // the sequence digit of the last packet sent + rx byte // of the last taken (0: none yet) + Their []byte // the other side's '+' packet body + queue [][]byte + partial []byte + max int // the most data a packet carries +} + +// NewBTransport starts the Transport Layer as the host: ENQ, the B Plus +// answer, the trade of '+' packets. +func NewBTransport(p Port, timeout time.Duration) (*BTransport, error) { + k := NewBLink(p) + k.Timeout = timeout + k.quoteAll() // quoting more than asked does no harm; less does + t := &BTransport{k: k, tx: '0', max: 1023} + if err := t.enq(); err != nil { + return nil, err + } + if err := t.send('+', TLParams); err != nil { + return nil, err + } + if t.Their == nil && len(t.queue) == 0 { + // its '+' (unless it came while ours waited for its ACK) + m, typ, err := t.packet() + if err != nil { + return nil, err + } + if err := t.take(typ, m); err != nil { + return nil, err + } + } + return t, nil +} + +// enq sends ENQ until the B Plus answer comes, up to 5 times. +func (t *BTransport) enq() error { + for try := 0; try < 5; try++ { + if err := t.k.l.write([]byte{bENQ}); err != nil { + return err + } + deadline := time.Now().Add(3 * time.Second) + var got []byte + for time.Now().Before(deadline) { + c, err := t.k.l.getc(time.Until(deadline)) + if errors.Is(err, ErrTimeout) { + break + } + if err != nil { + return err + } + got = append(got, c) + if n := len(got); n >= 5 && string(got[n-5:]) == "\x10++\x100" { + return nil + } + } + } + return ErrTimeout +} + +// send sends one packet and waits for its ACK, sending again on a NAK or +// silence; a packet that comes meanwhile is taken (and ACKed). +func (t *BTransport) send(typ byte, body []byte) error { + s := next(t.tx) + b := t.k.encode(BPacket{Seq: s, Type: typ, Body: body}, CheckSum) + errs := 0 + if err := t.k.l.write(b); err != nil { + return err + } + for { + ev, err := t.k.read(CheckSum) + if errors.Is(err, ErrTimeout) { + ev, err = bEvent{kind: evNAK}, nil + } + if err != nil { + return err + } + switch ev.kind { + case evACK: + if ev.seq == s { + t.tx = s + return nil + } + continue // an old one + case evPacket: + if err := t.received(ev.pkt); err != nil { + return err + } + continue + case evENQ: + // the other side lost its place: say where we are + t.k.ack(t.rx) + continue + } + // a NAK, a bad packet or silence: again + if errs++; errs > t.k.maxErrors() { + return ErrRetries + } + if err := t.k.l.write(b); err != nil { + return err + } + } +} + +// received takes a packet that came: a new one is ACKed and kept, the +// last one again is ACKed again. +func (t *BTransport) received(p BPacket) error { + if t.rx != 0 && p.Seq == t.rx { + return t.k.ack(p.Seq) // our ACK was lost + } + t.rx = p.Seq + if err := t.k.ack(p.Seq); err != nil { + return err + } + return t.take(p.Type, p.Body) +} + +// take keeps a packet's data: 'M' and 'L' make up messages. +func (t *BTransport) take(typ byte, body []byte) error { + switch typ { + case 'M', 'N': + t.partial = append(t.partial, body...) + case 'L': + m := append(t.partial, body...) + t.partial = nil + t.queue = append(t.queue, m) + case 'F': + return ErrTLFailed + case '+': + t.Their = body + } + return nil +} + +// packet reads the next new packet (ACKing it). +func (t *BTransport) packet() ([]byte, byte, error) { + for { + ev, err := t.k.read(CheckSum) + if err != nil { + return nil, 0, err + } + switch ev.kind { + case evPacket: + if t.rx != 0 && ev.seq == t.rx { + t.k.ack(ev.seq) + continue + } + t.rx = ev.seq + if err := t.k.ack(ev.seq); err != nil { + return nil, 0, err + } + return ev.pkt.Body, ev.pkt.Type, nil + case evBad: + t.k.l.write([]byte{bNAK}) + case evENQ: + t.k.ack(t.rx) + } + } +} + +// Recv is the next message, waiting at most d (0: the link's timeout); +// ErrTimeout when none came. +func (t *BTransport) Recv(d time.Duration) ([]byte, error) { + old := t.k.Timeout + if d > 0 { + t.k.Timeout = d + defer func() { t.k.Timeout = old }() + } + for len(t.queue) == 0 { + body, typ, err := t.packet() + if err != nil { + return nil, err + } + if err := t.take(typ, body); err != nil { + return nil, err + } + } + m := t.queue[0] + t.queue = t.queue[1:] + return m, nil +} + +// Send sends a message, as 'M' packets and a last 'L'. +func (t *BTransport) Send(m []byte) error { + for len(m) > t.max { + if err := t.send('M', m[:t.max]); err != nil { + return err + } + m = m[t.max:] + } + return t.send('L', m) +} + +// Fail ends the Transport Layer with an 'F' packet. +func (t *BTransport) Fail(text string) error { + return t.send('F', append([]byte{'E'}, text...)) +} + +// AnswerTL is the terminal's side of the start, for tests: the ENQ +// answer, then the trade of '+' packets. +func AnswerTL(p Port, params []byte, timeout time.Duration) (*BTransport, error) { + k := NewBLink(p) + k.Timeout = timeout + k.quoteAll() + t := &BTransport{k: k, tx: '0', max: 1023} + for { + c, err := k.l.getc(timeout) + if err != nil { + return nil, err + } + if c == bENQ { + break + } + } + if err := k.l.write([]byte{bDLE, '+', '+', bDLE, '0'}); err != nil { + return nil, err + } + body, typ, err := t.packet() + if err != nil { + return nil, err + } + if typ != '+' { + return nil, errors.New("cisb: no '+' packet from the host") + } + t.Their = body + if err := t.send('+', params); err != nil { + return nil, err + } + return t, nil +} diff --git a/internal/xfer/cisbtl_test.go b/internal/xfer/cisbtl_test.go new file mode 100644 index 0000000..3d1f85c --- /dev/null +++ b/internal/xfer/cisbtl_test.go @@ -0,0 +1,102 @@ +package xfer + +import ( + "bytes" + "crypto/rand" + "testing" + "time" +) + +// TestBTransport: the host's start as WinCIM sees it, then messages both +// ways, one of them several packets long, over a clean and a noisy line. +func TestBTransport(t *testing.T) { + // a 1 KB packet quoted is up to 2 KB on the wire, so the noise is one + // byte in 3001: one packet in two or so is hit + for _, noise := range []int{0, 3001} { + a, b := tcpPair(t) + var hp, tp Port = a, b + if noise > 0 { + hp, tp = &bNoisy{Conn: a, n: noise}, &bNoisy{Conn: b, n: noise + 2} + } + big := make([]byte, 5000) + rand.Read(big) + done := make(chan error, 1) + go func() { + term, err := AnswerTL(tp, []byte{4, 4, 0, 2, 3, 1}, 300*time.Millisecond) + if err != nil { + done <- err + return + } + if err := term.Send([]byte{3, 0x0F}); err != nil { + done <- err + return + } + m, err := term.Recv(5 * time.Second) + if err == nil && !bytes.Equal(m, big) { + t.Errorf("noise %d: the big message came as %d bytes", noise, len(m)) + } + if err == nil { + err = term.Send([]byte{1, 0x07}) + } + done <- err + }() + host, err := NewBTransport(hp, 300*time.Millisecond) + if err != nil { + t.Fatalf("noise %d: start: %v", noise, err) + } + if !bytes.Equal(host.Their, []byte{4, 4, 0, 2, 3, 1}) { + t.Errorf("their '+': % x", host.Their) + } + m, err := host.Recv(5 * time.Second) + if err != nil || !bytes.Equal(m, []byte{3, 0x0F}) { + t.Fatalf("noise %d: got % x, %v", noise, m, err) + } + if err := host.Send(big); err != nil { + t.Fatal(err) + } + m, err = host.Recv(5 * time.Second) + if err != nil || !bytes.Equal(m, []byte{1, 0x07}) { + t.Fatalf("noise %d: got % x, %v", noise, m, err) + } + if err := <-done; err != nil { + t.Fatalf("noise %d: terminal: %v", noise, err) + } + } +} + +// TestBTransportWire: the host's first bytes are WinCIM's trace: ENQ, then +// DLE B '1' '+' 04 04 08 00 00 01 ETX and the checksum. +func TestBTransportWire(t *testing.T) { + a, b := tcpPair(t) + go NewBTransport(a, time.Second) + buf := make([]byte, 1) + b.SetReadDeadline(time.Now().Add(2 * time.Second)) + if _, err := b.Read(buf); err != nil || buf[0] != bENQ { + t.Fatalf("% x %v", buf, err) + } + b.Write([]byte{bDLE, '+', '+', bDLE, '0'}) + raw := []byte{'1', '+', 4, 4, 8, 0, 0, 1, bETX} + var want []byte + want = append(want, bDLE, 'B', '1', '+', 4, 4, 8, 0, 0, 1) + // every control byte quoted: 04 as DLE 'D', 08 as DLE 'H', 00 as DLE '@', 01 as DLE 'A' + want = []byte{bDLE, 'B', '1', '+', bDLE, 0x44, bDLE, 0x44, bDLE, 0x48, bDLE, 0x40, bDLE, 0x40, bDLE, 0x41, bETX} + sum := BChecksum(raw) + if sum < 0x20 { + want = append(want, bDLE, sum+0x40) + } else if sum >= 0x80 && sum < 0xA0 { + want = append(want, bDLE, sum&0x1F+0x60) + } else { + want = append(want, sum) + } + got := make([]byte, 0, len(want)) + for len(got) < len(want) { + n, err := b.Read(buf) + if err != nil { + t.Fatalf("after % x: %v", got, err) + } + got = append(got, buf[:n]...) + } + if !bytes.Equal(got, want) { + t.Errorf("got % x\nwant % x", got, want) + } +}