From 2c9dedb4b2e339e6b2ec53fc3317bc6428a34756 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 05:12:52 +0000 Subject: [PATCH] MSN Classic: the 1996 client's NTLM sign-in MSN 1.3 (Windows 95 OSR2) signs in with NTLM on LOGSRV: a NEGOTIATE answered with a CHALLENGE, then an AUTHENTICATE whose NTLMv1 response (the LM one: the client leaves the NT one empty) is checked against the account's kept hashes, throttled and logged as a password is. The store keeps each account's LM and NT hashes (ntlm_keys) as it keeps CompuServe's key: made whenever the password is seen in the clear, bound to the password hash, and only while MSN Classic is served. The context an accepted sign-in leaves seals the account methods as the client expects: the Password dialog's change (0x12), the billing pages' record (0x13) and the payment commit (0x14), RC4 under the 40-bit seal key with a CRC-32 and sequence-numbered token. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01B82eRSzB4EzF1cUBt1ccvB --- TODO.md | 10 +- docs/wiki/MSN-Classic.md | 18 ++- internal/bbs/bbs.go | 1 + internal/marvel/conn.go | 19 ++- internal/marvel/logsrv.go | 154 ++++++++++++++++++++-- internal/marvel/marvel.go | 1 + internal/marvel/ntlm.go | 246 +++++++++++++++++++++++++++++++++++ internal/marvel/ntlm_test.go | 151 +++++++++++++++++++++ internal/server/server.go | 4 + internal/store/copy.go | 2 +- internal/store/msn_test.go | 37 ++++++ internal/store/ntlm.go | 99 ++++++++++++++ internal/store/schema.go | 6 + internal/store/store.go | 7 + 14 files changed, 730 insertions(+), 25 deletions(-) create mode 100644 internal/marvel/ntlm.go create mode 100644 internal/marvel/ntlm_test.go create mode 100644 internal/store/ntlm.go diff --git a/TODO.md b/TODO.md index a35990f..5cf09d8 100644 --- a/TODO.md +++ b/TODO.md @@ -5,19 +5,17 @@ Ideas not yet started, with what is known of them. ## An MSN Classic front end *Status: started; the link, the RPC, sign-in, the directory, bulletin -boards, e-mail and its address book, chat, Find and file downloads -(`internal/marvel`, `[marvel]`, `frontend = marvel`) are done. Not yet -tried with a real client.* +boards, e-mail and its address book, chat, Find, file downloads and +the 1996 client's NTLM sign-in (`internal/marvel`, `[marvel]`, +`frontend = marvel`) are done. Not yet tried with a real client.* -For the MSN client of Windows 95 (MSN 1.0 to 1.2), over TCP (port 569) and +For the MSN client of Windows 95 (MSN 1.0 to 1.3), over TCP (port 569) and by modem, from the marvel-msn project's protocol notes. Next: - **Uploads**: a file library as an MSN BBS whose messages carry the files as attachments (MOSAF objects in a rich-text body, MOS2 packed), which also lets a file be saved where the caller says rather than opened from the temporary folder. -- **MSN 1.3 (OSR2)**: its NTLM sign-in needs the password's NT hash, kept - as CompuServe's key is. - **MSN Today**: the Media Viewer title (MEDVIEW), a page of news. ## An AOL front end diff --git a/docs/wiki/MSN-Classic.md b/docs/wiki/MSN-Classic.md index 98efa08..aea819d 100644 --- a/docs/wiki/MSN-Classic.md +++ b/docs/wiki/MSN-Classic.md @@ -54,6 +54,20 @@ Point the client's phone number at the line that reaches that listener. node and shows in Who's On as `MSN`. The Password dialog changes the BBS password. The billing pages show the account's name and location and keep nothing. +- **The 1996 client** (Windows 95 OSR2, MSN 1.3) signs in with NTLM: it + never sends the password, only an answer to a challenge worked out from + the password's LAN Manager hash. The BBS keeps that hash and the NT + hash for each account, made whenever the password is typed in the clear + (signing in any other way, or setting a password), and bound to the + password, so a password changed somewhere they aren't made leaves them + unused until it is typed again. An account whose hashes aren't kept yet + gets "Password not valid" from this client: sign in once by telnet, the + web or the 1995 client first. The hashes are kept only while MSN Classic + is served (a `[marvel]` section or a `frontend = marvel` listener), and + they are password equivalents, the LM hash a weak one, so the database + needs guarding as a password file does. After signing in, the Password + dialog and the billing pages travel sealed (RC4) under the sign-in's + key, as the client expects. - **The directory**: only the areas the caller may read are listed. Go words are the areas' and groups' names (in any case), and `today`. - **Bulletin boards**: up to the newest few hundred messages of an area @@ -104,9 +118,7 @@ Point the client's phone number at the line that reaches that listener. here has a place, so a search with Place filled in finds nothing. At most 200 results come back. -Not served yet: the sign-up wizard and MSN Today's Media Viewer title. The 1996 client -(Windows 95 OSR2, MSN 1.3) signs in with NTLM, which needs a password hash -the BBS doesn't keep, so it can't sign in. +Not served yet: the sign-up wizard and MSN Today's Media Viewer title. ## Where the protocol comes from diff --git a/internal/bbs/bbs.go b/internal/bbs/bbs.go index 73a5059..fb69972 100644 --- a/internal/bbs/bbs.go +++ b/internal/bbs/bbs.go @@ -630,6 +630,7 @@ func (b *BBS) menuLogin(who, name, pw string) (*store.User, error) { b.Store.KeepOSCARKeys(u.ID, pw) // for AIM's digest logins, if kept b.Store.KeepCISKey(u.ID, pw) // and CompuServe's b.Store.KeepMSNKey(u.ID, pw) // and MSN's + b.Store.KeepNTLMKey(u.ID, pw) // and MSN Classic's return u, nil } diff --git a/internal/marvel/conn.go b/internal/marvel/conn.go index 605362d..2998265 100644 --- a/internal/marvel/conn.go +++ b/internal/marvel/conn.go @@ -253,6 +253,17 @@ func (c *conn) data(pipe uint16, b []byte) bool { // signOn signs the connection on as name with pw: 0 or the code LOGSRV's // reply says why not. func (c *conn) signOn(name, pw string) uint32 { + return c.signOnBy(name, func(node *bbs.Node, name string) (*store.User, error) { + if node != nil { + return node.Login(name, pw) + } + return c.s.B.Authenticate("marvel", c.source, name, pw) + }) +} + +// signOnBy signs on as name, by login (given the call's node, if a modem +// call: nil over TCP, and the member's name as the BBS has it). +func (c *conn) signOnBy(name string, login func(*bbs.Node, string) (*store.User, error)) uint32 { b := c.s.B if u, err := b.Store.UserByScreenName(name); err == nil { name = u.Name // a member ID with the spaces left out @@ -260,13 +271,7 @@ func (c *conn) signOn(name, pw string) uint32 { c.mu.Lock() node := c.node c.mu.Unlock() - var u *store.User - var err error - if node != nil { - u, err = node.Login(name, pw) - } else { - u, err = b.Authenticate("marvel", c.source, name, pw) - } + u, err := login(node, name) if err != nil { c.logf("sign-on as %q: %v", name, err) switch { diff --git a/internal/marvel/logsrv.go b/internal/marvel/logsrv.go index d2e4ff7..c8edeb6 100644 --- a/internal/marvel/logsrv.go +++ b/internal/marvel/logsrv.go @@ -1,12 +1,24 @@ package marvel import ( + "bytes" + "encoding/binary" "strings" + + "github.com/D-Modem/bbs/internal/bbs" + "github.com/D-Modem/bbs/internal/store" ) // LOGSRV signs the client on. Its one interface, {00028BC2-...}, is // called by the Sign In dialog, the Password dialog and the billing pages. -type logsrv struct{ c *conn } +type logsrv struct { + c *conn + + // the 1996 client's NTLM sign-on (ntlm.go), and the sealing it leaves + challenge []byte + flags uint32 + seal *sealer +} const logsrvIface = 0x06 @@ -22,6 +34,11 @@ const ( logPostSignup = 0x0D logPhoneBook = 0x0E logNTLMNegotiate = 0x0F + logNTLMAuth = 0x10 + logNTLMAccount = 0x11 // what an accepted NTLM sign-on reads next + logSealedPassword = 0x12 + logSealedBilling = 0x13 + logSealedPayment = 0x14 ) // The sign-on result: the first dword of the login reply. The client @@ -71,11 +88,46 @@ func (l *logsrv) call(h hostBlock) ([]byte, bool) { case logPhoneBook: return reply{}.dword(0), true case logNTLMNegotiate: - // the 1996 (OSR2) client's NTLM sign-on: a challenge would need - // the password's NT hash, which the BBS doesn't keep, so there is - // none, and the client says the sign-on failed - l.c.logf("an NTLM sign-on (a 1996 client), which this server can't answer") - return reply{}.bytes_(nil), true + t := ntlmToken(ps, ntlmTypeNegotiate) + if t == nil || len(t) < 16 { + return reply{}.bytes_(nil), true // no token: the client says the sign-on failed + } + l.flags = binary.LittleEndian.Uint32(t[12:]) + l.challenge = newChallenge() + return reply{}.bytes_(wrapToken(ntlmTypeChallenge, challengeToken(l.flags, l.challenge))), true + case logNTLMAuth: + result, ok := l.ntlmSignOn(ps) + word := uint16(ntlmRefused) + if ok { + word = ntlmAccepted + } + return reply{}.word(word).dword(result).endStatic(), true + case logNTLMAccount: + // five dwords, 16 bytes and five more, all nothing: a value here + // would ask for a software update + r := reply{} + for range 5 { + r = r.dword(0) + } + r = r.bytes_(make([]byte, 16)) + for range 5 { + r = r.dword(0) + } + return r.endStatic(), true + case logSealedPassword: + return l.sealedPassword(ps), true + case logSealedBilling: + if l.seal == nil { + return reply{}.bytes_(l.account()).bytes_(make([]byte, sealTokenLen)), true + } + data, token := l.seal.seal(l.account()) + return reply{}.bytes_(data).bytes_(token), true + case logSealedPayment: + // read (to keep the stream in step) and not kept: the BBS has no billing + if vs := vars(ps); l.seal != nil && len(vs) == 2 { + l.seal.unseal(vs[0], vs[1]) + } + return reply{}.bytes_(make([]byte, 4)), true } l.c.logf("LOGSRV: no method %#x", h.Method) return nil, false @@ -99,6 +151,85 @@ func (l *logsrv) login(ps []param) []byte { return r.endStatic().bytes_(make([]byte, 16)) } +// vars are a call's 0x04 values. +func vars(ps []param) [][]byte { + var out [][]byte + for _, p := range ps { + if p.Tag == 0x04 { + out = append(out, p.Data) + } + } + return out +} + +// ntlmSignOn checks an AUTHENTICATE against the member's kept hashes, and +// signs on. +func (l *logsrv) ntlmSignOn(ps []param) (uint32, bool) { + t := ntlmToken(ps, ntlmTypeAuthenticate) + if t == nil || l.challenge == nil { + return loginNoMember, false + } + challenge := l.challenge + l.challenge = nil // one answer to each + a, err := parseAuthenticate(t, l.flags) + if err != nil { + l.c.logf("NTLM: %v", err) + return loginNoMember, false + } + b := l.c.s.B + var lm, nt []byte + check := func() (*store.User, error) { + u, err := b.Store.UserByName(a.user) + if err != nil { + if u, err = b.Store.UserByScreenName(a.user); err != nil { + return nil, store.ErrNotFound + } + } + var ok bool + if lm, nt, ok, err = b.Store.NTLMKey(u.ID); err != nil || !ok { + // kept once the password is seen: a sign-in any other way + l.c.logf("NTLM: no password hashes kept for %s yet: they are kept when the password is next typed in the clear", u.Name) + return nil, store.ErrNotFound + } + if !a.verify(lm, nt, challenge) { + return nil, store.ErrNotFound + } + return u, nil + } + result := l.c.signOnBy(a.user, func(node *bbs.Node, name string) (*store.User, error) { + if node != nil { + return node.LoginWith(name, "NTLM", check) + } + return b.AuthenticateBy("marvel", l.c.source, name, check) + }) + if result != loginOK { + return result, false + } + if l.seal, err = newSealer(a.flags, a.sessionKey(lm, nt, challenge)); err != nil { + l.c.logf("NTLM: %v", err) + } + return loginOK, true +} + +// sealedPassword is the 1996 client's Password dialog: the old password +// and the new, each NUL-ended, sealed. +func (l *logsrv) sealedPassword(ps []param) []byte { + vs := vars(ps) + if l.seal == nil || len(vs) != 2 { + return reply{}.dword(1) + } + data, ok := l.seal.unseal(vs[0], vs[1]) + if !ok { + l.c.logf("password: a seal that doesn't check out") + return reply{}.dword(1) + } + pws := bytes.Split(data, []byte{0}) + if len(pws) != 3 || len(pws[2]) != 0 { + return reply{}.dword(1) + } + return l.changePassword(unansi(pws[0]), unansi(pws[1])) +} + // password is the Password dialog's change: the old one and the new, in // two 17-byte fields. Any status but 0 is "not valid". func (l *logsrv) password(ps []param) []byte { @@ -108,13 +239,20 @@ func (l *logsrv) password(ps []param) []byte { pws = append(pws, asciiz(p.Data)) } } + if len(pws) != 2 { + return reply{}.dword(1) + } + return l.changePassword(pws[0], pws[1]) +} + +func (l *logsrv) changePassword(old, pw string) []byte { l.c.mu.Lock() n := l.c.node l.c.mu.Unlock() - if len(pws) != 2 || n == nil || l.c.signedOn() == nil { + if n == nil || l.c.signedOn() == nil { return reply{}.dword(1) } - if err := n.ChangePassword(pws[0], pws[1]); err != nil { + if err := n.ChangePassword(old, pw); err != nil { l.c.logf("password: %v", err) return reply{}.dword(1) } diff --git a/internal/marvel/marvel.go b/internal/marvel/marvel.go index 981d548..917c623 100644 --- a/internal/marvel/marvel.go +++ b/internal/marvel/marvel.go @@ -67,6 +67,7 @@ func New(b *bbs.BBS, s Settings) (*Server, error) { if s.MaxClients == 0 { s.MaxClients = 64 } + b.Store.SetKeepNTLM(true) // the 1996 client's NTLM sign-in checks against them return &Server{B: b, S: s, conns: map[*conn]bool{}, roomIDs: map[string]uint32{}, roomNames: map[uint32]string{}}, nil } diff --git a/internal/marvel/ntlm.go b/internal/marvel/ntlm.go new file mode 100644 index 0000000..6ba1da0 --- /dev/null +++ b/internal/marvel/ntlm.go @@ -0,0 +1,246 @@ +package marvel + +import ( + "bytes" + "crypto/des" + "crypto/hmac" + "crypto/md5" + "crypto/rand" + "crypto/rc4" + "crypto/subtle" + "encoding/binary" + "errors" + ieee "hash/crc32" + "unicode/utf16" + + "github.com/D-Modem/bbs/internal/store" + "golang.org/x/crypto/md4" +) + +// The 1996 client (Windows 95 OSR2, MSN 1.3) signs in with NTLM, on two +// LOGSRV methods: a NEGOTIATE answered with a CHALLENGE, then an +// AUTHENTICATE answered with the result. The client answers the +// challenge with NTLMv1: DES keyed with the password's LM hash (the NT +// response it leaves empty), which the store keeps for it. The context +// the sign-in leaves then seals the account methods' data: the password +// change and the billing pages. +// +// Each token rides a 0x04 value behind a header, [type u16][length u16], +// in a 256-byte slot. + +const ( + ntlmTypeNegotiate = 1 + ntlmTypeChallenge = 2 + ntlmTypeAuthenticate = 3 + ntlmAccepted = 4 // the sign-in reply's word: the context stands + ntlmRefused = 0 + ntlmSlot = 256 + + ntlmUnicode = 0x00000001 + ntlmLMKey = 0x00000080 + ntlmNonNTKey = 0x00400000 + ntlmESS = 0x00080000 // extended session security + ntlm56 = 0x80000000 + sealTokenLen = 16 + ntlmChallengeN = 8 +) + +var ntlmSig = []byte("NTLMSSP\x00") + +// ntlmToken is the token in a method's 0x04 value. +func ntlmToken(ps []param, want uint32) []byte { + for _, p := range ps { + if p.Tag != 0x04 || len(p.Data) < 4 { + continue + } + n := int(binary.LittleEndian.Uint16(p.Data[2:])) + t := p.Data[4:] + if n < len(t) { + t = t[:n] + } + if len(t) >= 12 && bytes.Equal(t[:8], ntlmSig) && binary.LittleEndian.Uint32(t[8:]) == want { + return t + } + } + return nil +} + +func wrapToken(typ uint16, t []byte) []byte { + b := binary.LittleEndian.AppendUint16(nil, typ) + b = binary.LittleEndian.AppendUint16(b, uint16(len(t))) + b = append(b, t...) + if len(b) < 4+ntlmSlot { + b = append(b, make([]byte, 4+ntlmSlot-len(b))...) + } + return b +} + +// challengeToken is a CHALLENGE that gives the client back the flags it +// asked for: no target name, no target information. +func challengeToken(flags uint32, challenge []byte) []byte { + b := append([]byte(nil), ntlmSig...) + b = binary.LittleEndian.AppendUint32(b, ntlmTypeChallenge) + b = append(b, 0, 0, 0, 0, 48, 0, 0, 0) // target name: none + b = binary.LittleEndian.AppendUint32(b, flags) + b = append(b, challenge...) + b = append(b, make([]byte, 8)...) // reserved + return append(b, 0, 0, 0, 0, 48, 0, 0, 0) // target information: none +} + +type ntlmAuth struct { + flags uint32 + user, domain string + lmResp, ntResp []byte +} + +// parseAuthenticate reads an AUTHENTICATE. The 1996 client's header +// stops after the workstation's field (52 bytes, with no flags of its +// own), so the flags come from the token only when its data starts past +// the long header. +func parseAuthenticate(t []byte, negotiated uint32) (*ntlmAuth, error) { + if len(t) < 52 { + return nil, errors.New("an AUTHENTICATE cut short") + } + var fields [5][]byte + start := len(t) + for i := range fields { + at := 12 + 8*i + n, off := int(binary.LittleEndian.Uint16(t[at:])), int(binary.LittleEndian.Uint32(t[at+4:])) + if n == 0 { + continue + } + if off < 0 || off+n > len(t) { + return nil, errors.New("an AUTHENTICATE's field outside it") + } + fields[i] = t[off : off+n] + start = min(start, off) + } + a := &ntlmAuth{flags: negotiated, lmResp: fields[0], ntResp: fields[1]} + if start >= 64 { + a.flags = binary.LittleEndian.Uint32(t[60:]) + } + text := func(b []byte) string { + if a.flags&ntlmUnicode != 0 { + u := make([]uint16, len(b)/2) + for i := range u { + u[i] = binary.LittleEndian.Uint16(b[2*i:]) + } + return string(utf16.Decode(u)) + } + return unansi(b) + } + a.domain, a.user = text(fields[2]), text(fields[3]) + return a, nil +} + +// desl is NTLMv1's response: the challenge under each third of the hash +// (padded to 21 bytes). +func desl(k, c []byte) []byte { + key := append(append([]byte(nil), k...), make([]byte, 21-len(k))...) + out := make([]byte, 24) + for i := range 3 { + b, _ := des.NewCipher(store.DESKey(key[i*7 : i*7+7])) + b.Encrypt(out[i*8:], c) + } + return out +} + +func desEncrypt(k7, c []byte) []byte { + b, _ := des.NewCipher(store.DESKey(k7)) + out := make([]byte, 8) + b.Encrypt(out, c) + return out +} + +// verify checks a response against the hashes: the NT response if there +// is one, else the LM. +func (a *ntlmAuth) verify(lm, nt, challenge []byte) bool { + c := challenge + if a.flags&ntlmESS != 0 && len(a.lmResp) >= 8 { + h := md5.Sum(append(append([]byte(nil), challenge...), a.lmResp[:8]...)) + c = h[:8] + } + switch { + case len(a.ntResp) == 24: + return subtle.ConstantTimeCompare(a.ntResp, desl(nt, c)) == 1 + case len(a.lmResp) == 24 && a.flags&ntlmESS == 0: + return subtle.ConstantTimeCompare(a.lmResp, desl(lm, c)) == 1 + } + return false +} + +// sessionKey is the key an accepted exchange leaves (no key exchange: the +// short AUTHENTICATE has no room for one). +func (a *ntlmAuth) sessionKey(lm, nt, challenge []byte) []byte { + h := md4.New() + h.Write(nt) + base := h.Sum(nil) + switch { + case a.flags&ntlmESS != 0: + m := hmac.New(md5.New, base) + m.Write(challenge) + m.Write(a.lmResp[:8]) + return m.Sum(nil) + case a.flags&ntlmLMKey != 0 && len(a.lmResp) >= 8: + k := desEncrypt(lm[:7], a.lmResp[:8]) + return append(k, desEncrypt(append([]byte{lm[7]}, 0xBD, 0xBD, 0xBD, 0xBD, 0xBD, 0xBD), a.lmResp[:8])...) + case a.flags&ntlmNonNTKey != 0: + return append(append([]byte(nil), lm[:8]...), make([]byte, 8)...) + } + return base +} + +// sealer is the sealing an accepted sign-in leaves its pipe: an RC4 +// stream each way from one key, each message's data and then its token +// [1][RandomPad][CRC-32 of the data][sequence], the last 12 bytes +// encrypted from the same stream. +type sealer struct { + out, in *rc4.Cipher + outSeq, inSeq uint32 +} + +func newSealer(flags uint32, key []byte) (*sealer, error) { + if flags&ntlmESS != 0 { + return nil, errors.New("extended session security's sealing isn't served") + } + var k []byte + if flags&ntlm56 != 0 { + k = append(append([]byte(nil), key[:7]...), 0xA0) + } else { + k = append(append([]byte(nil), key[:5]...), 0xE5, 0x38, 0xB0) + } + out, _ := rc4.NewCipher(k) + in, _ := rc4.NewCipher(k) + return &sealer{out: out, in: in}, nil +} + +func (s *sealer) seal(data []byte) (sealed, token []byte) { + sealed = make([]byte, len(data)) + s.out.XORKeyStream(sealed, data) + tr := binary.LittleEndian.AppendUint32(make([]byte, 4), ieee.ChecksumIEEE(data)) + tr = binary.LittleEndian.AppendUint32(tr, s.outSeq) + s.outSeq++ + token = binary.LittleEndian.AppendUint32(nil, 1) + enc := make([]byte, 12) + s.out.XORKeyStream(enc, tr) + return sealed, append(token, enc...) +} + +func (s *sealer) unseal(sealed, token []byte) ([]byte, bool) { + if len(token) != sealTokenLen || binary.LittleEndian.Uint32(token) != 1 { + return nil, false + } + data := make([]byte, len(sealed)) + s.in.XORKeyStream(data, sealed) + tr := make([]byte, 12) + s.in.XORKeyStream(tr, token[4:]) + seq := s.inSeq + s.inSeq++ + return data, binary.LittleEndian.Uint32(tr[8:]) == seq && binary.LittleEndian.Uint32(tr[4:]) == ieee.ChecksumIEEE(data) +} + +func newChallenge() []byte { + c := make([]byte, ntlmChallengeN) + rand.Read(c) + return c +} diff --git a/internal/marvel/ntlm_test.go b/internal/marvel/ntlm_test.go new file mode 100644 index 0000000..51c676a --- /dev/null +++ b/internal/marvel/ntlm_test.go @@ -0,0 +1,151 @@ +package marvel + +import ( + "bytes" + "encoding/binary" + "encoding/hex" + "testing" + + "github.com/D-Modem/bbs/internal/store" +) + +// MS-NLMP 4.2.2: NTLMv1 with the password "Password" and the challenge +// 0123456789abcdef. +func TestNTLMv1Vectors(t *testing.T) { + c, _ := hex.DecodeString("0123456789abcdef") + if got := hex.EncodeToString(desl(store.LMHash("Password"), c)); got != "98def7b87f88aa5dafe2df779688a172def11c7d5ccdef13" { + t.Errorf("LM response: %s", got) + } + if got := hex.EncodeToString(desl(store.NTHash("Password"), c)); got != "67c43011f30298a2ad35ece64f16331c44bdbed927841f94" { + t.Errorf("NT response: %s", got) + } + a := &ntlmAuth{} + if got := hex.EncodeToString(a.sessionKey(store.LMHash("Password"), store.NTHash("Password"), c)); got != "d87262b0cde4b1cb7499becccdf10784" { + t.Errorf("session base key: %s", got) + } +} + +func TestSealer(t *testing.T) { + key := bytes.Repeat([]byte{0x55}, 16) + srv, _ := newSealer(0x82a2, key) + cli, _ := newSealer(0x82a2, key) + for i, m := range []string{"old\x00new\x00", "again"} { + data, token := cli.seal([]byte(m)) + if bytes.Equal(data, []byte(m)) || len(token) != sealTokenLen { + t.Fatalf("%d: not sealed", i) + } + if got, ok := srv.unseal(data, token); !ok || string(got) != m { + t.Fatalf("%d: %q %v", i, got, ok) + } + } + // out of order: the sequence number doesn't match + cli.seal([]byte("lost")) + data, token := cli.seal([]byte("next")) + if _, ok := srv.unseal(data, token); ok { + t.Fatal("a skipped message not noticed") + } +} + +// the 1996 client's tokens, as it builds them +const osr2Flags = 0x000082a2 + +func negotiateToken() []byte { + b := append([]byte(nil), ntlmSig...) + b = binary.LittleEndian.AppendUint32(b, ntlmTypeNegotiate) + b = binary.LittleEndian.AppendUint32(b, osr2Flags) + return append(b, make([]byte, 16)...) +} + +// authenticateToken has the short header: five fields and no flags. +func authenticateToken(user string, lmResp []byte) []byte { + payload := [][]byte{lmResp, nil, nil, []byte(user), []byte("WIN95")} + b := append([]byte(nil), ntlmSig...) + b = binary.LittleEndian.AppendUint32(b, ntlmTypeAuthenticate) + off := 52 + for _, p := range payload { + b = binary.LittleEndian.AppendUint16(b, uint16(len(p))) + b = binary.LittleEndian.AppendUint16(b, uint16(len(p))) + b = binary.LittleEndian.AppendUint32(b, uint32(off)) + off += len(p) + } + for _, p := range payload { + b = append(b, p...) + } + return b +} + +// ntlmLogin signs on by NTLM, and gives the reply's word and result, and +// the client's sealing. +func (c *client) ntlmLogin(t *testing.T, user, pw string) (uint32, uint32, *sealer) { + t.Helper() + r := c.call(1, logsrvIface, logNTLMNegotiate, vparam(wrapToken(ntlmTypeNegotiate, negotiateToken())), []byte{0x84}) + if len(r) < 3+4+48 || r[0] != tagVar { + t.Fatalf("challenge: %x", r) + } + ch := r[3+4:] + if !bytes.Equal(ch[:8], ntlmSig) || binary.LittleEndian.Uint32(ch[8:]) != ntlmTypeChallenge || + binary.LittleEndian.Uint32(ch[20:]) != osr2Flags { + t.Fatalf("challenge token: %x", ch[:48]) + } + challenge := ch[24:32] + lmResp := desl(store.LMHash(pw), challenge) + r = c.call(1, logsrvIface, logNTLMAuth, vparam(wrapToken(ntlmTypeAuthenticate, authenticateToken(user, lmResp))), []byte{0x82, 0x83}) + if len(r) != 3+5+1 || r[0] != tagWord || r[3] != tagDword || r[8] != tagEndStatic { + t.Fatalf("sign-on reply: %x", r) + } + a := &ntlmAuth{flags: osr2Flags, lmResp: lmResp} + s, _ := newSealer(osr2Flags, a.sessionKey(store.LMHash(pw), store.NTHash(pw), challenge)) + return uint32(binary.LittleEndian.Uint16(r[1:])), binary.LittleEndian.Uint32(r[4:]), s +} + +func TestNTLMSignOn(t *testing.T) { + srv, st := newServer(t) + // bob's password was set before the hashes were kept: none yet + st.SetKeepNTLM(false) + if _, err := st.CreateUser("bob", "password2", "", false); err != nil { + t.Fatal(err) + } + st.SetKeepNTLM(true) + alice, _ := st.UserByName("alice") + st.SetPassword(alice.ID, "password1") // seen in the clear: kept + + c := dial(t, srv) + c.open(1, "LOGSRV") + if w, r, _ := c.ntlmLogin(t, "alice", "wrong"); w != ntlmRefused || r != loginBadPassword { + t.Fatalf("a wrong password: %d %#x", w, r) + } + if w, r, _ := c.ntlmLogin(t, "nobody", "password1"); w != ntlmRefused || r != loginNoMember { + t.Fatalf("no such member: %d %#x", w, r) + } + if w, r, _ := c.ntlmLogin(t, "bob", "password2"); w != ntlmRefused || r != loginBadPassword { + t.Fatalf("no hashes: %d %#x", w, r) + } + w, r, cli := c.ntlmLogin(t, "ALICE", "password1") // the LM hash is of capitals + if w != ntlmAccepted || r != loginOK || c.call(1, logsrvIface, logNTLMAccount)[0] != tagDword { + t.Fatalf("sign-on: %d %#x", w, r) + } + + // the billing pages, sealed + rr := c.call(1, logsrvIface, logSealedBilling, []byte{0x84, 0x84}) + if len(rr) != 3+0x41C+2+sealTokenLen || rr[0] != tagVar { + t.Fatalf("billing: %d bytes", len(rr)) + } + acct, ok := cli.unseal(rr[3:3+0x41C], rr[3+0x41C+2:]) + if !ok || unansi(bytes.TrimRight(acct[8+0x3B:8+0x3B+40], "\x00")) != "alice" { + t.Fatalf("billing unsealed: %v %q", ok, acct[8+0x3B:8+0x3B+10]) + } + + // the password changed, sealed + data, token := cli.seal([]byte("password1\x00newpass99\x00")) + if rr := c.call(1, logsrvIface, logSealedPassword, vparam(data), vparam(token), []byte{0x83}); binary.LittleEndian.Uint32(rr[1:]) != 0 { + t.Fatalf("password change: %x", rr) + } + if _, err := st.CheckPassword("alice", "newpass99"); err != nil { + t.Fatal("password not changed") + } + // and a seal that doesn't check out is refused + data, _ = cli.seal([]byte("newpass99\x00other1234\x00")) + if rr := c.call(1, logsrvIface, logSealedPassword, vparam(data), vparam(make([]byte, 16)), []byte{0x83}); binary.LittleEndian.Uint32(rr[1:]) == 0 { + t.Fatal("a bad seal taken") + } +} diff --git a/internal/server/server.go b/internal/server/server.go index b3743dd..c8495c3 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -125,6 +125,10 @@ func (s *Server) Run(ctx context.Context) error { // CIM's Secure Login needs a key made from each password s.B.Store.SetKeepCIS(true) } + if l.Frontend == "marvel" { + // and MSN Classic's 1996 client, its NTLM sign-in the hashes + s.B.Store.SetKeepNTLM(true) + } if l.Kind == "ssh" { if err := s.sshSetup(l); err != nil { closeAll() diff --git a/internal/store/copy.go b/internal/store/copy.go index 269cfe1..c27da7c 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", "mailbox", "mail_uids", "mail_queue", "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", "cis_keys", "chats", "friends", "oscar_buddies", "msn_keys", "blocks", "address_book"} + "chan_boards", "chan_posts", "chan_bans", "chan_reports", "oscar_keys", "feedbag", "cis_keys", "chats", "friends", "oscar_buddies", "msn_keys", "blocks", "address_book", "ntlm_keys"} var columnPat = regexp.MustCompile(`(?m)^\s*("?\w+"?)\s+(\{\w+\})`) diff --git a/internal/store/msn_test.go b/internal/store/msn_test.go index bcaf28e..4c401e0 100644 --- a/internal/store/msn_test.go +++ b/internal/store/msn_test.go @@ -1,6 +1,8 @@ package store import ( + "bytes" + "encoding/hex" "path/filepath" "testing" ) @@ -105,3 +107,38 @@ func TestAddressBook(t *testing.T) { t.Fatalf("after removing: %+v", book) } } + +func TestNTLMKeys(t *testing.T) { + // the hashes of "password", as every NTLM write-up gives them + if got := hex.EncodeToString(LMHash("password")); got != "e52cac67419a9a224a3b108f3fa6cb6d" { + t.Errorf("LM: %s", got) + } + if got := hex.EncodeToString(NTHash("password")); got != "8846f7eaee8fb117ad06bdd830b7586c" { + t.Errorf("NT: %s", got) + } + BcryptCost = 4 + s, err := Open(filepath.Join(t.TempDir(), "bbs.db")) + if err != nil { + t.Fatal(err) + } + defer s.Close() + u, _ := s.CreateUser("alice", "password", "", false) + if _, _, ok, _ := s.NTLMKey(u.ID); ok { + t.Fatal("kept without SetKeepNTLM") + } + s.SetKeepNTLM(true) + s.CheckPassword("alice", "password") + lm, nt, ok, err := s.NTLMKey(u.ID) + if err != nil || !ok || !bytes.Equal(lm, LMHash("password")) || !bytes.Equal(nt, NTHash("password")) { + t.Fatalf("kept: %x %x %v %v", lm, nt, ok, err) + } + // a password changed where it isn't seen leaves them stale + s.db.Exec(`UPDATE users SET password = 'x' WHERE id = ?`, u.ID) + if _, _, ok, _ := s.NTLMKey(u.ID); ok { + t.Fatal("stale hashes used") + } + s.SetPassword(u.ID, "another1") + if lm, _, ok, _ := s.NTLMKey(u.ID); !ok || !bytes.Equal(lm, LMHash("another1")) { + t.Fatal("not kept on a new password") + } +} diff --git a/internal/store/ntlm.go b/internal/store/ntlm.go new file mode 100644 index 0000000..b526352 --- /dev/null +++ b/internal/store/ntlm.go @@ -0,0 +1,99 @@ +package store + +import ( + "crypto/des" + "database/sql" + "errors" + "strings" + "unicode/utf16" + + "golang.org/x/crypto/md4" + "golang.org/x/text/encoding/charmap" +) + +// The 1996 MSN client (Windows 95 OSR2, MSN 1.3) signs in with NTLM: it +// proves the password by DES over the server's challenge, keyed with the +// password's LM or NT hash, which a bcrypt hash cannot give. So both +// hashes are kept as CompuServe's key is (cis.go): whenever the password +// is known in the clear, bound to the password hash they were made with. +// They are password equivalents (the LM hash a weak one), kept only when +// an MSN Classic front end asks for them. + +// LMHash is a password's LAN Manager hash: its first 14 characters in +// capitals, as two DES keys over "KGS!@#$%". +func LMHash(pw string) []byte { + var k [14]byte + b, err := charmap.Windows1252.NewEncoder().Bytes([]byte(strings.ToUpper(pw))) + if err != nil { + b = []byte(strings.ToUpper(pw)) + } + copy(k[:], b) + out := make([]byte, 16) + for i := range 2 { + c, _ := des.NewCipher(DESKey(k[i*7 : i*7+7])) + c.Encrypt(out[i*8:], []byte("KGS!@#$%")) + } + return out +} + +// NTHash is a password's NT hash: MD4 of it in UTF-16LE. +func NTHash(pw string) []byte { + h := md4.New() + for _, u := range utf16.Encode([]rune(pw)) { + h.Write([]byte{byte(u), byte(u >> 8)}) + } + return h.Sum(nil) +} + +// DESKey spreads 7 bytes over a DES key's 8, a parity bit in each. +func DESKey(k []byte) []byte { + var v uint64 + for _, b := range k[:7] { + v = v<<8 | uint64(b) + } + out := make([]byte, 8) + for i := range 8 { + out[i] = byte(v>>(56-7*(i+1))) << 1 + } + return out +} + +// SetKeepNTLM says whether to keep the hashes: only with an MSN Classic +// front end, as they would let anyone who read the database sign in by it. +func (s *Store) SetKeepNTLM(on bool) { s.keepNTLM.Store(on) } + +// NTLMKey is the account's LM and NT hashes, if current ones are kept. +func (s *Store) NTLMKey(id int64) (lm, nt []byte, ok bool, err error) { + var bound, hash string + err = s.db.QueryRow(`SELECT n.lm, n.nt, n.bound, u.password FROM ntlm_keys n + JOIN users u ON u.id = n.user_id WHERE n.user_id = ?`, id).Scan(&lm, &nt, &bound, &hash) + if errors.Is(err, sql.ErrNoRows) { + return nil, nil, false, nil + } + if err != nil { + return nil, nil, false, err + } + return lm, nt, bound == hash && len(lm) == 16 && len(nt) == 16, nil +} + +// KeepNTLMKey keeps the account's hashes of pw (its password, just checked +// or set), bound to its password hash now, if the store keeps them. +func (s *Store) KeepNTLMKey(id int64, pw string) error { + if !s.keepNTLM.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 + } + lm, nt := LMHash(pw), NTHash(pw) + if ol, on, ok, err := s.NTLMKey(id); err == nil && ok && string(ol) == string(lm) && string(on) == string(nt) { + return nil + } + _, err := s.db.Exec(`INSERT INTO ntlm_keys (user_id, lm, nt, bound) VALUES (?, ?, ?, ?) + ON CONFLICT (user_id) DO UPDATE SET lm = excluded.lm, nt = excluded.nt, bound = excluded.bound`, id, lm, nt, hash) + return err +} diff --git a/internal/store/schema.go b/internal/store/schema.go index 6703544..a4eb396 100644 --- a/internal/store/schema.go +++ b/internal/store/schema.go @@ -259,6 +259,12 @@ CREATE TABLE IF NOT EXISTS ssh_keys ( created {int} NOT NULL, last_used {int} NOT NULL DEFAULT 0 )`, ` +CREATE TABLE IF NOT EXISTS ntlm_keys ( + user_id {int} NOT NULL PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE, + lm {blob} NOT NULL, + nt {blob} NOT NULL, + bound {str} NOT NULL +)`, ` CREATE TABLE IF NOT EXISTS cis_keys ( user_id {int} NOT NULL PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE, k {blob} NOT NULL, diff --git a/internal/store/store.go b/internal/store/store.go index 1a55bea..0c815e0 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -130,6 +130,8 @@ type Store struct { keepCIS atomic.Bool // keepMSN: and their MSN MD5 login digests (msn.go) keepMSN atomic.Bool + // keepNTLM: and their LM and NT hashes, for MSN Classic's 1996 client (ntlm.go) + keepNTLM atomic.Bool } // Open opens (and makes, if need be) the database at addr: a file's path @@ -268,6 +270,7 @@ func (s *Store) CreateUser(name, password, location string, sysop bool) (*User, s.KeepOSCARKeys(id, password) s.KeepCISKey(id, password) s.KeepMSNKey(id, password) + s.KeepNTLMKey(id, password) } return s.UserByID(id) } @@ -302,6 +305,7 @@ func (s *Store) CheckPassword(name, pw string) (*User, error) { s.KeepOSCARKeys(u.ID, pw) // best effort: the login stands without them s.KeepCISKey(u.ID, pw) s.KeepMSNKey(u.ID, pw) + s.KeepNTLMKey(u.ID, pw) return u, nil } @@ -320,6 +324,9 @@ func (s *Store) SetPassword(id int64, pw string) error { if err := s.KeepMSNKey(id, pw); err != nil { return err } + if err := s.KeepNTLMKey(id, pw); err != nil { + return err + } return s.KeepOSCARKeys(id, pw) }