diff --git a/TODO.md b/TODO.md
index ef62d4d..ceed97a 100644
--- a/TODO.md
+++ b/TODO.md
@@ -18,6 +18,19 @@ by modem, from the marvel-msn project's protocol notes. Next:
opened from the temporary folder.
- **MSN Today**: the Media Viewer title (MEDVIEW), a page of news.
+## MSN 2.x
+
+*Status: started; the NTLM ("MSN" security package) sign-in on mail,
+news and the web forum (`internal/ntlm`, `[security] ntlm`) is done.*
+
+For MSN 2.0 to 2.6 (Windows 95 and 98), whose programs are internet
+clients. Next:
+
+- **The Program Viewer**: what it loads at sign-in (the start page, its
+ channel list), and the MSN Sign-In dialer, found from the client.
+- **DPA**: the Distributed Password Authentication package of the later
+ Windows 98 mail, if it can be learned.
+
## An AOL front end
*Status: started; FDO91 (`internal/aol/fdo`), P3 (`internal/aol/p3`) and
diff --git a/bbs.conf.sample b/bbs.conf.sample
index 627c05f..b1ec03c 100644
--- a/bbs.conf.sample
+++ b/bbs.conf.sample
@@ -194,6 +194,13 @@ line_speed_ask = no
;name_deny_file = /etc/bbs/names.txt
;hack_log = /var/log/bbs/hack.log
;ban_minutes = 60
+; keep each password's LM and NT hashes (made when it is next typed),
+; so Microsoft's clients of the 1990s sign in without sending it: MSN 2.x's
+; Outlook Express (mail), Internet News and Program Viewer, by Secure
+; Password Authentication. The hashes are password equivalents, so the
+; database needs guarding as a password file does. Serving MSN Classic
+; keeps them anyway. See the wiki's MSN-2
+;ntlm = no
; scheduled events: a program (no shell), daily at a time or every N
; minutes; see the wiki's Sysop tools
diff --git a/cmd/bbs/main.go b/cmd/bbs/main.go
index 3e50d73..ebd4ec2 100644
--- a/cmd/bbs/main.go
+++ b/cmd/bbs/main.go
@@ -505,6 +505,10 @@ func serve(cfg *server.Config, path string) int {
b.Doors = cfg.Doors
b.Screens, b.Menus, b.Text, b.ScriptsDir = cfg.Screens, cfg.Menus, cfg.Text, cfg.ScriptsDir
b.Guard = cfg.Guard
+ if cfg.KeepNTLM {
+ // Microsoft's NTLM sign-ins, for MSN 2.x's mail, news and pages
+ st.SetKeepNTLM(true)
+ }
if m := cfg.MenuAuth; m != nil {
b.MenuAuth = &authd.Client{Socket: m.Socket, Timeout: m.Timeout}
b.MenuAuthCreate = m.Create
diff --git a/docs/wiki/Configuration-Reference.md b/docs/wiki/Configuration-Reference.md
index a0bb333..457ca20 100644
--- a/docs/wiki/Configuration-Reference.md
+++ b/docs/wiki/Configuration-Reference.md
@@ -158,6 +158,7 @@ keeping callers out: a file of addresses and networks refused, one of names no n
| `name_deny_file` | | | See the section above. Examples: `/etc/bbs/names.txt`. |
| `hack_log` | | | See the section above. Examples: `/var/log/bbs/hack.log`. |
| `ban_minutes` | | | See the section above. Examples: `60`. |
+| `ntlm` | | | keep each password's LM and NT hashes (made when it is next typed), so Microsoft's clients of the 1990s sign in without sending it: MSN 2.x's Outlook Express (mail), Internet News and Program Viewer, by Secure Password Authentication. The hashes are password equivalents, so the database needs guarding as a password file does. Serving MSN Classic keeps them anyway. See the wiki's MSN-2. Examples: `no`. |
## `[event NAME]`
diff --git a/docs/wiki/MSN-2.md b/docs/wiki/MSN-2.md
new file mode 100644
index 0000000..7bd0199
--- /dev/null
+++ b/docs/wiki/MSN-2.md
@@ -0,0 +1,68 @@
+MSN 2.0 (late 1996) and the 2.5 and 2.6 that came with Windows 98 turned
+The Microsoft Network into internet services: web pages in the MSN
+Program Viewer (Internet Explorer inside), newsgroups for the bulletin
+boards, IRC for chat, and internet mail. Members signed in to each with
+MSN's own security package, which is NTLM under another name ("MSN", once
+codenamed Sicily): the password never travels, only an answer to a
+challenge worked out from its hash. The BBS answers that sign-in on its
+mail, news and web servers, so MSN 2.x's programs sign in to the BBS as
+they did to MSN. This is early work, not yet tried with a real client.
+
+## Turning it on
+
+```ini
+[security]
+ntlm = yes
+```
+
+The sign-in checks each password's LAN Manager and NT hashes, which the
+BBS keeps once this is on (or MSN Classic is served, whose 1996 client
+signs in the same way). They are made when the password is next typed in
+the clear: when its owner signs in any other way (telnet, the web form, a
+mail program's plain password) or sets a password. Until then, that
+member's NTLM sign-in fails, and the log says why. The hashes are password
+equivalents, the LM hash a weak one, so the database needs guarding as a
+password file does.
+
+## What signs in
+
+The member ID is the BBS name (or the mail address, or the name with any
+domain), and the password the BBS password.
+
+- **Mail**: POP3 and IMAP, and SMTP on the submission listener, offer
+ `NTLM` and `MSN` beside `PLAIN`. In Outlook Express (or Internet Mail),
+ give the account the BBS's servers and tick "Log on using Secure
+ Password Authentication" for incoming mail, and under the outgoing
+ server's "My server requires authentication", the same.
+- **Newsgroups**: NNTP's `AUTHINFO GENERIC NTLM` (or `MSN`), as
+ Microsoft's news servers had it. In Internet News (or Outlook Express),
+ tick "This server requires me to log on" and "Log on using Secure
+ Password Authentication".
+- **The web forum**: `/forum/login/ntlm` asks the browser for NTLM (or
+ MSN), and the sign-in page links to it. Internet Explorer, the Program
+ Viewer's browser, answers with the name and password it already has
+ (MSN's or Windows'), or asks for them. The exchange needs one connection from start to
+ end, so a proxy in front of the BBS has to keep connections as they are.
+- **Chat**: Comic Chat, MSN 2.x's chat program, is an IRC client: point it
+ at the BBS's IRC server ([IRC](IRC)), which it signs in to by password.
+
+A server with `tls = required` asks for TLS before any sign-in, NTLM's
+too, and Windows 95 and 98 programs can't speak the TLS that a modern
+server does, so leave TLS optional on the servers these clients use.
+
+## Not served yet
+
+- The Program Viewer's own pages: MSN's start page, its channels and
+ OnStage shows, and the MSN Sign-In dialer. What the Viewer asks for
+ first isn't documented anywhere found so far; it needs the client
+ itself looked at.
+- DPA (Distributed Password Authentication), the other package MSN's
+ later Windows 98 mail used for Secure Password Authentication. It isn't
+ NTLM, and isn't documented.
+- MSN's own 16-character passwords: the security package spread the 15th
+ and 16th characters over the first 14 for the LM hash. Passwords longer
+ than 14 characters sign in by the NT hash, which needs the client to
+ send it.
+
+MSN 2.0 kept MSN Classic's Exchange mail for its members; that is served
+by [MSN Classic](MSN-Classic).
diff --git a/docs/wiki/MSN-Classic.md b/docs/wiki/MSN-Classic.md
index aea819d..548b020 100644
--- a/docs/wiki/MSN-Classic.md
+++ b/docs/wiki/MSN-Classic.md
@@ -63,7 +63,8 @@ Point the client's phone number at the line that reaches that listener.
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
+ is served (a `[marvel]` section or a `frontend = marvel` listener) or
+ `[security] ntlm` is on ([MSN 2.x](MSN-2)), 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
diff --git a/docs/wiki/_Sidebar.md b/docs/wiki/_Sidebar.md
index 2422766..8678613 100644
--- a/docs/wiki/_Sidebar.md
+++ b/docs/wiki/_Sidebar.md
@@ -39,6 +39,7 @@
- [AOL clients](AOL)
- [MSN Messenger](MSN-Messenger)
- [MSN Classic (1995)](MSN-Classic)
+- [MSN 2.x (1996)](MSN-2)
- [Yahoo! Messenger](Yahoo-Messenger)
- [MRC](MRC)
- [News, weather and quotes](News-Weather-and-Quotes)
diff --git a/internal/api/forum.go b/internal/api/forum.go
index e3fde54..ff45530 100644
--- a/internal/api/forum.go
+++ b/internal/api/forum.go
@@ -7,6 +7,7 @@ import (
"github.com/D-Modem/bbs/internal/forum"
"github.com/D-Modem/bbs/internal/imageboard"
+ "github.com/D-Modem/bbs/internal/ntlm"
"github.com/D-Modem/bbs/internal/store"
)
@@ -35,6 +36,16 @@ func (f forumSessions) LoginCode(r *http.Request, code string) (string, *store.U
return f.session(r, u)
}
+// LoginNTLM checks an NTLM sign-in as a forum login from the request's
+// address, and starts a browser session for its user.
+func (f forumSessions) LoginNTLM(r *http.Request, a *ntlm.Auth, challenge []byte) (string, *store.User, error) {
+ u, err := f.s.B.AuthenticateNTLM("forum", "ip:"+hostOf(r), a, challenge)
+ if err != nil {
+ return "", nil, err
+ }
+ return f.session(r, u)
+}
+
// session is a browser's session for u, signed in.
func (f forumSessions) session(r *http.Request, u *store.User) (string, *store.User, error) {
s := f.s
diff --git a/internal/bbs/ntlm.go b/internal/bbs/ntlm.go
new file mode 100644
index 0000000..c7bdbc0
--- /dev/null
+++ b/internal/bbs/ntlm.go
@@ -0,0 +1,62 @@
+package bbs
+
+import (
+ "strings"
+
+ "github.com/D-Modem/bbs/internal/ntlm"
+ "github.com/D-Modem/bbs/internal/store"
+)
+
+// NTLMOffered reports whether NTLM sign-ins can be offered: only while the
+// store keeps the password hashes they are checked against (while MSN is
+// served).
+func (b *BBS) NTLMOffered() bool { return b.Store.KeepsNTLM() }
+
+// NTLMCheck is a check for AuthenticateBy or LoginWith: the account a
+// names (by its name, its screen name, or an address's name before the
+// @), if a's answer to challenge proves its password. It gives the
+// account's hashes to keys, if given, for the session key. An account
+// whose hashes aren't kept yet fails, logged as why.
+func (b *BBS) NTLMCheck(who string, a *ntlm.Auth, challenge []byte, keys func(lm, nt []byte)) func() (*store.User, error) {
+ return func() (*store.User, error) {
+ u, err := b.ntlmUser(a.User)
+ if err != nil {
+ return nil, store.ErrNotFound
+ }
+ lm, nt, ok, err := b.Store.NTLMKey(u.ID)
+ if err != nil || !ok {
+ b.Log.Printf("%s: NTLM: no password hashes kept for %s yet: they are kept when the password is next typed in the clear", who, u.Name)
+ return nil, store.ErrNotFound
+ }
+ if !a.Verify(lm, nt, challenge) {
+ return nil, store.ErrNotFound
+ }
+ if keys != nil {
+ keys(lm, nt)
+ }
+ return u, nil
+ }
+}
+
+func (b *BBS) ntlmUser(name string) (*store.User, error) {
+ name = strings.TrimSpace(name)
+ if name == "" {
+ return nil, store.ErrNotFound
+ }
+ u, err := b.Store.UserByName(name)
+ if err == nil {
+ return u, nil
+ }
+ if u, err := b.Store.UserByScreenName(name); err == nil {
+ return u, nil
+ }
+ if local, _, ok := strings.Cut(name, "@"); ok && local != "" {
+ return b.Store.UserByName(local)
+ }
+ return nil, err
+}
+
+// AuthenticateNTLM is a login by NTLM, as Authenticate's by password.
+func (b *BBS) AuthenticateNTLM(who, source string, a *ntlm.Auth, challenge []byte) (*store.User, error) {
+ return b.authenticate(who, source, a.User, b.NTLMCheck(who, a, challenge, nil))
+}
diff --git a/internal/confui/fields.go b/internal/confui/fields.go
index 5936743..abf790e 100644
--- a/internal/confui/fields.go
+++ b/internal/confui/fields.go
@@ -84,7 +84,8 @@ var labels = map[string]string{
"general.tn3270_logo": "3270 logo (PNG)", "general.page_command": "Page command",
"security.deny_file": "Addresses refused (file)", "security.name_deny_file": "Names refused (file)",
"security.hack_log": "Hack log", "security.ban_minutes": "Ban after a lock-out (min)",
- "chan.dir": "Image boards' files", "fido.dir": "FidoNet's packets",
+ "security.ntlm": "Keep NTLM hashes (MSN 2.x)",
+ "chan.dir": "Image boards' files", "fido.dir": "FidoNet's packets",
"general.user": "Run as user", "general.group": "and group",
"modemmenu.auth_socket": "modemmenu's auth socket", "modemmenu.create_users": "Make accounts it knows",
"modemmenu.timeout": "Its answer within (s)",
diff --git a/internal/confui/menus.go b/internal/confui/menus.go
index 42563b1..ea46998 100644
--- a/internal/confui/menus.go
+++ b/internal/confui/menus.go
@@ -199,7 +199,7 @@ func (e *Editor) systemMenu() page {
out = append(out, e.fields(g, "files_dir", "max_file_size", "upload_quota", "screens_dir", "scripts_dir")...)
out = append(out, e.field(sec("chan"), "dir"), e.field(sec("fido"), "dir"))
out = append(out, heading("Security"))
- out = append(out, e.fields(sec("security"), "deny_file", "name_deny_file", "hack_log", "ban_minutes")...)
+ out = append(out, e.fields(sec("security"), "deny_file", "name_deny_file", "hack_log", "ban_minutes", "ntlm")...)
out = append(out, heading("The process"))
out = append(out, e.fields(g, "user", "group")...)
out = append(out,
diff --git a/internal/email/email.go b/internal/email/email.go
index 5e19b97..a3a53e5 100644
--- a/internal/email/email.go
+++ b/internal/email/email.go
@@ -23,6 +23,7 @@ import (
"github.com/D-Modem/bbs/internal/bbs"
"github.com/D-Modem/bbs/internal/ftn"
+ "github.com/D-Modem/bbs/internal/ntlm"
"github.com/D-Modem/bbs/internal/store"
)
@@ -192,13 +193,48 @@ func (s *Service) Login(who string, remote net.Addr, service, name, password str
name = u.Name
}
}
- // a local client's address is everyone's: its failures count
- // against the account named
- source := bbs.LocalSource(service, name)
+ return s.B.Authenticate(who, loginSource(remote, service, name), name, password)
+}
+
+// loginSource is where a login's failures count: a local client's address
+// is everyone's, so its count against the account named.
+func loginSource(remote net.Addr, service, name string) string {
if a, ok := remote.(*net.TCPAddr); ok && !a.IP.IsLoopback() {
- source = "ip:" + a.IP.String()
+ return "ip:" + a.IP.String()
}
- return s.B.Authenticate(who, source, name, password)
+ return bbs.LocalSource(service, name)
+}
+
+// NTLM mechanisms: Microsoft's name for it and MSN's (its security
+// package, which Outlook Express uses for an MSN account's Secure Password
+// Authentication). Offered only while the BBS keeps the hashes they check.
+var ntlmMechs = []string{"NTLM", "MSN"}
+
+func isNTLMMech(m string) bool { return strings.EqualFold(m, "NTLM") || strings.EqualFold(m, "MSN") }
+
+// ntlmOffered reports whether NTLM sign-ins are.
+func (s *Service) ntlmOffered() bool { return s.B.NTLMOffered() }
+
+// ntlmServer is an NTLM sign-in's SASL server, which logs in to done.
+func (s *Service) ntlmServer(who string, remote net.Addr, service string, done func(*store.User)) *ntlm.SASL {
+ return &ntlm.SASL{Exchange: ntlm.Exchange{Target: s.ntlmTarget()}, Login: func(a *ntlm.Auth, c []byte) error {
+ u, err := s.B.AuthenticateNTLM(who, loginSource(remote, service, a.User), a, c)
+ if err != nil {
+ return err
+ }
+ done(u)
+ return nil
+ }}
+}
+
+// ntlmTarget is the domain a CHALLENGE names: the BBS's mail domain's
+// first label, as a Windows domain would be.
+func (s *Service) ntlmTarget() string {
+ d, _, _ := strings.Cut(s.Set.Domain, ".")
+ if d == "" {
+ d = "BBS"
+ }
+ return strings.ToUpper(d)
}
// mayMail reports whether u's access lets them mail anyone (else only the
diff --git a/internal/email/imap.go b/internal/email/imap.go
index a4d6935..166c37b 100644
--- a/internal/email/imap.go
+++ b/internal/email/imap.go
@@ -15,6 +15,7 @@ import (
"github.com/emersion/go-imap/v2"
"github.com/emersion/go-imap/v2/imapserver"
"github.com/emersion/go-message/textproto"
+ "github.com/emersion/go-sasl"
"github.com/D-Modem/bbs/internal/bbs"
"github.com/D-Modem/bbs/internal/store"
@@ -132,10 +133,51 @@ func (is *imapSession) Login(username, password string) error {
if err != nil {
return imapserver.ErrAuthFailed
}
+ is.loggedIn(u, "")
+ return nil
+}
+
+func (is *imapSession) loggedIn(u *store.User, how string) {
is.user = u
is.wake, is.stop = is.x.svc.watch(u.ID)
- is.x.svc.B.Log.Printf("%s: %s logged in", is.who, u.Name)
- return nil
+ is.x.svc.B.Log.Printf("%s: %s logged in%s", is.who, u.Name, how)
+}
+
+// AuthenticateMechanisms are PLAIN, and NTLM while it's offered.
+func (is *imapSession) AuthenticateMechanisms() []string {
+ m := []string{sasl.Plain}
+ if is.x.svc.ntlmOffered() {
+ m = append(m, ntlmMechs...)
+ }
+ return m
+}
+
+// Authenticate is a mechanism's server.
+func (is *imapSession) Authenticate(mech string) (sasl.Server, error) {
+ switch {
+ case strings.EqualFold(mech, sasl.Plain):
+ return sasl.NewPlainServer(func(identity, name, password string) error {
+ if identity != "" && identity != name {
+ return imapserver.ErrAuthFailed
+ }
+ return is.Login(name, password)
+ }), nil
+ case isNTLMMech(mech) && is.x.svc.ntlmOffered():
+ x := is.x.svc.ntlmServer(is.who, is.conn.NetConn().RemoteAddr(), "imap", func(u *store.User) { is.loggedIn(u, " by NTLM") })
+ return saslFailed{x}, nil
+ }
+ return nil, &imap.Error{Type: imap.StatusResponseTypeNo, Text: "SASL mechanism not supported"}
+}
+
+// saslFailed gives a failed sign-in IMAP's own error.
+type saslFailed struct{ sasl.Server }
+
+func (s saslFailed) Next(r []byte) ([]byte, bool, error) {
+ c, done, err := s.Server.Next(r)
+ if err != nil {
+ err = imapserver.ErrAuthFailed
+ }
+ return c, done, err
}
// uidValidity is the user's UIDVALIDITY, the same for every folder: the
diff --git a/internal/email/ntlm_test.go b/internal/email/ntlm_test.go
new file mode 100644
index 0000000..7c0e505
--- /dev/null
+++ b/internal/email/ntlm_test.go
@@ -0,0 +1,106 @@
+package email
+
+import (
+ "bufio"
+ "encoding/base64"
+ "net"
+ "strings"
+ "testing"
+
+ "github.com/emersion/go-imap/v2/imapclient"
+ "github.com/emersion/go-smtp"
+
+ "github.com/D-Modem/bbs/internal/ntlm"
+)
+
+// ntlmClient is a client's NTLM, as Outlook Express's: v1, in Unicode.
+type ntlmClient struct {
+ mech, user, pw string
+}
+
+func (c *ntlmClient) Start() (string, []byte, error) {
+ return c.mech, ntlm.ClientNegotiate(ntlm.FlagUnicode | ntlm.FlagNTLM | ntlm.FlagRequestTarget), nil
+}
+
+func (c *ntlmClient) Next(challenge []byte) ([]byte, error) {
+ return c.answer(challenge), nil
+}
+
+func (c *ntlmClient) answer(ch []byte) []byte {
+ return ntlm.ClientAuthenticate(ntlm.FlagUnicode|ntlm.FlagNTLM, "B", c.user, nil, ntlm.DESL(ntlm.NTHash(c.pw), ch[24:32]))
+}
+
+func TestNTLM(t *testing.T) {
+ b := newSite(t, "b.test", &fakeDNS{}, []string{"alice", "bob"}, "pop3", "imap", Submission)
+ // not offered while the hashes aren't kept
+ c, err := net.Dial("tcp", b.addrs["pop3"])
+ if err != nil {
+ t.Fatal(err)
+ }
+ r := bufio.NewReader(c)
+ pop(t, r, c, "", false)
+ if got := pop(t, r, c, "AUTH", true); strings.Contains(got, "NTLM") {
+ t.Errorf("offered: %q", got)
+ }
+ c.Close()
+
+ b.st.SetKeepNTLM(true)
+ b.st.SetPassword(b.users["bob"].ID, "password1") // kept as it's set
+ c, err = net.Dial("tcp", b.addrs["pop3"])
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer c.Close()
+ r = bufio.NewReader(c)
+ pop(t, r, c, "", false)
+ if got := pop(t, r, c, "AUTH", true); !strings.Contains(got, "\r\nNTLM\r\nMSN\r\n") {
+ t.Errorf("not offered: %q", got)
+ }
+ popNTLM := func(mech, user, pw string) string {
+ cl := &ntlmClient{mech, user, pw}
+ if got := pop(t, r, c, "AUTH "+mech, false); got != "+OK\r\n" {
+ t.Fatalf("AUTH %s: %q", mech, got)
+ }
+ _, neg, _ := cl.Start()
+ got := pop(t, r, c, base64.StdEncoding.EncodeToString(neg), false)
+ ch, err := base64.StdEncoding.DecodeString(strings.TrimSpace(strings.TrimPrefix(got, "+ ")))
+ if err != nil || ntlm.Type(ch) != ntlm.TypeChallenge {
+ t.Fatalf("challenge: %q", got)
+ }
+ return pop(t, r, c, base64.StdEncoding.EncodeToString(cl.answer(ch)), false)
+ }
+ if got := popNTLM("NTLM", "bob", "wrong"); !strings.HasPrefix(got, "-ERR") {
+ t.Errorf("a wrong password: %q", got)
+ }
+ if got := popNTLM("NTLM", "alice", "password1"); !strings.HasPrefix(got, "-ERR") {
+ t.Errorf("no hashes kept yet: %q", got)
+ }
+ if got := popNTLM("MSN", "bob@b.test", "password1"); !strings.HasPrefix(got, "+OK bob has ") {
+ t.Errorf("by MSN's name: %q", got)
+ }
+
+ // SMTP submission and IMAP, by the same
+ sc, err := smtp.Dial(b.addrs[Submission])
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := sc.Auth(&ntlmClient{"NTLM", "bob", "wrong"}); err == nil {
+ t.Error("SMTP: a wrong password accepted")
+ }
+ if err := sc.Auth(&ntlmClient{"NTLM", "bob", "password1"}); err != nil {
+ t.Errorf("SMTP: %v", err)
+ }
+ sc.Close()
+
+ ic, err := imapclient.DialInsecure(b.addrs["imap"], nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer ic.Close()
+ if err := ic.Authenticate(&ntlmClient{"MSN", "bob", "password1"}); err != nil {
+ t.Errorf("IMAP: %v", err)
+ }
+ if _, err := ic.Select("INBOX", nil).Wait(); err != nil {
+ t.Errorf("IMAP select: %v", err)
+ }
+}
diff --git a/internal/email/pop3.go b/internal/email/pop3.go
index 9768b11..af4ce4e 100644
--- a/internal/email/pop3.go
+++ b/internal/email/pop3.go
@@ -192,9 +192,18 @@ func (ps *popSession) authorization(cmd string, args []string, line string) {
case "AUTH":
if len(args) == 0 {
ps.ok("Mechanisms follow")
+ if ps.x.svc.ntlmOffered() {
+ ps.w.WriteString(strings.Join(ntlmMechs, "\r\n") + "\r\n")
+ }
ps.w.WriteString("PLAIN\r\n.\r\n")
return
}
+ if isNTLMMech(args[0]) && ps.x.svc.ntlmOffered() {
+ if ps.mayLogin() {
+ ps.ntlm()
+ }
+ return
+ }
if !strings.EqualFold(args[0], "PLAIN") {
ps.err("Only PLAIN")
return
@@ -226,6 +235,49 @@ func (ps *popSession) authorization(cmd string, args []string, line string) {
}
}
+// ntlm is AUTH NTLM (or MSN), as MS-POP3 has it: +OK, then the
+// NEGOTIATE, answered "+ " and the CHALLENGE, then the AUTHENTICATE. A
+// "*" cancels.
+func (ps *popSession) ntlm() {
+ var u *store.User
+ x := ps.x.svc.ntlmServer(ps.who, ps.c.RemoteAddr(), "pop3", func(v *store.User) { u = v })
+ ps.w.WriteString("+OK\r\n")
+ for {
+ ps.w.Flush()
+ l, err := ps.r.ReadString('\n')
+ if err != nil {
+ return
+ }
+ l = strings.TrimSpace(l)
+ if l == "*" {
+ ps.err("[AUTH] Cancelled")
+ return
+ }
+ in, err := base64.StdEncoding.DecodeString(l)
+ if err != nil {
+ ps.err("[AUTH] Not base64")
+ return
+ }
+ out, done, err := x.Next(in)
+ if done {
+ if err != nil || u == nil {
+ ps.err("[AUTH] Authentication failed")
+ return
+ }
+ ps.open(u)
+ return
+ }
+ if err != nil {
+ ps.err("[AUTH] " + err.Error())
+ return
+ }
+ if out == nil {
+ continue // waiting for the NEGOTIATE
+ }
+ ps.w.WriteString("+ " + base64.StdEncoding.EncodeToString(out) + "\r\n")
+ }
+}
+
// stls answers STLS and makes the connection TLS. Anything sent before
// the handshake hangs up (an injection).
func (ps *popSession) stls() {
@@ -260,6 +312,13 @@ func (ps *popSession) login(name, pw string) {
ps.err("[AUTH] Authentication failed")
return
}
+ ps.open(u)
+}
+
+// open opens a user's maildrop, logged in.
+func (ps *popSession) open(u *store.User) {
+ svc := ps.x.svc
+ ps.name = ""
es, err := svc.B.Store.FolderEntries(u.ID, store.FolderInbox)
if err != nil {
ps.err("[SYS/TEMP] The maildrop cannot be read")
diff --git a/internal/email/smtp.go b/internal/email/smtp.go
index 832882b..312f042 100644
--- a/internal/email/smtp.go
+++ b/internal/email/smtp.go
@@ -108,12 +108,17 @@ func (ss *smtpSession) tls() bool {
return ok
}
-// AuthMechanisms are those offered: PLAIN and LOGIN, for submission.
+// AuthMechanisms are those offered: PLAIN and LOGIN, and NTLM while
+// it's offered, for submission.
func (ss *smtpSession) AuthMechanisms() []string {
if ss.x.kind != Submission {
return nil
}
- return []string{sasl.Plain, sasl.Login}
+ m := []string{sasl.Plain, sasl.Login}
+ if ss.x.svc.ntlmOffered() {
+ m = append(m, ntlmMechs...)
+ }
+ return m
}
// Auth is a mechanism's server.
@@ -133,6 +138,12 @@ func (ss *smtpSession) Auth(mech string) (sasl.Server, error) {
ss.x.svc.B.Log.Printf("%s: %s logged in", ss.who, u.Name)
return nil
}
+ if isNTLMMech(mech) && ss.x.svc.ntlmOffered() {
+ return ss.x.svc.ntlmServer(ss.who, ss.c.Conn().RemoteAddr(), "smtp", func(u *store.User) {
+ ss.user = u
+ ss.x.svc.B.Log.Printf("%s: %s logged in by NTLM", ss.who, u.Name)
+ }), nil
+ }
switch mech {
case sasl.Plain:
return sasl.NewPlainServer(login), nil
diff --git a/internal/forum/forum.go b/internal/forum/forum.go
index bdf5b55..b7a3b55 100644
--- a/internal/forum/forum.go
+++ b/internal/forum/forum.go
@@ -131,6 +131,7 @@ type Server struct {
tmpl map[string]*template.Template // by theme
key []byte // for forms' CSRF tokens
live atomic.Pointer[Options] // Reconfigure's
+ ntlm ntlmWaits // NTLM sign-ins under way
}
// Options are the forum's settings that can change while it runs.
@@ -206,6 +207,7 @@ func (s *Server) Handler() (http.Handler, error) {
"GET " + Base + "/search": s.search,
"GET " + Base + "/login": s.login,
"POST " + Base + "/login": s.login,
+ "GET " + Base + "/login/ntlm": s.loginNTLM,
"POST " + Base + "/logout": s.logout,
"GET " + Base + "/register": s.register,
"POST " + Base + "/register": s.register,
diff --git a/internal/forum/ntlm.go b/internal/forum/ntlm.go
new file mode 100644
index 0000000..20c94ba
--- /dev/null
+++ b/internal/forum/ntlm.go
@@ -0,0 +1,145 @@
+package forum
+
+import (
+ "encoding/base64"
+ "html/template"
+ "net/http"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/D-Modem/bbs/internal/ntlm"
+ "github.com/D-Modem/bbs/internal/store"
+)
+
+// Signing in by NTLM, as MSN 2.x's Program Viewer (Internet Explorer 3
+// inside) signed in to MSN's pages: its member's password never sent,
+// only an answer to a challenge. The exchange is HTTP's (MS-NTHT): a 401
+// asking for NTLM (or MSN, MSN's name for it), the NEGOTIATE in an
+// Authorization header, a 401 with the CHALLENGE, then the AUTHENTICATE,
+// all on one connection.
+
+// NTLMSessions are Sessions that can sign in by NTLM.
+type NTLMSessions interface {
+ // LoginNTLM checks an AUTHENTICATE's answer to challenge (throttled
+ // and logged as any login) and gives a session's secret.
+ LoginNTLM(r *http.Request, a *ntlm.Auth, challenge []byte) (secret string, u *store.User, err error)
+}
+
+// ntlmWaits are the exchanges waiting for their AUTHENTICATE, by
+// connection (its remote address and port).
+type ntlmWaits struct {
+ mu sync.Mutex
+ m map[string]ntlmWait
+}
+
+type ntlmWait struct {
+ x *ntlm.Exchange
+ scheme string
+ at time.Time
+}
+
+func (w *ntlmWaits) put(conn string, x ntlmWait) {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ if w.m == nil {
+ w.m = map[string]ntlmWait{}
+ }
+ for k, v := range w.m {
+ if time.Since(v.at) > time.Minute {
+ delete(w.m, k)
+ }
+ }
+ if len(w.m) < 4096 {
+ w.m[conn] = x
+ }
+}
+
+func (w *ntlmWaits) take(conn string) (ntlmWait, bool) {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ x, ok := w.m[conn]
+ delete(w.m, conn)
+ return x, ok && time.Since(x.at) <= time.Minute
+}
+
+// ntlmOn reports whether NTLM sign-ins are offered here.
+func (s *Server) ntlmOn() bool {
+ _, ok := s.Sessions.(NTLMSessions)
+ return ok && s.B.NTLMOffered()
+}
+
+var ntlmPage = template.Must(template.New("").Parse(`