diff --git a/bbs.conf.sample b/bbs.conf.sample index 2c1d562..aca1dee 100644 --- a/bbs.conf.sample +++ b/bbs.conf.sample @@ -844,6 +844,15 @@ address = 127.0.0.1:2513 ;uin_base = 100000 ; the screen name the BBS's notices come from ;system = OnlineHost +; The later AIM logins (AIM 6.2 to 7.x, and clientLogin: Pidgin, AIM +; Express, the phones' AIM) come by HTTP on address, or by TLS here, with +; tls_cert and tls_key (a certificate for the name clients use) +;tls_address = :443 +;tls_cert = /etc/bbs/aim.crt +;tls_key = /etc/bbs/aim.key +; where clients that ask for TLS are sent, host:port (default: host's host +; at tls_address's port); a TLS proxy's, when one is in front +;tls_host = aim.example.org:443 ; IRC server linking: the BBS as a hub server on an IRC network, by TS6 ; (Solanum, charybdis, ircd-ratbox; ircd-hybrid 8 with protocol = hybrid) diff --git a/cmd/bbs/main.go b/cmd/bbs/main.go index a913351..ab05183 100644 --- a/cmd/bbs/main.go +++ b/cmd/bbs/main.go @@ -315,6 +315,9 @@ func main() { } if o := cfg.OSCAR; o != nil { fmt.Printf("oscar: %q, reconnect at %q, ICQ numbers from %d\n", o.Address, o.Host, o.UINBase) + if o.TLSAddress != "" { + fmt.Printf("oscar: TLS on %q, clients asking for TLS sent to %q\n", o.TLSAddress, o.TLSHost) + } } if a := cfg.AOL; a != nil { fmt.Printf("aol: %q\n", a.Address) diff --git a/docs/wiki/AIM-and-ICQ.md b/docs/wiki/AIM-and-ICQ.md index 64ff14c..36648a1 100644 --- a/docs/wiki/AIM-and-ICQ.md +++ b/docs/wiki/AIM-and-ICQ.md @@ -1,7 +1,7 @@ The BBS has an AIM and ICQ server (OSCAR, the protocol AOL's AIM and ICQ clients spoke), beside its [IRC](IRC) server and on the same chat. Someone -signed on in AIM 5, AIM 4, ICQ 2003, Pidgin, Miranda or any other OSCAR -client sees the BBS's users on their buddy list, IMs them and talks in its +signed on in AIM 7, AIM 5, AIM 4, ICQ 2003, Pidgin, Miranda or any other +OSCAR client sees the BBS's users on their buddy list, IMs them and talks in its [chat rooms](Chat-and-Paging), with callers on telnet, SSH, 3270s, IRC, the web terminal and the API. @@ -19,13 +19,16 @@ host = aim.example.org:5190 | `max_per_ip` | `16` | from one address (each client opens a few) | | `uin_base` | `100000` | an account's ICQ number is this plus its number | | `system` | `OnlineHost` | the screen name the BBS's notices come from | +| `tls_address` | none | a TLS port for the [later logins](#later-aim-versions), e.g. `:443` | +| `tls_cert`, `tls_key` | none | its certificate and key (`tls_cert = acme` for the `[acme]` one) | +| `tls_host` | `host`'s name at `tls_address`'s port | where clients that ask for TLS are sent (`host:port`); a TLS proxy's, when one is in front | -Point the client at the BBS: in AIM, the "Host" under Connection settings -(`login.oscar.aol.com` was AOL's, so a hosts file entry also works); in -Pidgin, the server and port of an AIM or ICQ account, with "Use clientLogin" -unticked and encryption off (clientLogin and SSL were AOL's later web -sign-on, which this server does not serve, nor AIM 6's). The deny list and -bans in `[security]` apply as they do everywhere else. +Point the client at the BBS: in AIM up to 6.1, the "Host" under Connection +settings (`login.oscar.aol.com` was AOL's, so a hosts file entry also +works); in Pidgin, the server and port of an AIM or ICQ account, with "Use +clientLogin" unticked and encryption off, or see [later AIM +versions](#later-aim-versions) to use clientLogin. The deny list and bans in +`[security]` apply as they do everywhere else. ## Signing on @@ -88,6 +91,69 @@ name is made a room's: lower case, spaces as dashes, at most 20 letters and digits (`Test Room` is `test-room`). Inviting a buddy who isn't on AIM sends them a line naming the room. +## Later AIM versions + +AOL's later clients sign on by HTTP before they reach the server proper, +and the BBS serves both ways they do it, on port 5190 itself (a +connection that starts as an HTTP request is told apart by its first +byte) and on `tls_address`: + +- **AIM 6.2 to 7.5** post a Kerberos-style login to `/`. Set the client's + host and port under Settings, Connection, to the BBS's TLS address + (they ask for HTTPS and then a TLS connection, so `tls_address` or a + proxy is needed). The client checks the certificate against its own + store (an NSS database in its folder), so a certificate from a public + CA, or the BBS's own added there, is needed. +- **AIM 6.0 and 6.1** can't be set to another server for this login; set + their `serviceManifest.xml` to the old (BUCP) login and they sign on as + AIM 5 does. +- **Pidgin with "Use clientLogin"**, AIM Express and the phones' AIM ask + `api.screenname.aol.com` (`/auth/clientLogin`) and then + `api.oscar.aol.com` (`/aim/startOSCARSession`). Point those names at the + BBS in the hosts file; by HTTPS they need a certificate for those names + that the client trusts. Either way the client then signs on to the host + the BBS names, by TLS if it asked for it ("Use SSL") and there is a + TLS host. + +These logins send the password itself (inside TLS), so they work for any +account, without the AIM digests above. + +Wrong passwords count against the throttle and the hack log as any other +login does. The session secret clientLogin gives isn't used to check +the requests that follow; the token is a one-time sign-on cookie good for +five minutes. + +### AIM 6.2 and later, and TLS + +AIM 6.2 to 7.5 open TLS with an SSL 2.0-style hello, which Go's TLS (and +so `tls_address`) can't read; they need a TLS proxy in front, linked +against an OpenSSL that still takes it (1.0.2 or older: stunnel or nginx +built with it), with TLS 1.0 and the old ciphers on. Have it pass the +plain connection to port 5190 and set `tls_host` to the proxy's address: + +```ini +[oscar] +address = :5190 +host = aim.example.org:5190 +tls_host = aim.example.org:443 +``` + +``` +; stunnel, against OpenSSL 1.0.2 +[aim] +accept = 443 +connect = 127.0.0.1:5190 +cert = /etc/bbs/aim.pem +sslVersion = all +ciphers = ALL +``` + +Behind the proxy every client comes from the proxy's address, so +`max_per_ip`, the login throttle and bans see that one address; raise +`max_per_ip` to suit. `tls_address` on its own serves clients with modern +TLS, such as Pidgin. +A chat room asked for by TLS is sent to the TLS host too. + ## Port 5190 and AOL 5190 was AOL's own port before it was AIM's. A connection that begins as diff --git a/docs/wiki/Configuration-Reference.md b/docs/wiki/Configuration-Reference.md index 01db591..744ddc6 100644 --- a/docs/wiki/Configuration-Reference.md +++ b/docs/wiki/Configuration-Reference.md @@ -590,6 +590,10 @@ AIM and ICQ: the chat for AIM and ICQ clients (OSCAR), beside IRC. Users sign o | `max_per_ip` | | | each client opens a few connections: sign-on, the BOS, chat rooms. Examples: `16`. | | `uin_base` | | | an account's ICQ number is this plus its number. Examples: `100000`. | | `system` | | | the screen name the BBS's notices come from. Examples: `OnlineHost`. | +| `tls_address` | | | The later AIM logins (AIM 6.2 to 7.x, and clientLogin: Pidgin, AIM Express, the phones' AIM) come by HTTP on address, or by TLS here, with tls_cert and tls_key (a certificate for the name clients use) Examples: `:443`. | +| `tls_cert` | | | The later AIM logins (AIM 6.2 to 7.x, and clientLogin: Pidgin, AIM Express, the phones' AIM) come by HTTP on address, or by TLS here, with tls_cert and tls_key (a certificate for the name clients use) Examples: `/etc/bbs/aim.crt`. | +| `tls_key` | | | The later AIM logins (AIM 6.2 to 7.x, and clientLogin: Pidgin, AIM Express, the phones' AIM) come by HTTP on address, or by TLS here, with tls_cert and tls_key (a certificate for the name clients use) Examples: `/etc/bbs/aim.key`. | +| `tls_host` | | | where clients that ask for TLS are sent, host:port (default: host's host at tls_address's port); a TLS proxy's, when one is in front. Examples: `aim.example.org:443`. | ## `[irclink]` diff --git a/internal/oscar/oscar_test.go b/internal/oscar/oscar_test.go index 8974964..6cf09b2 100644 --- a/internal/oscar/oscar_test.go +++ b/internal/oscar/oscar_test.go @@ -57,7 +57,7 @@ func freeAddr(t *testing.T) string { // start is a BBS (alice, bob, Carol Ann and sysop, all password1; old, // made before AIM digests were kept) with OSCAR and IRC servers. -func start(t *testing.T) *env { +func start(t *testing.T, opts ...func(*Settings)) *env { t.Helper() store.BcryptCost = 4 st, err := store.Open(filepath.Join(t.TempDir(), "bbs.db")) @@ -83,7 +83,11 @@ func start(t *testing.T) *env { b := bbs.New(s, st, log.New(logs, "", 0)) e := &env{b: b, logs: logs, p3: make(chan []byte, 1)} e.addr = freeAddr(t) - srv, err := New(b, Settings{Address: e.addr, MaxPerIP: 50}) + set := Settings{Address: e.addr, MaxPerIP: 50} + for _, o := range opts { + o(&set) + } + srv, err := New(b, set) if err != nil { t.Fatal(err) } @@ -110,7 +114,11 @@ func start(t *testing.T) *env { t.Log("log:\n" + logs.String()) } }) - for _, a := range []string{e.addr, e.ircAddr} { + waitFor := []string{e.addr, e.ircAddr} + if set.TLSAddress != "" { + waitFor = append(waitFor, set.TLSAddress) + } + for _, a := range waitFor { for i := 0; ; i++ { if c, err := net.Dial("tcp", a); err == nil { c.Close() @@ -143,6 +151,12 @@ func dialWait(t *testing.T, addr string, hello tlvs, wait bool) *client { if err != nil { t.Fatal(err) } + return clientOn(t, c, hello, wait) +} + +// clientOn is dialWait on a connection made. +func clientOn(t *testing.T, c net.Conn, hello tlvs, wait bool) *client { + t.Helper() t.Cleanup(func() { c.Close() }) cl := &client{t: t, c: c, fc: newFlapConn(c, bufio.NewReader(c))} if !wait { @@ -253,7 +267,12 @@ func bos(t *testing.T, host string, ck []byte, buddies ...string) *client { t.Helper() var h tlvs h.add(tlvCookie, ck) - cl := dial(t, host, h) + return bosUp(t, dial(t, host, h), buddies...) +} + +// bosUp brings up a BOS connection made, as bos does. +func bosUp(t *testing.T, cl *client, buddies ...string) *client { + t.Helper() r := &rd{p: cl.expect(0x01, 0x03)} fams := map[uint16]bool{} for r.left() >= 2 { diff --git a/internal/oscar/server.go b/internal/oscar/server.go index c0d16b4..3a60aff 100644 --- a/internal/oscar/server.go +++ b/internal/oscar/server.go @@ -15,6 +15,7 @@ import ( "bufio" "context" "crypto/rand" + "crypto/tls" "errors" "fmt" "net" @@ -24,6 +25,7 @@ import ( "time" "github.com/D-Modem/bbs/internal/bbs" + "github.com/D-Modem/bbs/internal/certs" "github.com/D-Modem/bbs/internal/sockets" "github.com/D-Modem/bbs/internal/store" "github.com/D-Modem/bbs/internal/tcpserv" @@ -54,6 +56,13 @@ type Settings struct { UINBase uint32 // System is the screen name the BBS's notices come from System string + // TLSAddress, if set, is where clients come by TLS (AIM 6.2 to 7.x, + // clientLogin over HTTPS), with the certificate of TLSCert and TLSKey + TLSAddress, TLSCert, TLSKey string + // TLSHost is where clients that ask for TLS are sent (host:port, its + // host the certificate's name); "": Host's host at TLSAddress's port. + // Set it to a TLS proxy's when one is in front. + TLSHost string } // Server serves OSCAR. @@ -69,6 +78,7 @@ type Server struct { byNode map[int]*session cookies map[string]*cookie bagMu sync.Mutex // placing friends in buddy lists + web web // the HTTP logins } // New checks the settings and makes the server. @@ -110,10 +120,39 @@ func (s *Server) Serve(ctx context.Context, ln net.Listener) error { defer stop() stopFriends := s.B.WatchFriends(s.friendsChanged) defer stopFriends() + defer s.stopWeb() + refuse := func(c net.Conn) bool { return s.B.Refuse("oscar", c.RemoteAddr()) } + errs := make(chan error, 1) + if s.S.TLSAddress != "" { + src, err := certs.New(s.S.TLSCert, s.S.TLSKey) + if err != nil { + return fmt.Errorf("oscar: tls_cert, tls_key: %w", err) + } + tln, err := sockets.Listen("tcp", s.S.TLSAddress) + if err != nil { + return fmt.Errorf("oscar: %w", err) + } + cfg := legacyTLS(src.GetCertificate) + ts := &tcpserv.Server{Name: "oscar tls", MaxClients: s.S.MaxClients, MaxPerIP: s.S.MaxPerIP, Log: s.B.Log, + Refuse: refuse, Handle: func(c net.Conn) { + tc := tls.Server(c, cfg) + tc.SetDeadline(time.Now().Add(loginTimeout)) + if err := tc.Handshake(); err != nil { + s.B.Log.Printf("oscar: %s: TLS: %v", c.RemoteAddr(), err) + return + } + tc.SetDeadline(time.Time{}) + s.handle(tc) + }} + go func() { errs <- ts.Serve(ctx, tln) }() + } ts := &tcpserv.Server{Name: "oscar", MaxClients: s.S.MaxClients, MaxPerIP: s.S.MaxPerIP, Log: s.B.Log, - Handle: s.handle, - Refuse: func(c net.Conn) bool { return s.B.Refuse("oscar", c.RemoteAddr()) }} - return ts.Serve(ctx, ln) + Handle: s.handle, Refuse: refuse} + err := ts.Serve(ctx, ln) + if s.S.TLSAddress != "" { + <-errs + } + return err } // Clients is how many sessions are signed on. @@ -148,6 +187,10 @@ func (s *Server) handle(c net.Conn) { c.SetReadDeadline(time.Time{}) s.P3(&peeked{c, r}) return + case err == nil && isHTTP(first[0]): + c.SetReadDeadline(time.Time{}) + s.serveHTTP(&peeked{c, r}) // a later AIM's login, by HTTP + return case err == nil && first[0] != flapStart: return // neither case err != nil && !(errors.As(err, &ne) && ne.Timeout()): @@ -187,6 +230,7 @@ type cookie struct { room string // chat: the room exchange uint16 // chat: its exchange sess *session // a service's: the session it serves + tls bool // the client comes by TLS expires time.Time } diff --git a/internal/oscar/session.go b/internal/oscar/session.go index 278f421..ec8e9b8 100644 --- a/internal/oscar/session.go +++ b/internal/oscar/session.go @@ -433,10 +433,21 @@ func (ss *session) serviceRequest(h snacHeader, r *rd) { } var o tlvs o.addU16(0x000d, fam) - o.addStr(0x0005, ss.s.reconnectHost(ss.fc.c)) - o.add(0x0006, ss.s.newCookie(k)) - if t.has(0x008c) { - o.addU8(0x008e, 0) // no SSL + tlsTo := ss.s.tlsHost() + switch { + case t.has(0x008c) && tlsTo != "": // by TLS, as it asks + k.tls = true + certName, _, _ := net.SplitHostPort(tlsTo) + o.addStr(0x0005, tlsTo) + o.add(0x0006, ss.s.newCookie(k)) + o.addStr(0x008d, certName) + o.addU8(0x008e, 2) + default: + o.addStr(0x0005, ss.s.reconnectHost(ss.fc.c)) + o.add(0x0006, ss.s.newCookie(k)) + if t.has(0x008c) { + o.addU8(0x008e, 0) // no SSL + } } ss.snac(0x0001, 0x0005, h.req, o.bytes()) } diff --git a/internal/oscar/web.go b/internal/oscar/web.go new file mode 100644 index 0000000..2ba94f7 --- /dev/null +++ b/internal/oscar/web.go @@ -0,0 +1,564 @@ +package oscar + +import ( + "bytes" + "crypto/rand" + "crypto/tls" + "encoding/base64" + "encoding/json" + "encoding/xml" + "errors" + "fmt" + "io" + "net" + "net/http" + "strconv" + "strings" + "sync" + "time" + + "github.com/D-Modem/bbs/internal/bbs" + "github.com/D-Modem/bbs/internal/store" +) + +// The later AIM logins, over HTTP(S) on the OSCAR port (and the TLS +// port, if there is one): +// +// POST / AIM 6.2 to 7.x's Kerberos-style login: a +// SNAC (0x050C/0x0002) with the password, +// answered by one with the BOS host and cookie +// POST /auth/clientLogin the password, for a token (Pidgin, AIM +// Express, the phones' AIM; api.screenname.aol.com) +// GET /aim/startOSCARSession the token, for the BOS host and cookie +// (api.oscar.aol.com) +// +// A client that asks for TLS is sent to tls_host for the BOS; the others +// to the plain one. + +// isHTTP: a connection's first byte is an HTTP request's. +func isHTTP(b byte) bool { return b == 'G' || b == 'P' || b == 'H' || b == 'O' } + +// web is the HTTP server the sniffed connections are handed to. +type web struct { + once sync.Once + ln *connListener + hs *http.Server +} + +// connListener is a listener of connections handed to it. +type connListener struct { + ch chan net.Conn + done chan struct{} + once sync.Once +} + +func (l *connListener) Accept() (net.Conn, error) { + select { + case c := <-l.ch: + return c, nil + case <-l.done: + return nil, net.ErrClosed + } +} + +func (l *connListener) Close() error { + l.once.Do(func() { close(l.done) }) + return nil +} + +func (l *connListener) Addr() net.Addr { return &net.TCPAddr{} } + +// heldConn is a connection the HTTP server has; closed tells its handler +// it is done with it. +type heldConn struct { + net.Conn + once sync.Once + closed chan struct{} +} + +func (c *heldConn) Close() error { + c.once.Do(func() { close(c.closed) }) + return c.Conn.Close() +} + +// serveHTTP has the web server answer c, until it is done with it. +func (s *Server) serveHTTP(c net.Conn) { + s.web.once.Do(func() { + s.web.ln = &connListener{ch: make(chan net.Conn), done: make(chan struct{})} + s.web.hs = &http.Server{Handler: s.webHandler(), ReadHeaderTimeout: 30 * time.Second, + WriteTimeout: time.Minute, IdleTimeout: time.Minute} + go s.web.hs.Serve(s.web.ln) + }) + h := &heldConn{Conn: c, closed: make(chan struct{})} + select { + case s.web.ln.ch <- h: + case <-s.web.ln.done: + return + } + <-h.closed +} + +// stopWeb ends the web server. +func (s *Server) stopWeb() { + if s.web.hs != nil { + s.web.ln.Close() + s.web.hs.Close() + } +} + +// webHandler answers the logins. +func (s *Server) webHandler() http.Handler { + mux := http.NewServeMux() + mux.HandleFunc("POST /{$}", s.kerberos) + mux.HandleFunc("POST /auth/clientLogin", s.clientLogin) + mux.HandleFunc("GET /aim/startOSCARSession", s.startOSCARSession) + mux.HandleFunc("POST /aim/startOSCARSession", s.startOSCARSession) + mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/plain") + fmt.Fprintf(w, "%s: AIM and ICQ\n", s.B.Conf().Name) + }) + return mux +} + +// remoteHost is a request's client address, without its port. +func remoteHost(r *http.Request) string { + h, _, err := net.SplitHostPort(r.RemoteAddr) + if err != nil { + return r.RemoteAddr + } + return h +} + +// tlsHost is where a client that asked for TLS connects (host:port), "" +// if none is set up. +func (s *Server) tlsHost() string { + if s.S.TLSHost != "" { + return s.S.TLSHost + } + if s.S.TLSAddress == "" { + return "" + } + _, port, _ := net.SplitHostPort(s.S.TLSAddress) + host := "" + if s.S.Host != "" { + host, _, _ = net.SplitHostPort(s.S.Host) + } + if host == "" { + return "" + } + return net.JoinHostPort(host, port) +} + +// plainHost is where a client that came by HTTP connects in the clear. +func (s *Server) plainHost(r *http.Request) string { + if s.S.Host != "" { + return s.S.Host + } + if a, ok := r.Context().Value(http.LocalAddrContextKey).(net.Addr); ok { + if _, port, _ := net.SplitHostPort(s.S.Address); port != "" { + if h, _, err := net.SplitHostPort(a.String()); err == nil && h != "" && h != "::" && h != "0.0.0.0" { + return net.JoinHostPort(h, port) + } + } + } + host, _, _ := net.SplitHostPort(r.Host) + if host == "" { + host = r.Host + } + _, port, _ := net.SplitHostPort(s.S.Address) + return net.JoinHostPort(host, port) +} + +// webLogin checks a password sent in the clear, by HTTP; the cookie for +// the BOS (tls: for a client to come by TLS). +func (s *Server) webLogin(host, sn, pw, clientID string, tls bool) (*store.User, []byte, error) { + u, err := s.passwordLogin(host, strings.TrimSpace(sn), pw) + if err != nil { + if errors.Is(err, bbs.ErrBadLogin) && s.resolve(sn) == nil { + err = errNoUser + } + return nil, nil, err + } + icq := isUIN(strings.TrimSpace(sn)) + name := u.Name + if icq { + name = s.uinOf(u.ID) + } + ck := s.newCookie(&cookie{user: u, sn: name, icq: icq, clientID: clientID, tls: tls}) + s.B.Log.Printf("oscar: %s: %s signed on (%s)", host, u.Name, clientID) + return u, ck, nil +} + +// apiResponse is the AIM web API's answer, as XML or JSON. +type apiResponse struct { + XMLName xml.Name `json:"-" xml:"response"` + StatusCode int `json:"statusCode" xml:"statusCode"` + StatusText string `json:"statusText" xml:"statusText"` + StatusDetailCode int `json:"statusDetailCode,omitempty" xml:"statusDetailCode,omitempty"` + Data any `json:"data,omitempty" xml:"data,omitempty"` +} + +// sendAPI writes an answer in the format asked for (f=xml, f=json; the +// default is XML, as libpurple asks for). +func sendAPI(w http.ResponseWriter, r *http.Request, resp apiResponse) { + if resp.StatusText == "" { + resp.StatusText = http.StatusText(resp.StatusCode) + } + if resp.StatusCode == 200 { + resp.StatusText = "OK" + } + switch f := strings.ToLower(r.FormValue("f")); f { + case "json", "jsonp": + b, _ := json.Marshal(map[string]any{"response": resp}) + if cb := r.FormValue("c"); cb != "" && validCallback(cb) { + w.Header().Set("Content-Type", "text/javascript") + fmt.Fprintf(w, "%s(%s);", cb, b) + return + } + w.Header().Set("Content-Type", "application/json") + w.Write(b) + default: + w.Header().Set("Content-Type", "text/xml; charset=utf-8") + b, _ := xml.Marshal(resp) + w.Write([]byte(xml.Header)) + w.Write(b) + } +} + +// validCallback: a JSONP callback's name, nothing more. +func validCallback(s string) bool { + if len(s) > 64 { + return false + } + for _, r := range s { + if !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || r == '_' || r == '.' || r == '$') { + return false + } + } + return true +} + +// clientLoginData is clientLogin's answer. +type clientLoginData struct { + Token struct { + A string `json:"a" xml:"a"` + ExpiresIn int `json:"expiresIn" xml:"expiresIn"` + } `json:"token" xml:"token"` + LoginID string `json:"loginId" xml:"loginId"` + ScreenName string `json:"screenName" xml:"screenName"` + SessionSecret string `json:"sessionSecret" xml:"sessionSecret"` + HostTime int64 `json:"hostTime" xml:"hostTime"` +} + +// clientLogin is POST /auth/clientLogin: s (the screen name), pwd; a token +// for startOSCARSession. +func (s *Server) clientLogin(w http.ResponseWriter, r *http.Request) { + host := remoteHost(r) + if s.B.Refuse("oscar", addrOf(r.RemoteAddr)) { + http.Error(w, "refused", http.StatusForbidden) + return + } + sn := r.PostFormValue("s") + pw := r.PostFormValue("pwd") + if sn == "" || pw == "" { + sendAPI(w, r, apiResponse{StatusCode: 400, StatusText: "Missing parameter: s and pwd"}) + return + } + clientID := "clientLogin" + if d := r.PostFormValue("devId"); d != "" { + clientID += " (" + bbs.Trunc(d, 40) + ")" + } + u, ck, err := s.webLogin(host, sn, pw, clientID, false) + if err != nil { + switch { + case errors.Is(err, bbs.ErrThrottled): + sendAPI(w, r, apiResponse{StatusCode: 430, StatusText: "Rate limited: try again later"}) + case errors.Is(err, bbs.ErrLocked), errors.Is(err, bbs.ErrNotAllowed): + sendAPI(w, r, apiResponse{StatusCode: 401, StatusDetailCode: 3019, StatusText: "Account suspended"}) + case errors.Is(err, bbs.ErrBadLogin), errors.Is(err, errNoUser): + sendAPI(w, r, apiResponse{StatusCode: 330, StatusDetailCode: 3011, StatusText: "Incorrect screen name or password"}) + default: + s.B.Log.Printf("oscar: %s: clientLogin: %v", host, err) + sendAPI(w, r, apiResponse{StatusCode: 500, StatusText: "Temporarily unavailable"}) + } + return + } + secret := make([]byte, 16) + rand.Read(secret) + var d clientLoginData + d.Token.A = base64.URLEncoding.EncodeToString(ck) + d.Token.ExpiresIn = int(cookieLife / time.Second) + d.LoginID, d.ScreenName = sn, u.Name + d.SessionSecret = base64.StdEncoding.EncodeToString(secret) + d.HostTime = time.Now().Unix() + sendAPI(w, r, apiResponse{StatusCode: 200, Data: d}) +} + +// oscarSessionData is startOSCARSession's answer. +type oscarSessionData struct { + Host string `json:"host" xml:"host"` + Port int `json:"port" xml:"port"` + Cookie string `json:"cookie" xml:"cookie"` + TLSCertName string `json:"tlsCertName,omitempty" xml:"tlsCertName,omitempty"` +} + +// startOSCARSession is GET /aim/startOSCARSession: a (clientLogin's token), +// useTLS; the BOS host and cookie. The request's signature (keyed by the +// password and the session secret) is not checked: the token is the +// cookie, which is secret enough. +func (s *Server) startOSCARSession(w http.ResponseWriter, r *http.Request) { + tok := strings.TrimSpace(r.FormValue("a")) + ck, err := base64.URLEncoding.DecodeString(tok) + if err != nil { + ck, err = base64.StdEncoding.DecodeString(tok) + } + var k *cookie + if err == nil { + k = s.peekCookie(ck) + } + if k == nil || k.service != 0 { + sendAPI(w, r, apiResponse{StatusCode: 401, StatusText: "Authentication required: the token is unknown or expired"}) + return + } + useTLS := boolParam(r.FormValue("useTLS")) + target := s.plainHost(r) + if useTLS { + if t := s.tlsHost(); t != "" { + target = t + s.markTLS(ck) + } else { + useTLS = false // in the clear, as a client that asked for TLS takes when none is named + } + } + h, p, _ := net.SplitHostPort(target) + port, _ := strconv.Atoi(p) + d := oscarSessionData{Host: h, Port: port, Cookie: base64.StdEncoding.EncodeToString(ck)} + if useTLS { + d.TLSCertName = h + } + sendAPI(w, r, apiResponse{StatusCode: 200, Data: d}) +} + +func boolParam(v string) bool { + v = strings.ToLower(v) + return v == "1" || v == "true" || v == "yes" +} + +// peekCookie is a cookie, not spent (nil: none such, or expired). +func (s *Server) peekCookie(b []byte) *cookie { + s.mu.Lock() + defer s.mu.Unlock() + k := s.cookies[string(b)] + if k == nil || time.Now().After(k.expires) { + return nil + } + return k +} + +// markTLS notes that a cookie's client comes by TLS. +func (s *Server) markTLS(b []byte) { + s.mu.Lock() + defer s.mu.Unlock() + if k := s.cookies[string(b)]; k != nil { + k.tls = true + } +} + +// Kerberos login (AIM 6.2 to 7.x) +const ( + kerbFamily = 0x050c + kerbRequest = 0x0002 + kerbOK = 0x0003 + kerbFail = 0x0004 + kerbBadAuth = 0x0401 +) + +// roastKerberos is the Kerberos login's roasting table (its version 4 and +// later). +var roastKerberos = []byte{0x76, 0x91, 0xc5, 0xe7, 0xd0, 0xd9, 0x95, 0xdd, 0x9e, 0x2f, 0xea, 0xd8, 0x6b, 0x21, 0xc2, 0xbc} + +// kerbRequestBody is what a Kerberos login request says, of what is used. +type kerbRequestBody struct { + id uint32 + sn string + password string +} + +// parseKerberos reads a Kerberos login request (after its SNAC header). +func parseKerberos(body []byte) (kerbRequestBody, error) { + r := &rd{p: body} + var k kerbRequestBody + k.id = r.u32() + r.take(16) // the client's address, its COOL version, zero + r.tlvBlock() + r.take(8) // locale flags + r.str16() // country + r.str16() // language + r.tlvBlock() + r.u32() + r.u8() // auth type + k.sn = r.str16() + r.str16() // the service ("im/boss") + r.u32() + r.u16() + meta := r.tlvBlock() + if r.bad { + return k, errors.New("a short Kerberos login request") + } + v, ok := meta.get(0x0002) + if !ok { + return k, errors.New("no ticket request in the Kerberos login") + } + t := &rd{p: v} + t.u32() // marker + version := t.u16() + t.u32() // flags + t.u16() + pw := t.take(int(t.u16())) + if t.bad { + return k, errors.New("a short Kerberos ticket request") + } + if version >= 4 { + k.password = unroast(pw, roastKerberos) + } else { + k.password = string(pw) + } + return k, nil +} + +// kerberos is POST /: AIM 6.2 to 7.x's login. The answer is a SNAC: the +// login's ticket, with where the BOS is and the cookie, or a refusal. +func (s *Server) kerberos(w http.ResponseWriter, r *http.Request) { + host := remoteHost(r) + if s.B.Refuse("oscar", addrOf(r.RemoteAddr)) { + http.Error(w, "refused", http.StatusForbidden) + return + } + body, err := readBody(r, 64<<10) + if err != nil { + http.Error(w, "a body too long", http.StatusRequestEntityTooLarge) + return + } + h, rest, err := parseSNAC(body) + if err != nil || h.fam != kerbFamily || h.sub != kerbRequest { + http.Error(w, "not a Kerberos login request", http.StatusBadRequest) + return + } + req, err := parseKerberos(rest) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + tlsTo := s.tlsHost() + _, ck, err := s.webLogin(host, req.sn, req.password, "AIM 6/7 (Kerberos login)", tlsTo != "") + var b buf + sub := uint16(kerbOK) + if err != nil { + if !errors.Is(err, bbs.ErrBadLogin) && !errors.Is(err, errNoUser) && !errors.Is(err, bbs.ErrThrottled) && + !errors.Is(err, bbs.ErrLocked) && !errors.Is(err, bbs.ErrNotAllowed) { + s.B.Log.Printf("oscar: %s: Kerberos login: %v", host, err) + } + sub = kerbFail + msg := "Incorrect screen name or password." + switch { + case errors.Is(err, bbs.ErrThrottled): + msg = "Too many tries: wait a while, then try again." + case errors.Is(err, bbs.ErrLocked), errors.Is(err, bbs.ErrNotAllowed): + msg = "This account may not use AIM." + } + b.u32(req.id) + b.str16(req.sn) + b.u16(kerbBadAuth) + b.str16(msg) + b.u32(0) + b.u16(0) // no TLVs + } else { + target := tlsTo + if target == "" { + target = s.plainHost(r) + } + var conn tlvs + conn.addStr(0x0005, target) + conn.add(0x0006, ck) + if tlsTo != "" { + certName, _, _ := net.SplitHostPort(tlsTo) + conn.addU16(0x008e, 0x0002) // by TLS + conn.addStr(0x008d, certName) + } + var info buf + info.u16(1) + info.raw(conn.block()) + var meta tlvs + meta.add(0x0003, info) + now := uint32(time.Now().Unix()) + b.u32(req.id) + b.u32(now) + b.u32(0) + b.str16(req.sn) + b.str16("AOL") + b.u16(1) // one ticket: the BOS's + b.u16(5) // Kerberos 5 + b.str16("") + b.str16("AOL") + b.str16("im/boss") + b.str16("AOL") + b.str16(req.sn) + b.u8(0) // key version + b.str16("") // no session key + b.u32(0) + b.u32(0) + b.u32(now) // authenticated + b.u32(now) // valid from + b.u32(now + 24*3600) + b.u32(0) + b.u32(0x60000000) + b.u32(0x40000000) + b.u32(0) + b.raw(meta.block()) + b.u16(0) // no extensions + } + var out buf + out.u16(kerbFamily) + out.u16(sub) + out.u16(0) + out.u32(h.req) + out.raw(b) + w.Header().Set("Content-Type", "application/x-snac") + w.Write(out) +} + +// readBody reads a request's body, up to max bytes. +func readBody(r *http.Request, max int64) ([]byte, error) { + var b bytes.Buffer + if _, err := b.ReadFrom(io.LimitReader(r.Body, max+1)); err != nil { + return nil, err + } + if int64(b.Len()) > max { + return nil, errors.New("too long") + } + return b.Bytes(), nil +} + +// addrOf is a request's remote address as a net.Addr. +func addrOf(s string) net.Addr { + a, err := net.ResolveTCPAddr("tcp", s) + if err != nil { + return &net.TCPAddr{} + } + return a +} + +// legacyTLS takes old clients' TLS: 1.0, with RSA key exchange and 3DES +// or RC4 (all AIM 6's NSS has), as well as current ones. +func legacyTLS(get func(*tls.ClientHelloInfo) (*tls.Certificate, error)) *tls.Config { + return &tls.Config{GetCertificate: get, MinVersion: tls.VersionTLS10, + CipherSuites: []uint16{ + tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, + tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, + tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, + tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, + tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, + tls.TLS_RSA_WITH_AES_128_CBC_SHA, tls.TLS_RSA_WITH_AES_256_CBC_SHA, + tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA, tls.TLS_RSA_WITH_RC4_128_SHA, + }} +} diff --git a/internal/oscar/web_test.go b/internal/oscar/web_test.go new file mode 100644 index 0000000..4b9b660 --- /dev/null +++ b/internal/oscar/web_test.go @@ -0,0 +1,261 @@ +package oscar + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "encoding/base64" + "encoding/pem" + "encoding/xml" + "io" + "math/big" + "net" + "net/http" + "net/url" + "os" + "path/filepath" + "strconv" + "strings" + "testing" + "time" +) + +// webResponse is the AIM web API's XML answer, of what the tests read. +type webResponse struct { + StatusCode int `xml:"statusCode"` + StatusDetailCode int `xml:"statusDetailCode"` + Token string `xml:"data>token>a"` + SessionSecret string `xml:"data>sessionSecret"` + Host string `xml:"data>host"` + Port int `xml:"data>port"` + Cookie string `xml:"data>cookie"` + TLSCertName string `xml:"data>tlsCertName"` +} + +func readWeb(t *testing.T) func(*http.Response, error) webResponse { + return func(resp *http.Response, err error) webResponse { return readWebResp(t, resp, err) } +} + +func readWebResp(t *testing.T, resp *http.Response, err error) webResponse { + t.Helper() + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + b, _ := io.ReadAll(resp.Body) + var w webResponse + if err := xml.Unmarshal(b, &w); err != nil { + t.Fatalf("%v: %s", err, b) + } + return w +} + +// TestClientLogin: clientLogin over HTTP on the OSCAR port (as Pidgin +// does it), then startOSCARSession, then the BOS with its cookie; a +// wrong password refused as libpurple reads it. +func TestClientLogin(t *testing.T) { + e := start(t) + base := "http://" + e.addr + w := readWeb(t)(http.PostForm(base+"/auth/clientLogin", + url.Values{"devId": {"pidgin"}, "f": {"xml"}, "s": {"alice"}, "pwd": {"wrong"}})) + if w.StatusCode != 330 || w.StatusDetailCode != 3011 { + t.Errorf("wrong password: %+v", w) + } + w = readWeb(t)(http.PostForm(base+"/auth/clientLogin", + url.Values{"devId": {"pidgin"}, "f": {"xml"}, "s": {"alice"}, "pwd": {"password1"}})) + if w.StatusCode != 200 || w.Token == "" || w.SessionSecret == "" { + t.Fatalf("clientLogin: %+v", w) + } + q := url.Values{"a": {w.Token}, "f": {"xml"}, "k": {"pidgin"}, "ts": {"1"}, "useTLS": {"0"}} + w = readWeb(t)(http.Get(base + "/aim/startOSCARSession?" + q.Encode())) + if w.StatusCode != 200 || net.JoinHostPort(w.Host, strconv.Itoa(w.Port)) != e.addr || w.TLSCertName != "" { + t.Fatalf("startOSCARSession: %+v", w) + } + ck, err := base64.StdEncoding.DecodeString(w.Cookie) + if err != nil { + t.Fatal(err) + } + alice := bos(t, e.addr, ck) + alice.sendIM("bob", "hi", false) + if from, _ := alice.recvIM(); from != "OnlineHost" { // bob is away: kept + t.Errorf("from %q", from) + } + + // a spent token is no good + w = readWeb(t)(http.Get(base + "/aim/startOSCARSession?" + q.Encode())) + if w.StatusCode != 401 { + t.Errorf("spent token: %+v", w) + } +} + +// kerberosRequest is AIM 6's login request, roasted as version 4 and +// later roast it. +func kerberosRequest(sn, pw string) []byte { + var ticket buf + ticket.u32(0x00010000) + ticket.u16(4) + ticket.u32(0) + ticket.u16(0) + ticket.str16(unroast([]byte(pw), roastKerberos)) + ticket.u16(0) + var meta tlvs + meta.add(0x0002, ticket) + var b buf + b.u16(kerbFamily) + b.u16(kerbRequest) + b.u16(0) + b.u32(7) + b.u32(42) // request id + b.raw(make([]byte, 16)) + b.u16(0) + b.raw(make([]byte, 8)) + b.str16("US") + b.str16("en") + b.u16(0) + b.u32(0) + b.u8(1) + b.str16(sn) + b.str16("im/boss") + b.u32(0) + b.u16(2) + b.raw(meta.block()) + return b +} + +// kerberosAnswer reads a Kerberos login's answer: its subtype, and the +// ticket's connection TLVs. +func kerberosAnswer(t *testing.T) func(*http.Response, error) (uint16, tlvs) { + return func(resp *http.Response, err error) (uint16, tlvs) { return kerberosResp(t, resp, err) } +} + +func kerberosResp(t *testing.T, resp *http.Response, err error) (uint16, tlvs) { + t.Helper() + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + b, _ := io.ReadAll(resp.Body) + h, body, err := parseSNAC(b) + if err != nil || h.fam != kerbFamily { + t.Fatalf("answer %x", b) + } + if h.sub != kerbOK { + return h.sub, nil + } + r := &rd{p: body} + if id := r.u32(); id != 42 { + t.Errorf("request id %d", id) + } + r.take(8) + r.str16() + r.str16() + if n := r.u16(); n != 1 { + t.Fatalf("%d tickets", n) + } + r.u16() + for range 5 { + r.str16() + } + r.u8() + r.str16() + r.take(36) + meta := r.tlvBlock() + v, _ := meta.get(0x0003) + ir := &rd{p: v} + ir.u16() + conn := ir.tlvBlock() + if r.bad || ir.bad { + t.Fatalf("short answer %x", b) + } + return h.sub, conn +} + +// TestKerberos: AIM 6.2 to 7.x's login, by HTTP on the OSCAR port: a +// wrong password refused, a right one answered with the BOS's host and a +// cookie that signs on. +func TestKerberos(t *testing.T) { + e := start(t) + sub, _ := kerberosAnswer(t)(http.Post("http://"+e.addr+"/", "application/x-snac", + strings.NewReader(string(kerberosRequest("alice", "nope"))))) + if sub != kerbFail { + t.Errorf("wrong password: %x", sub) + } + sub, conn := kerberosAnswer(t)(http.Post("http://"+e.addr+"/", "application/x-snac", + strings.NewReader(string(kerberosRequest("alice", "password1"))))) + if sub != kerbOK { + t.Fatalf("login: %x", sub) + } + if conn.str(0x0005) != e.addr || conn.has(0x008e) { + t.Errorf("connection %v", conn) + } + ck, _ := conn.get(0x0006) + bos(t, e.addr, ck) +} + +// selfSigned writes a certificate for 127.0.0.1 and its key; their paths. +func selfSigned(t *testing.T) (string, string) { + t.Helper() + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + tmpl := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "127.0.0.1"}, + IPAddresses: []net.IP{net.ParseIP("127.0.0.1")}, NotBefore: time.Now().Add(-time.Hour), + NotAfter: time.Now().Add(time.Hour), KeyUsage: x509.KeyUsageDigitalSignature, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}} + der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key) + if err != nil { + t.Fatal(err) + } + kb, _ := x509.MarshalECPrivateKey(key) + dir := t.TempDir() + crt, kf := filepath.Join(dir, "c.pem"), filepath.Join(dir, "k.pem") + os.WriteFile(crt, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), 0o600) + os.WriteFile(kf, pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: kb}), 0o600) + return crt, kf +} + +// TestKerberosTLS: with a TLS port, the Kerberos login comes by HTTPS +// (TLS 1.0 taken, as AIM 6 speaks it) and sends the client to the TLS +// host; the BOS by TLS there; a chat room asked for by TLS is there too. +func TestKerberosTLS(t *testing.T) { + crt, key := selfSigned(t) + tlsAddr := freeAddr(t) + start(t, func(s *Settings) { s.TLSAddress, s.TLSCert, s.TLSKey, s.TLSHost = tlsAddr, crt, key, tlsAddr }) + hc := &http.Client{Transport: &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true, MinVersion: tls.VersionTLS10, + MaxVersion: tls.VersionTLS10}}} + sub, conn := kerberosAnswer(t)(hc.Post("https://"+tlsAddr+"/", "application/x-snac", + strings.NewReader(string(kerberosRequest("alice", "password1"))))) + if sub != kerbOK { + t.Fatalf("login: %x", sub) + } + if conn.str(0x0005) != tlsAddr || conn.str(0x008d) != "127.0.0.1" { + t.Errorf("connection %v", conn) + } + if v, _ := conn.u16(0x008e); v != 2 { + t.Errorf("SSL %d", v) + } + ck, _ := conn.get(0x0006) + c, err := tls.Dial("tcp", tlsAddr, &tls.Config{InsecureSkipVerify: true}) + if err != nil { + t.Fatal(err) + } + var h tlvs + h.add(tlvCookie, ck) + alice := bosUp(t, clientOn(t, c, h, false)) + + // a chat room, by TLS as asked + var q buf + q.u16(0x000d) + var sr tlvs + sr.add(0x008c, nil) + q.raw(sr.bytes()) + alice.send(0x01, 0x04, q) + res := parseTLVs(alice.expect(0x01, 0x05)) + if res.str(0x0005) != tlsAddr || res.str(0x008d) != "127.0.0.1" { + t.Errorf("service %v", res) + } +} diff --git a/internal/server/oscarconfig.go b/internal/server/oscarconfig.go index 0294e09..90f5e34 100644 --- a/internal/server/oscarconfig.go +++ b/internal/server/oscarconfig.go @@ -1,10 +1,12 @@ package server import ( + "errors" "fmt" "net" "strings" + "github.com/D-Modem/bbs/internal/certs" "github.com/D-Modem/bbs/internal/config" "github.com/D-Modem/bbs/internal/oscar" ) @@ -42,6 +44,24 @@ func (c *Config) oscarSection(cf *config.File) error { return err } o.UINBase = uint32(base) + o.TLSAddress, o.TLSCert, o.TLSKey = s.String("tls_address", ""), s.String("tls_cert", ""), s.String("tls_key", "") + o.TLSHost = s.String("tls_host", "") + if o.TLSAddress != "" { + if _, _, err := net.SplitHostPort(o.TLSAddress); err != nil { + return fmt.Errorf("tls_address: %v", err) + } + if o.TLSCert == "" || o.TLSKey == "" && !certs.IsACME(o.TLSCert) { + return errors.New("tls_address needs tls_cert and tls_key") + } + if err := certs.Check(o.TLSCert, o.TLSKey, c.acmeNames()); err != nil { + return fmt.Errorf("tls_cert, tls_key: %v", err) + } + } + if o.TLSHost != "" { + if h, _, err := net.SplitHostPort(o.TLSHost); err != nil || h == "" { + return errors.New("tls_host: host:port, where clients come by TLS (its host the certificate's name)") + } + } c.OSCAR = o return nil }()