mirror of
https://github.com/D-Modem/bbs.git
synced 2026-11-28 17:38:04 -08:00
Merge pull request #53 from D-Modem/claude/project-thread-zw6c9g
MSN 2.x: NTLM sign-in for mail, news and the web forum
This commit is contained in:
32 files changed
+1383
-259
No files matched your search
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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]`
|
||||
|
||||
@@ -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).
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
@@ -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)",
|
||||
|
||||
@@ -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,
|
||||
|
||||
+41
-5
@@ -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
|
||||
|
||||
+44
-2
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
|
||||
+13
-2
@@ -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
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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(`<html><head><title>Sign In</title></head><body>
|
||||
<p>{{.Text}}</p>
|
||||
<p><a href="/forum/login?back={{.Back}}">Sign in with your name and password</a></p>
|
||||
</body></html>`))
|
||||
|
||||
// loginNTLM is /forum/login/ntlm: the exchange, then back where the
|
||||
// caller was, signed in.
|
||||
func (s *Server) loginNTLM(q *req) {
|
||||
back := safeBack(q.r.FormValue("back"))
|
||||
ns, ok := s.Sessions.(NTLMSessions)
|
||||
if !ok || !s.B.NTLMOffered() {
|
||||
q.redirect(Base + "/login?back=" + urlEscape(back))
|
||||
return
|
||||
}
|
||||
if q.user != nil {
|
||||
q.redirect(back)
|
||||
return
|
||||
}
|
||||
ask := func(text string, challenge []byte, scheme string) {
|
||||
h := q.w.Header()
|
||||
if challenge != nil {
|
||||
h.Add("WWW-Authenticate", scheme+" "+base64.StdEncoding.EncodeToString(challenge))
|
||||
} else {
|
||||
h.Add("WWW-Authenticate", "NTLM")
|
||||
h.Add("WWW-Authenticate", "MSN")
|
||||
}
|
||||
h.Set("Content-Type", "text/html; charset=utf-8")
|
||||
q.w.WriteHeader(http.StatusUnauthorized)
|
||||
ntlmPage.Execute(q.w, map[string]string{"Text": text, "Back": back})
|
||||
}
|
||||
scheme, token, _ := strings.Cut(q.r.Header.Get("Authorization"), " ")
|
||||
if !strings.EqualFold(scheme, "NTLM") && !strings.EqualFold(scheme, "MSN") {
|
||||
ask("Signing in with your MSN password...", nil, "")
|
||||
return
|
||||
}
|
||||
in, err := base64.StdEncoding.DecodeString(strings.TrimSpace(token))
|
||||
if err != nil {
|
||||
ask("That sign-in could not be read.", nil, "")
|
||||
return
|
||||
}
|
||||
conn := q.r.RemoteAddr
|
||||
switch ntlm.Type(in) {
|
||||
case ntlm.TypeNegotiate:
|
||||
x := &ntlm.Exchange{Target: "BBS"}
|
||||
c, err := x.Challenge(in)
|
||||
if err != nil {
|
||||
ask("That sign-in could not be read.", nil, "")
|
||||
return
|
||||
}
|
||||
s.ntlm.put(conn, ntlmWait{x, scheme, time.Now()})
|
||||
ask("Signing in...", c, scheme)
|
||||
return
|
||||
case ntlm.TypeAuthenticate:
|
||||
wait, ok := s.ntlm.take(conn)
|
||||
if !ok {
|
||||
ask("That sign-in took too long: try again.", nil, "")
|
||||
return
|
||||
}
|
||||
a, c, err := wait.x.Authenticate(in)
|
||||
if err != nil {
|
||||
ask("That sign-in could not be read.", nil, "")
|
||||
return
|
||||
}
|
||||
secret, _, err := ns.LoginNTLM(q.r, a, c)
|
||||
if err != nil {
|
||||
ask(capital(err.Error())+".", nil, "")
|
||||
return
|
||||
}
|
||||
q.setCookie(secret)
|
||||
q.redirect(back)
|
||||
return
|
||||
}
|
||||
ask("That sign-in could not be read.", nil, "")
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package forum
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/D-Modem/bbs/internal/ntlm"
|
||||
"github.com/D-Modem/bbs/internal/store"
|
||||
)
|
||||
|
||||
// LoginNTLM checks an NTLM sign-in on the BBS and starts a session.
|
||||
func (s *sessions) LoginNTLM(r *http.Request, a *ntlm.Auth, challenge []byte) (string, *store.User, error) {
|
||||
u, err := s.b.AuthenticateNTLM("forum", "test", a, challenge)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
return s.session(u)
|
||||
}
|
||||
|
||||
// TestNTLMLogin: the exchange in headers on one connection, as Internet
|
||||
// Explorer has it, and a session at its end.
|
||||
func TestNTLMLogin(t *testing.T) {
|
||||
s := setup(t)
|
||||
st := s.b.Store
|
||||
if _, _, body := s.browser().get("/forum/login"); strings.Contains(body, "/forum/login/ntlm") {
|
||||
t.Error("offered while the hashes aren't kept")
|
||||
}
|
||||
st.SetKeepNTLM(true)
|
||||
alice, _ := st.UserByName("alice")
|
||||
st.SetPassword(alice.ID, "password1")
|
||||
if _, _, body := s.browser().get("/forum/login"); !strings.Contains(body, "/forum/login/ntlm") {
|
||||
t.Error("not offered")
|
||||
}
|
||||
|
||||
try := func(pw string) (int, string, string) {
|
||||
jar, _ := cookiejar.New(nil)
|
||||
c := &http.Client{Jar: jar, Transport: &http.Transport{MaxConnsPerHost: 1}}
|
||||
do := func(auth string) *http.Response {
|
||||
req, _ := http.NewRequest("GET", s.ts.URL+"/forum/login/ntlm?back=/forum/online", nil)
|
||||
if auth != "" {
|
||||
req.Header.Set("Authorization", auth)
|
||||
}
|
||||
resp, err := c.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
io.Copy(io.Discard, resp.Body)
|
||||
resp.Body.Close()
|
||||
return resp
|
||||
}
|
||||
r := do("")
|
||||
if r.StatusCode != 401 || strings.Join(r.Header.Values("WWW-Authenticate"), ",") != "NTLM,MSN" {
|
||||
t.Fatalf("asked: %d %v", r.StatusCode, r.Header.Values("WWW-Authenticate"))
|
||||
}
|
||||
r = do("MSN " + base64.StdEncoding.EncodeToString(ntlm.ClientNegotiate(ntlm.FlagUnicode|ntlm.FlagNTLM)))
|
||||
scheme, tok, _ := strings.Cut(r.Header.Get("WWW-Authenticate"), " ")
|
||||
ch, err := base64.StdEncoding.DecodeString(tok)
|
||||
if r.StatusCode != 401 || scheme != "MSN" || err != nil || ntlm.Type(ch) != ntlm.TypeChallenge {
|
||||
t.Fatalf("challenge: %d %q", r.StatusCode, r.Header.Get("WWW-Authenticate"))
|
||||
}
|
||||
r = do("MSN " + base64.StdEncoding.EncodeToString(ntlm.ClientAuthenticate(ntlm.FlagUnicode|ntlm.FlagNTLM, "", "alice", nil, ntlm.DESL(ntlm.NTHash(pw), ch[24:32]))))
|
||||
var name string
|
||||
for _, ck := range jar.Cookies(r.Request.URL) {
|
||||
if ck.Name == cookieName && ck.Value != "" {
|
||||
name = "signed in"
|
||||
}
|
||||
}
|
||||
return r.StatusCode, r.Request.URL.Path, name
|
||||
}
|
||||
if code, _, in := try("wrong"); code != 401 || in != "" {
|
||||
t.Errorf("a wrong password: %d %q", code, in)
|
||||
}
|
||||
if code, at, in := try("password1"); code != 200 || at != "/forum/online" || in == "" {
|
||||
t.Errorf("signed in: %d %s %q", code, at, in)
|
||||
}
|
||||
}
|
||||
@@ -627,7 +627,7 @@ func (s *Server) login(q *req) {
|
||||
q.redirect(back)
|
||||
return
|
||||
}
|
||||
form := map[string]any{"Back": back}
|
||||
form := map[string]any{"Back": back, "NTLM": s.ntlmOn()}
|
||||
if q.r.Method == http.MethodPost {
|
||||
name := strings.TrimSpace(q.r.PostForm.Get("name"))
|
||||
var secret string
|
||||
|
||||
@@ -16,5 +16,8 @@
|
||||
<label class="field"><span>Code</span><input type="text" name="code" placeholder="ABCD-EFGH" autocomplete="one-time-code" autocapitalize="characters" spellcheck="false" maxlength="12" required></label>
|
||||
<div class="editor-foot"><button class="button important">Sign In</button></div>
|
||||
</form>
|
||||
{{if $b.NTLM}}<div class="box-body signin">
|
||||
<p class="desc">Or, from MSN or Internet Explorer on Windows, without typing your password: <a href="/forum/login/ntlm?back={{$b.Back}}">sign in with your MSN password</a>.</p>
|
||||
</div>{{end}}
|
||||
</div>
|
||||
{{template "foot" .}}{{end}}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/D-Modem/bbs/internal/bbs"
|
||||
"github.com/D-Modem/bbs/internal/ntlm"
|
||||
"github.com/D-Modem/bbs/internal/store"
|
||||
)
|
||||
|
||||
@@ -93,8 +94,8 @@ func (l *logsrv) call(h hostBlock) ([]byte, bool) {
|
||||
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
|
||||
l.challenge = ntlm.NewChallenge()
|
||||
return reply{}.bytes_(wrapToken(ntlmTypeChallenge, ntlm.ChallengeMessage(l.flags, l.challenge, ""))), true
|
||||
case logNTLMAuth:
|
||||
result, ok := l.ntlmSignOn(ps)
|
||||
word := uint16(ntlmRefused)
|
||||
@@ -171,32 +172,15 @@ func (l *logsrv) ntlmSignOn(ps []param) (uint32, bool) {
|
||||
}
|
||||
challenge := l.challenge
|
||||
l.challenge = nil // one answer to each
|
||||
a, err := parseAuthenticate(t, l.flags)
|
||||
a, err := ntlm.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) {
|
||||
check := b.NTLMCheck("marvel", a, challenge, func(l, n []byte) { lm, nt = l, n })
|
||||
result := l.c.signOnBy(a.User, func(node *bbs.Node, name string) (*store.User, error) {
|
||||
if node != nil {
|
||||
return node.LoginWith(name, "NTLM", check)
|
||||
}
|
||||
@@ -205,7 +189,7 @@ func (l *logsrv) ntlmSignOn(ps []param) (uint32, bool) {
|
||||
if result != loginOK {
|
||||
return result, false
|
||||
}
|
||||
if l.seal, err = newSealer(a.flags, a.sessionKey(lm, nt, challenge)); err != nil {
|
||||
if l.seal, err = newSealer(a.Flags, a.SessionKey(lm, nt, challenge)); err != nil {
|
||||
l.c.logf("NTLM: %v", err)
|
||||
}
|
||||
return loginOK, true
|
||||
|
||||
+8
-142
@@ -2,19 +2,12 @@ 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"
|
||||
"github.com/D-Modem/bbs/internal/ntlm"
|
||||
)
|
||||
|
||||
// The 1996 client (Windows 95 OSR2, MSN 1.3) signs in with NTLM, on two
|
||||
@@ -29,23 +22,17 @@ import (
|
||||
// in a 256-byte slot.
|
||||
|
||||
const (
|
||||
ntlmTypeNegotiate = 1
|
||||
ntlmTypeChallenge = 2
|
||||
ntlmTypeAuthenticate = 3
|
||||
ntlmTypeNegotiate = ntlm.TypeNegotiate
|
||||
ntlmTypeChallenge = ntlm.TypeChallenge
|
||||
ntlmTypeAuthenticate = ntlm.TypeAuthenticate
|
||||
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
|
||||
sealTokenLen = 16
|
||||
)
|
||||
|
||||
var ntlmSig = []byte("NTLMSSP\x00")
|
||||
var ntlmSig = ntlm.Signature
|
||||
|
||||
// ntlmToken is the token in a method's 0x04 value.
|
||||
func ntlmToken(ps []param, want uint32) []byte {
|
||||
@@ -75,121 +62,6 @@ func wrapToken(typ uint16, t []byte) []byte {
|
||||
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
|
||||
@@ -200,11 +72,11 @@ type sealer struct {
|
||||
}
|
||||
|
||||
func newSealer(flags uint32, key []byte) (*sealer, error) {
|
||||
if flags&ntlmESS != 0 {
|
||||
if flags&ntlm.FlagESS != 0 {
|
||||
return nil, errors.New("extended session security's sealing isn't served")
|
||||
}
|
||||
var k []byte
|
||||
if flags&ntlm56 != 0 {
|
||||
if flags&ntlm.Flag56 != 0 {
|
||||
k = append(append([]byte(nil), key[:7]...), 0xA0)
|
||||
} else {
|
||||
k = append(append([]byte(nil), key[:5]...), 0xE5, 0x38, 0xB0)
|
||||
@@ -238,9 +110,3 @@ func (s *sealer) unseal(sealed, token []byte) ([]byte, bool) {
|
||||
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
|
||||
}
|
||||
@@ -3,28 +3,11 @@ package marvel
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"testing"
|
||||
|
||||
"github.com/D-Modem/bbs/internal/store"
|
||||
"github.com/D-Modem/bbs/internal/ntlm"
|
||||
)
|
||||
|
||||
// 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)
|
||||
@@ -88,13 +71,13 @@ func (c *client) ntlmLogin(t *testing.T, user, pw string) (uint32, uint32, *seal
|
||||
t.Fatalf("challenge token: %x", ch[:48])
|
||||
}
|
||||
challenge := ch[24:32]
|
||||
lmResp := desl(store.LMHash(pw), challenge)
|
||||
lmResp := ntlm.DESL(ntlm.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))
|
||||
a := &ntlm.Auth{Flags: osr2Flags, LM: lmResp}
|
||||
s, _ := newSealer(osr2Flags, a.SessionKey(ntlm.LMHash(pw), ntlm.NTHash(pw), challenge))
|
||||
return uint32(binary.LittleEndian.Uint16(r[1:])), binary.LittleEndian.Uint32(r[4:]), s
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
package nntp
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/D-Modem/bbs/internal/ntlm"
|
||||
)
|
||||
|
||||
// TestNTLM: AUTHINFO GENERIC NTLM, as Internet News signs in to an MSN
|
||||
// news server.
|
||||
func TestNTLM(t *testing.T) {
|
||||
s := newSite(t, "news.a.test", ServerSettings{Post: true, ReadUsers: true}, nil)
|
||||
cv := dialConv(t, s.addr)
|
||||
cv.send("AUTHINFO GENERIC")
|
||||
cv.expect("485") // not while the hashes aren't kept
|
||||
|
||||
st := s.b.Store
|
||||
st.SetKeepNTLM(true)
|
||||
alice, _ := st.UserByName("alice")
|
||||
st.SetPassword(alice.ID, "alicepass1")
|
||||
cv.send("AUTHINFO GENERIC")
|
||||
cv.expect("281")
|
||||
if got := cv.block(); got != "NTLM\r\nMSN\r\n" {
|
||||
t.Fatalf("mechanisms: %q", got)
|
||||
}
|
||||
login := func(mech, pw string) string {
|
||||
cv.send("AUTHINFO GENERIC " + mech)
|
||||
cv.expect("381")
|
||||
cv.send("AUTHINFO GENERIC " + base64.StdEncoding.EncodeToString(ntlm.ClientNegotiate(ntlm.FlagOEM|ntlm.FlagNTLM|ntlm.FlagRequestTarget)))
|
||||
ch, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(cv.expect("381 "), "381 "))
|
||||
if err != nil || ntlm.Type(ch) != ntlm.TypeChallenge {
|
||||
t.Fatalf("challenge: %x %v", ch, err)
|
||||
}
|
||||
cv.send("AUTHINFO GENERIC " + base64.StdEncoding.EncodeToString(
|
||||
ntlm.ClientAuthenticate(ntlm.FlagUnicode|ntlm.FlagNTLM, "", "alice", ntlm.DESL(ntlm.LMHash(pw), ch[24:32]), ntlm.DESL(ntlm.NTHash(pw), ch[24:32]))))
|
||||
return cv.expect("")
|
||||
}
|
||||
if got := login("NTLM", "wrong"); !strings.HasPrefix(got, "502") {
|
||||
t.Fatalf("a wrong password: %q", got)
|
||||
}
|
||||
if got := login("MSN", "alicepass1"); !strings.HasPrefix(got, "281") {
|
||||
t.Fatalf("login: %q", got)
|
||||
}
|
||||
cv.send("GROUP bbs.general")
|
||||
cv.expect("211")
|
||||
}
|
||||
+79
-6
@@ -5,6 +5,7 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -17,6 +18,7 @@ import (
|
||||
"github.com/D-Modem/bbs/internal/bbs"
|
||||
"github.com/D-Modem/bbs/internal/certs"
|
||||
"github.com/D-Modem/bbs/internal/news"
|
||||
"github.com/D-Modem/bbs/internal/ntlm"
|
||||
"github.com/D-Modem/bbs/internal/sockets"
|
||||
"github.com/D-Modem/bbs/internal/store"
|
||||
)
|
||||
@@ -163,7 +165,8 @@ type session struct {
|
||||
tls bool
|
||||
who string
|
||||
user *store.User
|
||||
name string // AUTHINFO USER, waiting for PASS
|
||||
name string // AUTHINFO USER, waiting for PASS
|
||||
ntlm *ntlm.SASL // AUTHINFO GENERIC NTLM, under way
|
||||
peer *Peer
|
||||
group *store.Area
|
||||
cur int64
|
||||
@@ -427,6 +430,10 @@ func (ss *session) starttls() {
|
||||
// (throttled, counted against the address unless it is loopback). Not before
|
||||
// STARTTLS if TLS is required.
|
||||
func (ss *session) authinfo(args []string) {
|
||||
if len(args) >= 1 && strings.EqualFold(args[0], "GENERIC") && ss.user == nil {
|
||||
ss.generic(args[1:])
|
||||
return
|
||||
}
|
||||
if len(args) < 2 {
|
||||
ss.reply(501, "AUTHINFO USER name, then AUTHINFO PASS password")
|
||||
return
|
||||
@@ -450,11 +457,7 @@ func (ss *session) authinfo(args []string) {
|
||||
}
|
||||
// a local client's address is everyone's: its failures count
|
||||
// against the account named
|
||||
source := bbs.LocalSource("nntp", ss.name)
|
||||
if a, ok := ss.c.RemoteAddr().(*net.TCPAddr); ok && !a.IP.IsLoopback() {
|
||||
source = "ip:" + a.IP.String()
|
||||
}
|
||||
u, err := ss.s.Svc.B.Authenticate(ss.who, source, ss.name, strings.Join(args[1:], " "))
|
||||
u, err := ss.s.Svc.B.Authenticate(ss.who, ss.source(ss.name), ss.name, strings.Join(args[1:], " "))
|
||||
ss.name = ""
|
||||
if err != nil {
|
||||
ss.reply(481, "Authentication failed")
|
||||
@@ -468,6 +471,76 @@ func (ss *session) authinfo(args []string) {
|
||||
}
|
||||
}
|
||||
|
||||
// source is where a login's failures count: a local client's address is
|
||||
// everyone's, so its count against the account named.
|
||||
func (ss *session) source(name string) string {
|
||||
if a, ok := ss.c.RemoteAddr().(*net.TCPAddr); ok && !a.IP.IsLoopback() {
|
||||
return "ip:" + a.IP.String()
|
||||
}
|
||||
return bbs.LocalSource("nntp", name)
|
||||
}
|
||||
|
||||
// generic answers AUTHINFO GENERIC, as MS-NNTP has it, with NTLM (or MSN,
|
||||
// MSN's name for it) while the BBS keeps the hashes it checks: alone, the
|
||||
// mechanisms; with one, 381 and an exchange of base64 messages, each
|
||||
// "AUTHINFO GENERIC <message>", ended 281 or 502.
|
||||
func (ss *session) generic(args []string) {
|
||||
b := ss.s.Svc.B
|
||||
if !b.NTLMOffered() {
|
||||
ss.ntlm = nil
|
||||
ss.reply(485, "No AUTHINFO GENERIC mechanisms here")
|
||||
return
|
||||
}
|
||||
if !ss.tls && ss.s.Set.TLS == TLSRequired {
|
||||
ss.reply(483, "Use STARTTLS first")
|
||||
return
|
||||
}
|
||||
switch {
|
||||
case len(args) == 0:
|
||||
ss.ntlm = nil
|
||||
ss.reply(281, "List of authenticators follows")
|
||||
ss.w.WriteString("NTLM\r\nMSN\r\n")
|
||||
ss.end()
|
||||
return
|
||||
case strings.EqualFold(args[0], "NTLM") || strings.EqualFold(args[0], "MSN"):
|
||||
ss.ntlm = &ntlm.SASL{Exchange: ntlm.Exchange{Target: "BBS"}, Login: func(a *ntlm.Auth, c []byte) error {
|
||||
u, err := b.AuthenticateNTLM(ss.who, ss.source(a.User), a, c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ss.user = u
|
||||
b.Log.Printf("%s: %s logged in by NTLM", ss.who, u.Name)
|
||||
return nil
|
||||
}}
|
||||
ss.reply(381, "Protocol supported, proceed")
|
||||
return
|
||||
case ss.ntlm == nil:
|
||||
ss.reply(485, "Only NTLM")
|
||||
return
|
||||
}
|
||||
in, err := base64.StdEncoding.DecodeString(args[0])
|
||||
if err != nil {
|
||||
ss.ntlm = nil
|
||||
ss.reply(501, "Not base64")
|
||||
return
|
||||
}
|
||||
out, done, err := ss.ntlm.Next(in)
|
||||
if done || err != nil {
|
||||
ss.ntlm = nil
|
||||
if err != nil || ss.user == nil {
|
||||
ss.reply(502, "Permission denied")
|
||||
return
|
||||
}
|
||||
ss.reply(281, "Authentication ok")
|
||||
return
|
||||
}
|
||||
if out == nil {
|
||||
ss.reply(381, "Protocol supported, proceed")
|
||||
return
|
||||
}
|
||||
ss.reply(381, base64.StdEncoding.EncodeToString(out))
|
||||
}
|
||||
|
||||
// groups are the newsgroups (areas that are) this reader may see
|
||||
func (ss *session) groups() []*store.Area {
|
||||
gs, err := ss.s.Svc.B.Store.Newsgroups()
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package ntlm
|
||||
|
||||
import "encoding/binary"
|
||||
|
||||
// ClientNegotiate is a client's NEGOTIATE with flags (for tests).
|
||||
func ClientNegotiate(flags uint32) []byte {
|
||||
b := append([]byte(nil), Signature...)
|
||||
b = binary.LittleEndian.AppendUint32(b, TypeNegotiate)
|
||||
b = binary.LittleEndian.AppendUint32(b, flags)
|
||||
return append(b, make([]byte, 16)...)
|
||||
}
|
||||
|
||||
// ClientAuthenticate is a client's AUTHENTICATE (the long header), in
|
||||
// Unicode (for tests).
|
||||
func ClientAuthenticate(flags uint32, domain, user string, lm, nt []byte) []byte {
|
||||
payload := [][]byte{lm, nt, utf16le(domain), utf16le(user), utf16le("WS")}
|
||||
b := append([]byte(nil), Signature...)
|
||||
b = binary.LittleEndian.AppendUint32(b, TypeAuthenticate)
|
||||
off := 64
|
||||
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)
|
||||
}
|
||||
b = append(b, 0, 0, 0, 0, 0, 0, 0, 0) // session key: none
|
||||
b = binary.LittleEndian.AppendUint32(b, flags)
|
||||
for _, p := range payload {
|
||||
b = append(b, p...)
|
||||
}
|
||||
return b
|
||||
}
|
||||
@@ -0,0 +1,390 @@
|
||||
// Package ntlm is the server's side of NTLM, as Microsoft's clients of the
|
||||
// 1990s spoke it: MSN's own security package (msnsspc, "Sicily") is NTLM
|
||||
// under another name, so MSN Classic's 1996 client, MSN 2.x's Program
|
||||
// Viewer, Outlook Express and Internet News all sign in by it. The
|
||||
// client proves the password with DES over the server's challenge, keyed
|
||||
// with the password's LM or NT hash, which the store keeps for it.
|
||||
package ntlm
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/des"
|
||||
"crypto/hmac"
|
||||
"crypto/md5"
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"strings"
|
||||
"unicode/utf16"
|
||||
|
||||
"golang.org/x/crypto/md4"
|
||||
"golang.org/x/text/encoding/charmap"
|
||||
)
|
||||
|
||||
// Message types.
|
||||
const (
|
||||
TypeNegotiate = 1
|
||||
TypeChallenge = 2
|
||||
TypeAuthenticate = 3
|
||||
)
|
||||
|
||||
// Flags.
|
||||
const (
|
||||
FlagUnicode = 0x00000001
|
||||
FlagOEM = 0x00000002
|
||||
FlagRequestTarget = 0x00000004
|
||||
FlagSign = 0x00000010
|
||||
FlagSeal = 0x00000020
|
||||
FlagLMKey = 0x00000080
|
||||
FlagNTLM = 0x00000200
|
||||
FlagAlwaysSign = 0x00008000
|
||||
FlagTargetDomain = 0x00010000
|
||||
FlagESS = 0x00080000 // extended session security
|
||||
FlagNonNTKey = 0x00400000
|
||||
FlagTargetInfo = 0x00800000
|
||||
Flag128 = 0x20000000
|
||||
FlagKeyExchange = 0x40000000
|
||||
Flag56 = 0x80000000
|
||||
)
|
||||
|
||||
// Signature begins every message.
|
||||
var Signature = []byte("NTLMSSP\x00")
|
||||
|
||||
// Type is a message's type, or 0 if it isn't one.
|
||||
func Type(t []byte) uint32 {
|
||||
if len(t) < 12 || !bytes.Equal(t[:8], Signature) {
|
||||
return 0
|
||||
}
|
||||
return binary.LittleEndian.Uint32(t[8:])
|
||||
}
|
||||
|
||||
// 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()
|
||||
h.Write(utf16le(pw))
|
||||
return h.Sum(nil)
|
||||
}
|
||||
|
||||
func utf16le(s string) []byte {
|
||||
var b []byte
|
||||
for _, u := range utf16.Encode([]rune(s)) {
|
||||
b = append(b, byte(u), byte(u>>8))
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// 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(DESKey(key[i*7 : i*7+7]))
|
||||
b.Encrypt(out[i*8:], c)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func desEncrypt(k7, c []byte) []byte {
|
||||
b, _ := des.NewCipher(DESKey(k7))
|
||||
out := make([]byte, 8)
|
||||
b.Encrypt(out, c)
|
||||
return out
|
||||
}
|
||||
|
||||
// NewChallenge is a server challenge.
|
||||
func NewChallenge() []byte {
|
||||
c := make([]byte, 8)
|
||||
rand.Read(c)
|
||||
return c
|
||||
}
|
||||
|
||||
// NegotiateFlags are a NEGOTIATE's flags.
|
||||
func NegotiateFlags(t []byte) (uint32, error) {
|
||||
if Type(t) != TypeNegotiate || len(t) < 16 {
|
||||
return 0, errors.New("not an NTLM NEGOTIATE")
|
||||
}
|
||||
return binary.LittleEndian.Uint32(t[12:]), nil
|
||||
}
|
||||
|
||||
// Answer is the flags a server gives back to a client's: the client's
|
||||
// character set, NTLM, and what it asked for of extended session
|
||||
// security, signing and key strength.
|
||||
func Answer(asked uint32, target string) uint32 {
|
||||
f := uint32(FlagNTLM | FlagAlwaysSign)
|
||||
if asked&FlagUnicode != 0 {
|
||||
f |= FlagUnicode
|
||||
} else {
|
||||
f |= FlagOEM
|
||||
}
|
||||
f |= asked & (FlagESS | FlagSign | FlagSeal | Flag128 | Flag56 | FlagRequestTarget)
|
||||
if f&FlagESS == 0 {
|
||||
f |= asked & FlagLMKey
|
||||
}
|
||||
if target != "" && asked&FlagRequestTarget != 0 {
|
||||
f |= FlagTargetDomain | FlagTargetInfo
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
// ChallengeMessage is a CHALLENGE with flags: with the target's name and
|
||||
// target information when target is given, else with neither (as MSN
|
||||
// Classic's client expects).
|
||||
func ChallengeMessage(flags uint32, challenge []byte, target string) []byte {
|
||||
var name, info []byte
|
||||
if target != "" && flags&FlagTargetInfo != 0 {
|
||||
name = []byte(strings.ToUpper(target))
|
||||
if flags&FlagUnicode != 0 {
|
||||
name = utf16le(strings.ToUpper(target))
|
||||
}
|
||||
av := func(id uint16, v []byte) []byte {
|
||||
b := binary.LittleEndian.AppendUint16(nil, id)
|
||||
b = binary.LittleEndian.AppendUint16(b, uint16(len(v)))
|
||||
return append(b, v...)
|
||||
}
|
||||
u := utf16le(strings.ToUpper(target))
|
||||
info = append(append(av(2, u), av(1, u)...), 0, 0, 0, 0) // domain, server, end
|
||||
}
|
||||
const head = 48
|
||||
field := func(b []byte, v []byte, off int) []byte {
|
||||
b = binary.LittleEndian.AppendUint16(b, uint16(len(v)))
|
||||
b = binary.LittleEndian.AppendUint16(b, uint16(len(v)))
|
||||
return binary.LittleEndian.AppendUint32(b, uint32(off))
|
||||
}
|
||||
b := append([]byte(nil), Signature...)
|
||||
b = binary.LittleEndian.AppendUint32(b, TypeChallenge)
|
||||
b = field(b, name, head)
|
||||
b = binary.LittleEndian.AppendUint32(b, flags)
|
||||
b = append(b, challenge...)
|
||||
b = append(b, make([]byte, 8)...) // reserved
|
||||
b = field(b, info, head+len(name))
|
||||
return append(append(b, name...), info...)
|
||||
}
|
||||
|
||||
// Auth is an AUTHENTICATE read.
|
||||
type Auth struct {
|
||||
Flags uint32
|
||||
User, Domain, Workstation string
|
||||
LM, NT []byte
|
||||
}
|
||||
|
||||
// ParseAuthenticate reads an AUTHENTICATE. MSN Classic's 1996 client's
|
||||
// header stops after the workstation's field (52 bytes, with no flags of
|
||||
// its own), so the flags come from the message only when its data starts
|
||||
// past the long header; else they are those negotiated.
|
||||
func ParseAuthenticate(t []byte, negotiated uint32) (*Auth, error) {
|
||||
if Type(t) != TypeAuthenticate || len(t) < 52 {
|
||||
return nil, errors.New("not an NTLM AUTHENTICATE")
|
||||
}
|
||||
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 := &Auth{Flags: negotiated, LM: fields[0], NT: fields[1]}
|
||||
if start >= 64 {
|
||||
a.Flags = binary.LittleEndian.Uint32(t[60:])
|
||||
}
|
||||
text := func(b []byte) string {
|
||||
if a.Flags&FlagUnicode != 0 {
|
||||
u := make([]uint16, len(b)/2)
|
||||
for i := range u {
|
||||
u[i] = binary.LittleEndian.Uint16(b[2*i:])
|
||||
}
|
||||
return string(utf16.Decode(u))
|
||||
}
|
||||
s, err := charmap.Windows1252.NewDecoder().Bytes(b)
|
||||
if err != nil {
|
||||
return string(b)
|
||||
}
|
||||
return string(s)
|
||||
}
|
||||
a.Domain, a.User, a.Workstation = text(fields[2]), text(fields[3]), text(fields[4])
|
||||
return a, nil
|
||||
}
|
||||
|
||||
// Anonymous reports whether the AUTHENTICATE names no one.
|
||||
func (a *Auth) Anonymous() bool { return a.User == "" && len(a.NT) == 0 && len(a.LM) <= 1 }
|
||||
|
||||
func (a *Auth) ess() bool {
|
||||
return a.Flags&FlagESS != 0 && len(a.LM) == 24 && len(a.NT) == 24 && bytes.Equal(a.LM[8:], make([]byte, 16))
|
||||
}
|
||||
|
||||
// Verify checks the responses against the password's hashes: NTLMv2 if
|
||||
// the NT response is longer than v1's, else NTLMv1 (with extended session
|
||||
// security if it's that), by the NT response if there is one, else the LM.
|
||||
func (a *Auth) Verify(lm, nt, challenge []byte) bool {
|
||||
eq := func(x, y []byte) bool { return subtle.ConstantTimeCompare(x, y) == 1 }
|
||||
switch {
|
||||
case len(a.NT) > 24:
|
||||
for _, k := range a.v2Keys(nt) {
|
||||
m := hmac.New(md5.New, k)
|
||||
m.Write(challenge)
|
||||
m.Write(a.NT[16:])
|
||||
if eq(m.Sum(nil), a.NT[:16]) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
case a.ess():
|
||||
h := md5.Sum(append(append([]byte(nil), challenge...), a.LM[:8]...))
|
||||
return eq(a.NT, DESL(nt, h[:8]))
|
||||
case len(a.NT) == 24:
|
||||
return eq(a.NT, DESL(nt, challenge))
|
||||
case len(a.LM) == 24:
|
||||
if eq(a.LM, DESL(lm, challenge)) {
|
||||
return true
|
||||
}
|
||||
for _, k := range a.v2Keys(nt) { // LMv2 alone
|
||||
m := hmac.New(md5.New, k)
|
||||
m.Write(challenge)
|
||||
m.Write(a.LM[16:])
|
||||
if eq(m.Sum(nil), a.LM[:16]) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// v2Keys are NTOWFv2's for the name and domain as sent, and with no
|
||||
// domain (clients differ on which they use).
|
||||
func (a *Auth) v2Keys(nt []byte) [][]byte {
|
||||
var out [][]byte
|
||||
for _, d := range []string{a.Domain, ""} {
|
||||
m := hmac.New(md5.New, nt)
|
||||
m.Write(utf16le(strings.ToUpper(a.User) + d))
|
||||
out = append(out, m.Sum(nil))
|
||||
if a.Domain == "" {
|
||||
break
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// SessionKey is the NTLMv1 key an accepted exchange leaves, with no key
|
||||
// exchange (MSN Classic's short AUTHENTICATE has no room for one).
|
||||
func (a *Auth) SessionKey(lm, nt, challenge []byte) []byte {
|
||||
h := md4.New()
|
||||
h.Write(nt)
|
||||
base := h.Sum(nil)
|
||||
switch {
|
||||
case a.Flags&FlagESS != 0 && len(a.LM) >= 8:
|
||||
m := hmac.New(md5.New, base)
|
||||
m.Write(challenge)
|
||||
m.Write(a.LM[:8])
|
||||
return m.Sum(nil)
|
||||
case a.Flags&FlagLMKey != 0 && len(a.LM) >= 8:
|
||||
k := desEncrypt(lm[:7], a.LM[:8])
|
||||
return append(k, desEncrypt(append([]byte{lm[7]}, 0xBD, 0xBD, 0xBD, 0xBD, 0xBD, 0xBD), a.LM[:8])...)
|
||||
case a.Flags&FlagNonNTKey != 0:
|
||||
return append(append([]byte(nil), lm[:8]...), make([]byte, 8)...)
|
||||
}
|
||||
return base
|
||||
}
|
||||
|
||||
// Exchange is one sign-in's server side: a NEGOTIATE in, a CHALLENGE out,
|
||||
// then the AUTHENTICATE.
|
||||
type Exchange struct {
|
||||
Target string // the CHALLENGE's domain, if any
|
||||
flags uint32
|
||||
challenge []byte
|
||||
}
|
||||
|
||||
// Challenge answers a NEGOTIATE.
|
||||
func (x *Exchange) Challenge(negotiate []byte) ([]byte, error) {
|
||||
asked, err := NegotiateFlags(negotiate)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
x.flags = Answer(asked, x.Target)
|
||||
x.challenge = NewChallenge()
|
||||
return ChallengeMessage(x.flags, x.challenge, x.Target), nil
|
||||
}
|
||||
|
||||
// Authenticate reads the AUTHENTICATE that answers the challenge, and
|
||||
// gives the challenge it answers. There is one answer to each.
|
||||
func (x *Exchange) Authenticate(t []byte) (*Auth, []byte, error) {
|
||||
if x.challenge == nil {
|
||||
return nil, nil, errors.New("an AUTHENTICATE before a CHALLENGE")
|
||||
}
|
||||
c := x.challenge
|
||||
x.challenge = nil
|
||||
a, err := ParseAuthenticate(t, x.flags)
|
||||
return a, c, err
|
||||
}
|
||||
|
||||
// SASL is the exchange as a SASL mechanism's server (NTLM, or MSN by
|
||||
// MSN's name for it): Next takes the NEGOTIATE (asking for it if the
|
||||
// client began with nothing), then the AUTHENTICATE, which Login checks.
|
||||
type SASL struct {
|
||||
Exchange
|
||||
Login func(a *Auth, challenge []byte) error
|
||||
step int
|
||||
}
|
||||
|
||||
// ErrFailed is a sign-in that isn't accepted.
|
||||
var ErrFailed = errors.New("NTLM: not accepted")
|
||||
|
||||
func (s *SASL) Next(response []byte) (challenge []byte, done bool, err error) {
|
||||
switch s.step {
|
||||
case 0:
|
||||
if len(response) == 0 {
|
||||
return nil, false, nil
|
||||
}
|
||||
s.step = 1
|
||||
c, err := s.Challenge(response)
|
||||
if err != nil {
|
||||
return nil, true, err
|
||||
}
|
||||
return c, false, nil
|
||||
case 1:
|
||||
s.step = 2
|
||||
a, c, err := s.Authenticate(response)
|
||||
if err != nil {
|
||||
return nil, true, err
|
||||
}
|
||||
return nil, true, s.Login(a, c)
|
||||
}
|
||||
return nil, true, ErrFailed
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package ntlm
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func unhex(s string) []byte {
|
||||
b, err := hex.DecodeString(s)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// MS-NLMP 4.2: the password "Password", user "User", domain "Domain", the
|
||||
// server challenge 0123456789abcdef and the client's aaaaaaaaaaaaaaaa.
|
||||
var (
|
||||
pw = "Password"
|
||||
challenge = unhex("0123456789abcdef")
|
||||
client = unhex("aaaaaaaaaaaaaaaa")
|
||||
)
|
||||
|
||||
func TestV1(t *testing.T) {
|
||||
lm, nt := LMHash(pw), NTHash(pw)
|
||||
if got := hex.EncodeToString(DESL(lm, challenge)); got != "98def7b87f88aa5dafe2df779688a172def11c7d5ccdef13" {
|
||||
t.Errorf("LM response: %s", got)
|
||||
}
|
||||
ntResp := DESL(nt, challenge)
|
||||
if got := hex.EncodeToString(ntResp); got != "67c43011f30298a2ad35ece64f16331c44bdbed927841f94" {
|
||||
t.Errorf("NT response: %s", got)
|
||||
}
|
||||
a := &Auth{User: "User", NT: ntResp, LM: DESL(lm, challenge)}
|
||||
if !a.Verify(lm, nt, challenge) {
|
||||
t.Error("v1 not accepted")
|
||||
}
|
||||
if a.Verify(LMHash("other"), NTHash("other"), challenge) {
|
||||
t.Error("v1 with the wrong password accepted")
|
||||
}
|
||||
if got := hex.EncodeToString(a.SessionKey(lm, nt, challenge)); got != "d87262b0cde4b1cb7499becccdf10784" {
|
||||
t.Errorf("session base key: %s", got)
|
||||
}
|
||||
// LM alone, as MSN Classic's 1996 client sends it
|
||||
if !(&Auth{LM: DESL(lm, challenge)}).Verify(lm, nt, challenge) {
|
||||
t.Error("LM alone not accepted")
|
||||
}
|
||||
}
|
||||
|
||||
// 4.2.3: NTLMv1 with extended session security.
|
||||
func TestESS(t *testing.T) {
|
||||
a := &Auth{Flags: FlagESS, User: "User", LM: append(append([]byte(nil), client...), make([]byte, 16)...),
|
||||
NT: unhex("7537f803ae367128ca458204bde7caf81e97ed2683267232")}
|
||||
if !a.Verify(LMHash(pw), NTHash(pw), challenge) {
|
||||
t.Error("ESS not accepted")
|
||||
}
|
||||
if a.Verify(LMHash(pw), NTHash("other"), challenge) {
|
||||
t.Error("ESS with the wrong password accepted")
|
||||
}
|
||||
}
|
||||
|
||||
// 4.2.4: NTLMv2.
|
||||
func TestV2(t *testing.T) {
|
||||
av := func(id uint16, s string) []byte {
|
||||
v := utf16le(s)
|
||||
b := binary.LittleEndian.AppendUint16(nil, id)
|
||||
b = binary.LittleEndian.AppendUint16(b, uint16(len(v)))
|
||||
return append(b, v...)
|
||||
}
|
||||
info := append(append(av(2, "Domain"), av(1, "Server")...), 0, 0, 0, 0)
|
||||
temp := append([]byte{1, 1, 0, 0, 0, 0, 0, 0}, make([]byte, 8)...) // time 0
|
||||
temp = append(append(append(temp, client...), 0, 0, 0, 0), info...)
|
||||
temp = append(temp, 0, 0, 0, 0)
|
||||
a := &Auth{User: "User", Domain: "Domain",
|
||||
NT: append(unhex("68cd0ab851e51c96aabc927bebef6a1c"), temp...)}
|
||||
if !a.Verify(nil, NTHash(pw), challenge) {
|
||||
t.Error("v2 not accepted")
|
||||
}
|
||||
if a.Verify(nil, NTHash("other"), challenge) {
|
||||
t.Error("v2 with the wrong password accepted")
|
||||
}
|
||||
lmv2 := &Auth{User: "User", Domain: "Domain", LM: append(unhex("86c35097ac9cec102554764a57cccc19"), client...)}
|
||||
if !lmv2.Verify(LMHash(pw), NTHash(pw), challenge) {
|
||||
t.Error("LMv2 not accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSASL(t *testing.T) {
|
||||
var got *Auth
|
||||
s := &SASL{Exchange: Exchange{Target: "BBS"}, Login: func(a *Auth, c []byte) error {
|
||||
if !a.Verify(LMHash(pw), NTHash(pw), c) {
|
||||
return ErrFailed
|
||||
}
|
||||
got = a
|
||||
return nil
|
||||
}}
|
||||
if c, done, err := s.Next(nil); c != nil || done || err != nil {
|
||||
t.Fatalf("first: %x %v %v", c, done, err)
|
||||
}
|
||||
c, done, err := s.Next(ClientNegotiate(FlagUnicode | FlagNTLM | FlagRequestTarget))
|
||||
if err != nil || done || Type(c) != TypeChallenge {
|
||||
t.Fatalf("challenge: %x %v %v", c, done, err)
|
||||
}
|
||||
flags := binary.LittleEndian.Uint32(c[20:])
|
||||
if flags&FlagUnicode == 0 || flags&FlagTargetInfo == 0 {
|
||||
t.Fatalf("flags %#x", flags)
|
||||
}
|
||||
n, off := binary.LittleEndian.Uint16(c[12:]), binary.LittleEndian.Uint32(c[16:])
|
||||
if !bytes.Equal(c[off:off+uint32(n)], utf16le("BBS")) {
|
||||
t.Fatalf("target name: %x", c[off:off+uint32(n)])
|
||||
}
|
||||
ch := c[24:32]
|
||||
if _, done, err := s.Next(ClientAuthenticate(flags, "BBS", "alice", nil, DESL(NTHash(pw), ch))); !done || err != nil {
|
||||
t.Fatalf("authenticate: %v %v", done, err)
|
||||
}
|
||||
if got == nil || got.User != "alice" || got.Domain != "BBS" || got.Workstation != "WS" {
|
||||
t.Fatalf("auth: %+v", got)
|
||||
}
|
||||
// the challenge answers once
|
||||
s = &SASL{Login: func(a *Auth, c []byte) error { return nil }}
|
||||
s.Next(ClientNegotiate(FlagOEM | FlagNTLM))
|
||||
s.Next(ClientAuthenticate(0, "", "x", nil, nil))
|
||||
if _, _, err := s.Next(nil); err == nil {
|
||||
t.Fatal("a third step accepted")
|
||||
}
|
||||
}
|
||||
@@ -101,6 +101,7 @@ type Config struct {
|
||||
Listeners []*Listener
|
||||
Warnings []string
|
||||
Guard *guard.Guard // [security]
|
||||
KeepNTLM bool // [security] ntlm: keep the hashes NTLM sign-ins check
|
||||
RunAs *sockets.Account // [general] user and group: who serve becomes, its ports bound (nil: as it is started)
|
||||
MenuAuth *MenuAuth // [modemmenu]: passwords asked of modemmenu (nil: none)
|
||||
Events []*events.Event
|
||||
@@ -516,6 +517,9 @@ func (c *Config) securitySection(sec *config.Section) error {
|
||||
return err
|
||||
}
|
||||
g.BanTime = time.Duration(mins) * time.Minute
|
||||
if c.KeepNTLM, err = sec.Bool("ntlm", false); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, w := range g.Check() {
|
||||
c.Warnings = append(c.Warnings, "[security] "+w)
|
||||
}
|
||||
|
||||
@@ -5,6 +5,8 @@ import (
|
||||
"encoding/hex"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/D-Modem/bbs/internal/ntlm"
|
||||
)
|
||||
|
||||
// TestMSNKeys: digests kept only when asked, made at a password's check,
|
||||
@@ -110,10 +112,10 @@ func TestAddressBook(t *testing.T) {
|
||||
|
||||
func TestNTLMKeys(t *testing.T) {
|
||||
// the hashes of "password", as every NTLM write-up gives them
|
||||
if got := hex.EncodeToString(LMHash("password")); got != "e52cac67419a9a224a3b108f3fa6cb6d" {
|
||||
if got := hex.EncodeToString(ntlm.LMHash("password")); got != "e52cac67419a9a224a3b108f3fa6cb6d" {
|
||||
t.Errorf("LM: %s", got)
|
||||
}
|
||||
if got := hex.EncodeToString(NTHash("password")); got != "8846f7eaee8fb117ad06bdd830b7586c" {
|
||||
if got := hex.EncodeToString(ntlm.NTHash("password")); got != "8846f7eaee8fb117ad06bdd830b7586c" {
|
||||
t.Errorf("NT: %s", got)
|
||||
}
|
||||
BcryptCost = 4
|
||||
@@ -129,7 +131,7 @@ func TestNTLMKeys(t *testing.T) {
|
||||
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")) {
|
||||
if err != nil || !ok || !bytes.Equal(lm, ntlm.LMHash("password")) || !bytes.Equal(nt, ntlm.NTHash("password")) {
|
||||
t.Fatalf("kept: %x %x %v %v", lm, nt, ok, err)
|
||||
}
|
||||
// a password changed where it isn't seen leaves them stale
|
||||
@@ -138,7 +140,7 @@ func TestNTLMKeys(t *testing.T) {
|
||||
t.Fatal("stale hashes used")
|
||||
}
|
||||
s.SetPassword(u.ID, "another1")
|
||||
if lm, _, ok, _ := s.NTLMKey(u.ID); !ok || !bytes.Equal(lm, LMHash("another1")) {
|
||||
if lm, _, ok, _ := s.NTLMKey(u.ID); !ok || !bytes.Equal(lm, ntlm.LMHash("another1")) {
|
||||
t.Fatal("not kept on a new password")
|
||||
}
|
||||
}
|
||||
+12
-50
@@ -1,67 +1,29 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"crypto/des"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"strings"
|
||||
"unicode/utf16"
|
||||
|
||||
"golang.org/x/crypto/md4"
|
||||
"golang.org/x/text/encoding/charmap"
|
||||
"github.com/D-Modem/bbs/internal/ntlm"
|
||||
)
|
||||
|
||||
// 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
|
||||
// MSN's clients from 1996 on (MSN Classic's on Windows 95 OSR2, and MSN
|
||||
// 2.x's Program Viewer, mail and news) sign 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.
|
||||
// an MSN Classic front end or [security] ntlm 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.
|
||||
// SetKeepNTLM says whether to keep the hashes: only when asked, as they
|
||||
// would let anyone who read the database sign in by them.
|
||||
func (s *Store) SetKeepNTLM(on bool) { s.keepNTLM.Store(on) }
|
||||
|
||||
// KeepsNTLM reports whether the hashes are kept, and so whether NTLM
|
||||
// sign-ins can be offered.
|
||||
func (s *Store) KeepsNTLM() bool { return s.keepNTLM.Load() }
|
||||
|
||||
// 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
|
||||
@@ -89,7 +51,7 @@ func (s *Store) KeepNTLMKey(id int64, pw string) error {
|
||||
}
|
||||
return err
|
||||
}
|
||||
lm, nt := LMHash(pw), NTHash(pw)
|
||||
lm, nt := ntlm.LMHash(pw), ntlm.NTHash(pw)
|
||||
if ol, on, ok, err := s.NTLMKey(id); err == nil && ok && string(ol) == string(lm) && string(on) == string(nt) {
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user