From a54f5b17ed6cc48d9c09c148cf74e11e74488ed6 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 06:54:38 +0000 Subject: [PATCH] oldtls: a TLS 1.0 server for AIM 6.2+'s SSL 2.0-format hello AIM 6.2 to 7.5 open TLS with an SSL 2.0-format ClientHello, which crypto/tls can't read, and TLS's Finished messages sign the hello's own bytes, so it can't be rewritten for crypto/tls either. internal/oldtls is a small TLS 1.0 server (RSA key exchange; AES-CBC, 3DES-CBC, RC4) that takes either hello format. The OSCAR TLS port hands it the connections that open in SSL 2.0's format; the rest still go to crypto/tls. It needs an RSA certificate; the log says so when there isn't one. Tested against crypto/tls's own client at TLS 1.0 with each suite, and a scripted client opening with an SSL 2.0-format hello. Signed-off-by: Claude Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01B82eRTAJGnEAiwGZm9ygpG --- bbs.conf.sample | 4 +- docs/wiki/AIM-and-ICQ.md | 42 +- docs/wiki/Configuration-Reference.md | 6 +- internal/oldtls/conn.go | 566 +++++++++++++++++++++++++++ internal/oldtls/conn_test.go | 328 ++++++++++++++++ internal/oldtls/record.go | 173 ++++++++ internal/oscar/server.go | 24 +- internal/oscar/web_test.go | 36 +- 8 files changed, 1138 insertions(+), 41 deletions(-) create mode 100644 internal/oldtls/conn.go create mode 100644 internal/oldtls/conn_test.go create mode 100644 internal/oldtls/record.go diff --git a/bbs.conf.sample b/bbs.conf.sample index aca1dee..7a3aa06 100644 --- a/bbs.conf.sample +++ b/bbs.conf.sample @@ -846,7 +846,9 @@ address = 127.0.0.1:2513 ;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_cert and tls_key (a certificate for the name clients use; an RSA one +; for AIM 6.2 to 7.x, whose TLS 1.0 has only RSA key exchange: with acme, +; key_type = rsa2048) ;tls_address = :443 ;tls_cert = /etc/bbs/aim.crt ;tls_key = /etc/bbs/aim.key diff --git a/docs/wiki/AIM-and-ICQ.md b/docs/wiki/AIM-and-ICQ.md index 36648a1..1e40b6f 100644 --- a/docs/wiki/AIM-and-ICQ.md +++ b/docs/wiki/AIM-and-ICQ.md @@ -100,8 +100,8 @@ 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 + (they ask for HTTPS and then a TLS connection, so `tls_address` 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 @@ -125,34 +125,18 @@ 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: +AIM 6.2 to 7.5 open TLS with an SSL 2.0-format hello and speak only TLS +1.0 with RSA key exchange. Go's TLS can't read that hello, so the BBS +answers those clients with a small TLS 1.0 server of its own (AES, 3DES +or RC4, by RSA); every other client gets Go's TLS. So `tls_cert` must be +an RSA certificate (with `[acme]`, `key_type = rsa2048`); the log says so +at start when it isn't. A chat room asked for by TLS is sent to the TLS +host too. -```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. +A TLS proxy in front (stunnel, nginx) works as well: have it pass the +plain connection to port 5190 and set `tls_host` to its address. Behind +it every client comes from the proxy's address, so `max_per_ip`, the +login throttle and bans see that one address. ## Port 5190 and AOL diff --git a/docs/wiki/Configuration-Reference.md b/docs/wiki/Configuration-Reference.md index 744ddc6..59f9dae 100644 --- a/docs/wiki/Configuration-Reference.md +++ b/docs/wiki/Configuration-Reference.md @@ -590,9 +590,9 @@ 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_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; an RSA one for AIM 6.2 to 7.x, whose TLS 1.0 has only RSA key exchange: with acme, key_type = rsa2048) 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; an RSA one for AIM 6.2 to 7.x, whose TLS 1.0 has only RSA key exchange: with acme, key_type = rsa2048) 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; an RSA one for AIM 6.2 to 7.x, whose TLS 1.0 has only RSA key exchange: with acme, key_type = rsa2048) 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`. | diff --git a/internal/oldtls/conn.go b/internal/oldtls/conn.go new file mode 100644 index 0000000..e6d45ff --- /dev/null +++ b/internal/oldtls/conn.go @@ -0,0 +1,566 @@ +// Package oldtls is a small TLS 1.0 server for the clients Go's crypto/tls +// can't take: those that open with an SSL 2.0-format hello, as AIM 6.2 to +// 7.5 (their NSS) do. Only that first message is SSL 2.0's; the rest is +// TLS 1.0, which crypto/tls still speaks, but TLS's Finished messages sign +// the hello's very bytes, so it can't be rewritten for crypto/tls. +// +// It serves TLS 1.0 only, with RSA key exchange (so an RSA certificate) +// and AES-CBC, 3DES-CBC or RC4: no resumption, renegotiation, client +// certificates or extensions beyond secure renegotiation's. These are +// old ciphers for old clients; anything newer belongs on crypto/tls. +package oldtls + +import ( + "bufio" + "crypto/md5" + "crypto/rand" + "crypto/rsa" + "crypto/sha1" + "crypto/subtle" + "crypto/tls" + "encoding/binary" + "errors" + "fmt" + "hash" + "io" + "net" + "slices" + "sync" + "sync/atomic" + "time" +) + +const ( + version10 = 0x0301 + + recCCS = 20 + recAlert = 21 + recHandshake = 22 + recData = 23 + + hsClientHello = 1 + hsServerHello = 2 + hsCertificate = 11 + hsServerDone = 14 + hsClientKeyExchange = 16 + hsFinished = 20 + + maxPlain = 16384 + maxRecord = maxPlain + 2048 + maxHSMsg = 1 << 16 + + alertCloseNotify = 0 + alertUnexpected = 10 + alertBadMAC = 20 + alertOverflow = 22 + alertHandshakeFailure = 40 + alertDecode = 50 + alertDecrypt = 51 + alertProtocolVersion = 70 + alertInternal = 80 + alertNoRenegotiation = 100 + levelWarning, levelFatal = 1, 2 +) + +// Config is a server's. +type Config struct { + // GetCertificate gives the certificate (its key must be RSA). + GetCertificate func(*tls.ClientHelloInfo) (*tls.Certificate, error) +} + +// IsSSLv2Hello reports whether a connection's first bytes (three or +// more) are an SSL 2.0-format ClientHello. +func IsSSLv2Hello(b []byte) bool { return len(b) >= 3 && b[0]&0x80 != 0 && b[2] == 1 } + +// Conn is a TLS 1.0 connection, server side. +type Conn struct { + net.Conn + cfg *Config + br *bufio.Reader + + hsMu sync.Mutex + hsDone bool + hsErr error + up atomic.Bool + suite uint16 + + hs []byte // handshake bytes read, not yet taken + md5h, sha1h hash.Hash + + inMu sync.Mutex + in half + data []byte + readErr error + + outMu sync.Mutex + out half +} + +// Server is c served as TLS 1.0; the handshake comes with the first Read +// or Write, or Handshake. +func Server(c net.Conn, cfg *Config) *Conn { + return &Conn{Conn: c, cfg: cfg, br: bufio.NewReader(c)} +} + +// CipherSuite is the suite agreed (0 before the handshake). +func (c *Conn) CipherSuite() uint16 { + c.hsMu.Lock() + defer c.hsMu.Unlock() + return c.suite +} + +// tlsError is an error that sends an alert. +type tlsError struct { + alert uint8 + msg string +} + +func (e *tlsError) Error() string { return "oldtls: " + e.msg } + +func fail(alert uint8, format string, a ...any) error { + return &tlsError{alert, fmt.Sprintf(format, a...)} +} + +// alertFor sends err's alert, if it has one. +func (c *Conn) alertFor(err error) { + var te *tlsError + if errors.As(err, &te) && te.alert != 0 { + c.sendAlert(levelFatal, te.alert) + } +} + +func (c *Conn) sendAlert(level, desc uint8) { + c.writeRecord(recAlert, []byte{level, desc}) +} + +// alertIn is the error for an alert the client sent. +func alertIn(data []byte) error { + if len(data) != 2 { + return fail(alertDecode, "bad alert") + } + if data[1] == alertCloseNotify { + return io.EOF + } + return fmt.Errorf("oldtls: alert %d from the client", data[1]) +} + +func (c *Conn) writeRecord(typ uint8, data []byte) error { + c.outMu.Lock() + defer c.outMu.Unlock() + var buf []byte + for len(data) > 0 || buf == nil { + n := min(len(data), maxPlain) + buf = append(buf, c.out.seal(typ, data[:n])...) + data = data[n:] + } + _, err := c.Conn.Write(buf) + return err +} + +func (c *Conn) readRecord() (uint8, []byte, error) { + var hdr [5]byte + if _, err := io.ReadFull(c.br, hdr[:]); err != nil { + return 0, nil, err + } + if hdr[1] != 3 { + return 0, nil, fail(alertProtocolVersion, "record version %x", hdr[1:3]) + } + n := int(binary.BigEndian.Uint16(hdr[3:])) + if n > maxRecord { + return 0, nil, fail(alertOverflow, "record of %d bytes", n) + } + body := make([]byte, n) + if _, err := io.ReadFull(c.br, body); err != nil { + return 0, nil, err + } + plain, ok := c.in.open(hdr[0], body) + if !ok { + return 0, nil, fail(alertBadMAC, "bad record MAC") + } + if len(plain) > maxPlain { + return 0, nil, fail(alertOverflow, "record of %d bytes", len(plain)) + } + return hdr[0], plain, nil +} + +// readHandshake is the next handshake message, whole (with its header). +func (c *Conn) readHandshake() ([]byte, error) { + for { + if len(c.hs) >= 4 { + n := int(c.hs[1])<<16 | int(c.hs[2])<<8 | int(c.hs[3]) + if n > maxHSMsg { + return nil, fail(alertDecode, "handshake message of %d bytes", n) + } + if len(c.hs) >= 4+n { + m := slices.Clone(c.hs[:4+n]) + c.hs = c.hs[4+n:] + return m, nil + } + } + typ, data, err := c.readRecord() + if err != nil { + return nil, err + } + switch typ { + case recHandshake: + c.hs = append(c.hs, data...) + case recAlert: + return nil, alertIn(data) + default: + return nil, fail(alertUnexpected, "record type %d in the handshake", typ) + } + } +} + +func (c *Conn) hash(m []byte) { + c.md5h.Write(m) + c.sha1h.Write(m) +} + +// finished is a Finished message's verify data, for the handshake so far. +func (c *Conn) finished(ms []byte, label string) []byte { + return prf10(ms, label, append(c.md5h.Sum(nil), c.sha1h.Sum(nil)...), 12) +} + +// Handshake runs the handshake, if it hasn't run. +func (c *Conn) Handshake() error { + c.hsMu.Lock() + defer c.hsMu.Unlock() + if c.hsDone { + return c.hsErr + } + c.hsDone = true + if c.hsErr = c.serverHandshake(); c.hsErr != nil { + c.alertFor(c.hsErr) + } else { + c.up.Store(true) + } + return c.hsErr +} + +type clientHello struct { + version uint16 + random []byte + suites []uint16 + sni string + secureReneg bool +} + +func (c *Conn) serverHandshake() error { + c.md5h, c.sha1h = md5.New(), sha1.New() + ch, err := c.readClientHello() + if err != nil { + return err + } + if ch.version < version10 { + return fail(alertProtocolVersion, "the client offers only SSL %x", ch.version) + } + cert, err := c.cfg.GetCertificate(&tls.ClientHelloInfo{ServerName: ch.sni, CipherSuites: ch.suites, + SupportedVersions: []uint16{tls.VersionTLS10}, Conn: c.Conn}) + if err != nil { + return fail(alertInternal, "certificate: %v", err) + } + key, ok := cert.PrivateKey.(*rsa.PrivateKey) + if !ok || len(cert.Certificate) == 0 { + return fail(alertHandshakeFailure, "the certificate's key is not RSA, which these clients need") + } + var s *suite + for i := range suites { + if slices.Contains(ch.suites, suites[i].id) { + s = &suites[i] + break + } + } + if s == nil { + return fail(alertHandshakeFailure, "no cipher suite in common: the client offers %04x", ch.suites) + } + + sr := make([]byte, 32) + rand.Read(sr) + hello := binary.BigEndian.AppendUint16(nil, version10) + hello = append(hello, sr...) + hello = append(hello, 0) // no session id: nothing is resumed + hello = binary.BigEndian.AppendUint16(hello, s.id) + hello = append(hello, 0) + if ch.secureReneg { + hello = append(hello, 0, 5, 0xff, 0x01, 0, 1, 0) // renegotiation_info, empty + } + var chain []byte + for _, der := range cert.Certificate { + chain = appendU24(chain, len(der)) + chain = append(chain, der...) + } + flight := msg(hsServerHello, hello) + flight = append(flight, msg(hsCertificate, appendU24(nil, len(chain)), chain...)...) + flight = append(flight, msg(hsServerDone, nil)...) + c.hash(flight) + if err := c.writeRecord(recHandshake, flight); err != nil { + return err + } + + m, err := c.readHandshake() + if err != nil { + return err + } + if m[0] != hsClientKeyExchange { + return fail(alertUnexpected, "handshake message %d, not the key exchange", m[0]) + } + c.hash(m) + ct, k := m[4:], key.Size() + if len(ct) == k+2 && int(binary.BigEndian.Uint16(ct)) == k { + ct = ct[2:] + } + if len(ct) != k { + return fail(alertDecode, "key exchange of %d bytes", len(m)-4) + } + // A bad decryption, or the wrong version in it, goes on with a random + // secret, in the same time, and fails at Finished (Bleichenbacher). + pre, alt := make([]byte, 48), make([]byte, 48) + rand.Read(pre) + rand.Read(alt) + if err := rsa.DecryptPKCS1v15SessionKey(nil, key, ct, pre); err != nil { + return fail(alertInternal, "%v", err) + } + vOK := subtle.ConstantTimeByteEq(pre[0], byte(ch.version>>8)) & + (subtle.ConstantTimeByteEq(pre[1], byte(ch.version)) | subtle.ConstantTimeByteEq(pre[1], 1)) + subtle.ConstantTimeCopy(1-vOK, pre, alt) + + ms := prf10(pre, "master secret", append(slices.Clone(ch.random), sr...), 48) + ck, sk := s.keys(ms, ch.random, sr) + clientFinished := c.finished(ms, "client finished") + + if len(c.hs) != 0 { + return fail(alertUnexpected, "handshake data before ChangeCipherSpec") + } + typ, data, err := c.readRecord() + if err != nil { + return err + } + if typ == recAlert { + return alertIn(data) + } + if typ != recCCS || len(data) != 1 || data[0] != 1 { + return fail(alertUnexpected, "record type %d, not ChangeCipherSpec", typ) + } + c.in = s.newHalf(ck.mac, ck.key, ck.iv, false) + if m, err = c.readHandshake(); err != nil { + return err + } + if m[0] != hsFinished || len(m) != 4+12 { + return fail(alertUnexpected, "handshake message %d, not Finished", m[0]) + } + if subtle.ConstantTimeCompare(m[4:], clientFinished) != 1 { + return fail(alertDecrypt, "the client's Finished is wrong") + } + c.hash(m) + + if err := c.writeRecord(recCCS, []byte{1}); err != nil { + return err + } + c.outMu.Lock() + c.out = s.newHalf(sk.mac, sk.key, sk.iv, true) + c.outMu.Unlock() + if err := c.writeRecord(recHandshake, msg(hsFinished, c.finished(ms, "server finished"))); err != nil { + return err + } + c.suite = s.id + return nil +} + +func appendU24(b []byte, n int) []byte { return append(b, byte(n>>16), byte(n>>8), byte(n)) } + +// msg is a handshake message. +func msg(typ uint8, body []byte, more ...byte) []byte { + m := appendU24([]byte{typ}, len(body)+len(more)) + return append(append(m, body...), more...) +} + +// readClientHello reads the hello, in either format. +func (c *Conn) readClientHello() (*clientHello, error) { + b, err := c.br.Peek(1) + if err != nil { + return nil, err + } + if b[0]&0x80 != 0 { + return c.readV2Hello() + } + m, err := c.readHandshake() + if err != nil { + return nil, err + } + if m[0] != hsClientHello { + return nil, fail(alertUnexpected, "handshake message %d, not ClientHello", m[0]) + } + c.hash(m) + return parseClientHello(m[4:]) +} + +// readV2Hello reads an SSL 2.0-format ClientHello: its message (the bytes +// after the two of the record's length) is the handshake's first. +func (c *Conn) readV2Hello() (*clientHello, error) { + var hdr [2]byte + if _, err := io.ReadFull(c.br, hdr[:]); err != nil { + return nil, err + } + n := int(hdr[0]&0x7f)<<8 | int(hdr[1]) + if n < 9 { + return nil, fail(alertDecode, "SSL 2.0 hello of %d bytes", n) + } + m := make([]byte, n) + if _, err := io.ReadFull(c.br, m); err != nil { + return nil, err + } + if m[0] != 1 { + return nil, fail(alertUnexpected, "SSL 2.0 message %d, not CLIENT-HELLO", m[0]) + } + c.hash(m) + u := func(i int) int { return int(binary.BigEndian.Uint16(m[i:])) } + specLen, sidLen, chalLen := u(3), u(5), u(7) + if 9+specLen+sidLen+chalLen != n || specLen%3 != 0 || chalLen < 16 || chalLen > 32 { + return nil, fail(alertDecode, "bad SSL 2.0 hello") + } + ch := &clientHello{version: uint16(u(1))} + specs := m[9 : 9+specLen] + for i := 0; i < len(specs); i += 3 { + if specs[i] == 0 { // a TLS suite; others are SSL 2.0's own + id := binary.BigEndian.Uint16(specs[i+1:]) + ch.suites = append(ch.suites, id) + if id == 0x00ff { + ch.secureReneg = true + } + } + } + chal := m[9+specLen+sidLen:] + ch.random = make([]byte, 32) + copy(ch.random[32-len(chal):], chal) + return ch, nil +} + +type reader struct { + b []byte + bad bool +} + +func (r *reader) take(n int) []byte { + if r.bad || len(r.b) < n { + r.bad = true + return nil + } + v := r.b[:n] + r.b = r.b[n:] + return v +} + +func (r *reader) u8() int { + if v := r.take(1); v != nil { + return int(v[0]) + } + return 0 +} + +func (r *reader) u16() int { + if v := r.take(2); v != nil { + return int(binary.BigEndian.Uint16(v)) + } + return 0 +} + +func parseClientHello(body []byte) (*clientHello, error) { + r := &reader{b: body} + ch := &clientHello{version: uint16(r.u16())} + ch.random = slices.Clone(r.take(32)) + r.take(r.u8()) // session id + ss := r.take(r.u16()) + if len(ss)%2 != 0 { + r.bad = true + } + for i := 0; i+1 < len(ss); i += 2 { + id := binary.BigEndian.Uint16(ss[i:]) + ch.suites = append(ch.suites, id) + if id == 0x00ff { + ch.secureReneg = true + } + } + if comp := r.take(r.u8()); !r.bad && !slices.Contains(comp, 0) { + return nil, fail(alertHandshakeFailure, "the client offers no null compression") + } + if len(r.b) > 0 && !r.bad { + ext := &reader{b: r.take(r.u16())} + for len(ext.b) > 0 && !ext.bad { + typ, data := ext.u16(), ext.take(ext.u16()) + switch typ { + case 0xff01: + ch.secureReneg = true + case 0x0000: // server name + sn := &reader{b: data} + list := &reader{b: sn.take(sn.u16())} + if list.u8() == 0 { + ch.sni = string(list.take(list.u16())) + } + } + } + r.bad = r.bad || ext.bad + } + if r.bad { + return nil, fail(alertDecode, "bad ClientHello") + } + return ch, nil +} + +// Read reads application data. +func (c *Conn) Read(p []byte) (int, error) { + if err := c.Handshake(); err != nil { + return 0, err + } + c.inMu.Lock() + defer c.inMu.Unlock() + for len(c.data) == 0 { + if c.readErr != nil { + return 0, c.readErr + } + typ, data, err := c.readRecord() + switch { + case err != nil: + c.alertFor(err) + c.readErr = err + case typ == recData: + c.data = data + case typ == recAlert: + if len(data) == 2 && data[0] == levelWarning && data[1] != alertCloseNotify { + continue + } + c.readErr = alertIn(data) + case typ == recHandshake: // the client would renegotiate: not here + c.sendAlert(levelWarning, alertNoRenegotiation) + default: + c.readErr = fail(alertUnexpected, "record type %d", typ) + c.alertFor(c.readErr) + } + } + n := copy(p, c.data) + c.data = c.data[n:] + return n, nil +} + +// Write writes application data. +func (c *Conn) Write(p []byte) (int, error) { + if err := c.Handshake(); err != nil { + return 0, err + } + if len(p) == 0 { + return 0, nil + } + if err := c.writeRecord(recData, p); err != nil { + return 0, err + } + return len(p), nil +} + +// Close sends close_notify (after a handshake) and closes the connection. +func (c *Conn) Close() error { + if c.up.Load() { + c.Conn.SetWriteDeadline(time.Now().Add(5 * time.Second)) + c.sendAlert(levelWarning, alertCloseNotify) + } + return c.Conn.Close() +} diff --git a/internal/oldtls/conn_test.go b/internal/oldtls/conn_test.go new file mode 100644 index 0000000..e425f39 --- /dev/null +++ b/internal/oldtls/conn_test.go @@ -0,0 +1,328 @@ +package oldtls + +import ( + "bufio" + "bytes" + "crypto/md5" + "crypto/rand" + "crypto/rsa" + "crypto/sha1" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "encoding/binary" + "hash" + "io" + "math/big" + "net" + "sync" + "testing" + "time" +) + +var ( + certOnce sync.Once + testCert tls.Certificate +) + +func cert(t *testing.T) *tls.Certificate { + t.Helper() + certOnce.Do(func() { + key, err := rsa.GenerateKey(rand.Reader, 2048) + 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 | x509.KeyUsageKeyEncipherment, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}} + der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key) + if err != nil { + t.Fatal(err) + } + testCert = tls.Certificate{Certificate: [][]byte{der}, PrivateKey: key} + }) + return &testCert +} + +// echo serves one connection by oldtls, echoing what it reads; the +// server's error comes on the channel. +func echo(t *testing.T) (string, chan error) { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { ln.Close() }) + c := cert(t) + errs := make(chan error, 1) + go func() { + nc, err := ln.Accept() + if err != nil { + errs <- err + return + } + sc := Server(nc, &Config{GetCertificate: func(*tls.ClientHelloInfo) (*tls.Certificate, error) { return c, nil }}) + defer sc.Close() + sc.SetDeadline(time.Now().Add(10 * time.Second)) + _, err = io.Copy(sc, sc) + errs <- err + }() + return ln.Addr().String(), errs +} + +// TestGoClient: Go's own TLS client, at TLS 1.0, with each suite. +func TestGoClient(t *testing.T) { + for _, id := range []uint16{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} { + t.Run(tls.CipherSuiteName(id), func(t *testing.T) { + addr, errs := echo(t) + c, err := tls.Dial("tcp", addr, &tls.Config{InsecureSkipVerify: true, MinVersion: tls.VersionTLS10, + MaxVersion: tls.VersionTLS10, CipherSuites: []uint16{id}}) + if err != nil { + t.Fatal(err) + } + if st := c.ConnectionState(); st.CipherSuite != id || st.Version != tls.VersionTLS10 { + t.Fatalf("state %+v", st) + } + msg := bytes.Repeat([]byte("ping "), 9000) // more than a record + go c.Write(msg) + got := make([]byte, len(msg)) + if _, err := io.ReadFull(c, got); err != nil || !bytes.Equal(got, msg) { + t.Fatalf("echo: %v", err) + } + c.Close() + if err := <-errs; err != nil { + t.Errorf("server: %v", err) + } + }) + } +} + +// v2Client is a TLS 1.0 client that opens with an SSL 2.0-format hello, +// as AIM 6.2's NSS does. +type v2Client struct { + t *testing.T + nc net.Conn + srv Conn // its record layer, reused for the client's side + hs []byte + finishedOK bool +} + +func v2Hello(suites []uint16, challenge []byte) []byte { + var specs []byte + for _, s := range suites { + specs = append(specs, 0, byte(s>>8), byte(s)) + } + specs = append(specs, 0x01, 0x00, 0x80) // SSL 2.0's RC4_128_WITH_MD5, to be passed over + m := []byte{1, 3, 1} + m = binary.BigEndian.AppendUint16(m, uint16(len(specs))) + m = binary.BigEndian.AppendUint16(m, 0) + m = binary.BigEndian.AppendUint16(m, uint16(len(challenge))) + m = append(append(m, specs...), challenge...) + return append([]byte{0x80 | byte(len(m)>>8), byte(len(m))}, m...) +} + +// handshake runs the client's side: the wrong Finished if badFinished. +func (v *v2Client) handshake(id uint16, badFinished bool) error { + t := v.t + chal := make([]byte, 16) + rand.Read(chal) + hello := v2Hello([]uint16{0x00ff, id}, chal) + c := &v.srv + c.Conn, c.br = v.nc, nil + c.md5h, c.sha1h = newHashes() + c.hash(hello[2:]) + if _, err := v.nc.Write(hello); err != nil { + return err + } + c.br = bufioReader(v.nc) + sh, err := c.readHandshake() + if err != nil { + return err + } + if sh[0] != hsServerHello || binary.BigEndian.Uint16(sh[4:]) != version10 { + t.Fatalf("server hello %x", sh) + } + sr := sh[6:38] + if got := binary.BigEndian.Uint16(sh[39:]); got != id { + t.Fatalf("suite %04x", got) + } + if !bytes.HasSuffix(sh, []byte{0xff, 0x01, 0, 1, 0}) { + t.Errorf("no renegotiation_info: %x", sh) + } + c.hash(sh) + ce, err := c.readHandshake() + if err != nil { + return err + } + c.hash(ce) + pc, err := x509.ParseCertificate(ce[10:]) + if err != nil { + t.Fatal(err) + } + done, err := c.readHandshake() + if err != nil || done[0] != hsServerDone { + t.Fatalf("server hello done %x %v", done, err) + } + c.hash(done) + + pre := make([]byte, 48) + rand.Read(pre) + pre[0], pre[1] = 3, 1 + ct, err := rsa.EncryptPKCS1v15(rand.Reader, pc.PublicKey.(*rsa.PublicKey), pre) + if err != nil { + t.Fatal(err) + } + cke := msg(hsClientKeyExchange, binary.BigEndian.AppendUint16(nil, uint16(len(ct))), ct...) + c.hash(cke) + cr := make([]byte, 32) + copy(cr[16:], chal) + ms := prf10(pre, "master secret", append(append([]byte{}, cr...), sr...), 48) + var s *suite + for i := range suites { + if suites[i].id == id { + s = &suites[i] + } + } + ck, sk := s.keys(ms, cr, sr) + fin := c.finished(ms, "client finished") + if badFinished { + fin[0] ^= 1 + } + finMsg := msg(hsFinished, fin) + c.hash(finMsg) + if err := c.writeRecord(recHandshake, cke); err != nil { + return err + } + if err := c.writeRecord(recCCS, []byte{1}); err != nil { + return err + } + c.out = s.newHalf(ck.mac, ck.key, ck.iv, true) + if err := c.writeRecord(recHandshake, finMsg); err != nil { + return err + } + typ, data, err := c.readRecord() + if err != nil { + return err + } + if typ == recAlert { + return alertIn(data) + } + if typ != recCCS { + t.Fatalf("record %d, not CCS", typ) + } + c.in = s.newHalf(sk.mac, sk.key, sk.iv, false) + sf, err := c.readHandshake() + if err != nil { + return err + } + if !bytes.Equal(sf[4:], c.finished(ms, "server finished")) { + t.Fatalf("server Finished wrong") + } + return nil +} + +// TestSSLv2Hello: a client opening with an SSL 2.0-format hello is served, +// with each suite, and its data echoed. +func TestSSLv2Hello(t *testing.T) { + for _, s := range suites { + t.Run(tls.CipherSuiteName(s.id), func(t *testing.T) { + addr, errs := echo(t) + nc, err := net.Dial("tcp", addr) + if err != nil { + t.Fatal(err) + } + defer nc.Close() + nc.SetDeadline(time.Now().Add(10 * time.Second)) + v := &v2Client{t: t, nc: nc} + if err := v.handshake(s.id, false); err != nil { + t.Fatal(err) + } + c := &v.srv + want := bytes.Repeat([]byte("hello "), 5000) + if err := c.writeRecord(recData, want); err != nil { + t.Fatal(err) + } + var got []byte + for len(got) < len(want) { + typ, data, err := c.readRecord() + if err != nil || typ != recData { + t.Fatalf("record %d: %v", typ, err) + } + got = append(got, data...) + } + if !bytes.Equal(got, want) { + t.Fatal("echo differs") + } + c.sendAlert(levelWarning, alertCloseNotify) + if err := <-errs; err != nil { + t.Errorf("server: %v", err) + } + }) + } +} + +// TestBadFinished: a wrong Finished is refused, with an alert. +func TestBadFinished(t *testing.T) { + addr, errs := echo(t) + nc, err := net.Dial("tcp", addr) + if err != nil { + t.Fatal(err) + } + defer nc.Close() + nc.SetDeadline(time.Now().Add(10 * time.Second)) + v := &v2Client{t: t, nc: nc} + if err := v.handshake(0x002f, true); err == nil { + t.Fatal("handshake passed") + } + if err := <-errs; err == nil { + t.Error("server took it") + } +} + +// TestSSL3Refused: a client offering only SSL 3.0 is refused. +func TestSSL3Refused(t *testing.T) { + addr, errs := echo(t) + nc, err := net.Dial("tcp", addr) + if err != nil { + t.Fatal(err) + } + defer nc.Close() + nc.SetDeadline(time.Now().Add(10 * time.Second)) + h := v2Hello([]uint16{0x002f}, make([]byte, 16)) + h[4] = 0 // version 3.0 + nc.Write(h) + b, _ := io.ReadAll(nc) + if len(b) < 7 || b[0] != recAlert || b[6] != alertProtocolVersion { + t.Errorf("answer %x", b) + } + if err := <-errs; err == nil { + t.Error("server took it") + } +} + +func TestIsSSLv2Hello(t *testing.T) { + if !IsSSLv2Hello(v2Hello([]uint16{0x002f}, make([]byte, 16))) { + t.Error("v2 hello not seen") + } + if IsSSLv2Hello([]byte{0x16, 3, 1, 0, 5}) { + t.Error("a TLS record taken for v2") + } +} + +func TestPRF(t *testing.T) { + // The TLS 1.0 PRF test vector (48 bytes of 0xab secret, 64 of 0xcd + // seed) from the IETF TLS list: its first bytes. + secret := bytes.Repeat([]byte{0xab}, 48) + seed := bytes.Repeat([]byte{0xcd}, 64) + got := prf10(secret, "PRF Testvector", seed, 104) + want := []byte{0xd3, 0xd4, 0xd1, 0xe3, 0x49, 0xb5, 0xd5, 0x15} + if !bytes.Equal(got[:8], want) { + t.Errorf("prf %x", got[:8]) + } +} + +func newHashes() (hash.Hash, hash.Hash) { return md5.New(), sha1.New() } + +func bufioReader(c net.Conn) *bufio.Reader { return bufio.NewReader(c) } diff --git a/internal/oldtls/record.go b/internal/oldtls/record.go new file mode 100644 index 0000000..f5c98b7 --- /dev/null +++ b/internal/oldtls/record.go @@ -0,0 +1,173 @@ +package oldtls + +import ( + "crypto/aes" + "crypto/cipher" + "crypto/des" + "crypto/hmac" + "crypto/md5" + "crypto/rc4" + "crypto/sha1" + "encoding/binary" + "hash" +) + +// suite is a cipher suite: RSA key exchange, then a block cipher in CBC or +// RC4, with an HMAC. +type suite struct { + id uint16 + keyLen, ivLen int // ivLen 0: RC4 + macLen int + block func(key []byte) (cipher.Block, error) + hash func() hash.Hash +} + +// suites are those served, the best first. +var suites = []suite{ + {0x002f, 16, 16, 20, aes.NewCipher, sha1.New}, // TLS_RSA_WITH_AES_128_CBC_SHA + {0x0035, 32, 16, 20, aes.NewCipher, sha1.New}, // TLS_RSA_WITH_AES_256_CBC_SHA + {0x000a, 24, 8, 20, des.NewTripleDESCipher, sha1.New}, // TLS_RSA_WITH_3DES_EDE_CBC_SHA + {0x0005, 16, 0, 20, nil, sha1.New}, // TLS_RSA_WITH_RC4_128_SHA + {0x0004, 16, 0, 16, nil, md5.New}, // TLS_RSA_WITH_RC4_128_MD5 +} + +// half is one direction of the record layer: none (mac nil) until the +// ChangeCipherSpec, then a cipher and MAC. +type half struct { + seq uint64 + mac hash.Hash + block cipher.BlockMode // CBC; its IV chains from record to record, as TLS 1.0's does + stream cipher.Stream // or RC4 +} + +// newHalf is a direction's protection from its keys (enc: the sending +// side). +func (s *suite) newHalf(mac, key, iv []byte, enc bool) half { + h := half{mac: hmac.New(s.hash, mac)} + if s.ivLen == 0 { + r, _ := rc4.NewCipher(key) + h.stream = r + return h + } + b, _ := s.block(key) + if enc { + h.block = cipher.NewCBCEncrypter(b, iv) + } else { + h.block = cipher.NewCBCDecrypter(b, iv) + } + return h +} + +func (h *half) macOf(typ uint8, data []byte) []byte { + var hdr [13]byte + binary.BigEndian.PutUint64(hdr[:], h.seq) + hdr[8] = typ + binary.BigEndian.PutUint16(hdr[9:], version10) + binary.BigEndian.PutUint16(hdr[11:], uint16(len(data))) + h.mac.Reset() + h.mac.Write(hdr[:]) + h.mac.Write(data) + return h.mac.Sum(nil) +} + +// seal is a record of plain (at most maxPlain bytes). +func (h *half) seal(typ uint8, plain []byte) []byte { + out := make([]byte, 5, 5+len(plain)+64) + out[0] = typ + binary.BigEndian.PutUint16(out[1:], version10) + if h.mac == nil { + out = append(out, plain...) + } else { + body := append(append(make([]byte, 0, len(plain)+64), plain...), h.macOf(typ, plain)...) + h.seq++ + if h.block != nil { + bs := h.block.BlockSize() + n := (bs - (len(body)+1)%bs) % bs + for range n + 1 { + body = append(body, byte(n)) + } + h.block.CryptBlocks(body, body) + } else { + h.stream.XORKeyStream(body, body) + } + out = append(out, body...) + } + binary.BigEndian.PutUint16(out[3:], uint16(len(out)-5)) + return out +} + +// open is a record's plaintext, in place; ok false: its MAC or padding is +// wrong. A bad padding is still MACed, so the two fail alike. +func (h *half) open(typ uint8, body []byte) (plain []byte, ok bool) { + if h.mac == nil { + return body, true + } + ms := h.mac.Size() + defer func() { h.seq++ }() + if h.stream != nil { + h.stream.XORKeyStream(body, body) + if len(body) < ms { + return nil, false + } + n := len(body) - ms + return body[:n], hmac.Equal(h.macOf(typ, body[:n]), body[n:]) + } + bs := h.block.BlockSize() + if len(body)%bs != 0 || len(body) < ms+1 { + return nil, false + } + h.block.CryptBlocks(body, body) + pad := int(body[len(body)-1]) + good := true + if pad+1+ms > len(body) { + good, pad = false, 0 + } + for _, b := range body[len(body)-1-pad : len(body)-1] { + if b != byte(pad) { + good = false + } + } + n := len(body) - 1 - pad - ms + macOK := hmac.Equal(h.macOf(typ, body[:n]), body[n:n+ms]) + return body[:n], macOK && good +} + +// prf10 is TLS 1.0's PRF: P_MD5 over the secret's first half, XORed with +// P_SHA1 over its second. +func prf10(secret []byte, label string, seed []byte, n int) []byte { + ls := append([]byte(label), seed...) + s1, s2 := secret[:(len(secret)+1)/2], secret[len(secret)/2:] + out, b := make([]byte, n), make([]byte, n) + pHash(out, s1, ls, md5.New) + pHash(b, s2, ls, sha1.New) + for i := range out { + out[i] ^= b[i] + } + return out +} + +func pHash(out, secret, seed []byte, h func() hash.Hash) { + m := hmac.New(h, secret) + m.Write(seed) + a := m.Sum(nil) + for j := 0; j < len(out); { + m.Reset() + m.Write(a) + m.Write(seed) + j += copy(out[j:], m.Sum(nil)) + m.Reset() + m.Write(a) + a = m.Sum(nil) + } +} + +// keys are a session's client and server protection, from its master +// secret and randoms. +func (s *suite) keys(ms, cr, sr []byte) (client, server struct{ mac, key, iv []byte }) { + kb := prf10(ms, "key expansion", append(append([]byte{}, sr...), cr...), 2*(s.macLen+s.keyLen+s.ivLen)) + take := func(n int) []byte { v := kb[:n]; kb = kb[n:]; return v } + client.mac, server.mac = take(s.macLen), take(s.macLen) + client.key, server.key = take(s.keyLen), take(s.keyLen) + client.iv, server.iv = take(s.ivLen), take(s.ivLen) + return +} diff --git a/internal/oscar/server.go b/internal/oscar/server.go index 3a60aff..8a2f15c 100644 --- a/internal/oscar/server.go +++ b/internal/oscar/server.go @@ -15,6 +15,7 @@ import ( "bufio" "context" "crypto/rand" + "crypto/rsa" "crypto/tls" "errors" "fmt" @@ -26,6 +27,7 @@ import ( "github.com/D-Modem/bbs/internal/bbs" "github.com/D-Modem/bbs/internal/certs" + "github.com/D-Modem/bbs/internal/oldtls" "github.com/D-Modem/bbs/internal/sockets" "github.com/D-Modem/bbs/internal/store" "github.com/D-Modem/bbs/internal/tcpserv" @@ -132,11 +134,29 @@ func (s *Server) Serve(ctx context.Context, ln net.Listener) error { if err != nil { return fmt.Errorf("oscar: %w", err) } + if c, err := src.GetCertificate(&tls.ClientHelloInfo{}); err == nil { + if _, ok := c.PrivateKey.(*rsa.PrivateKey); !ok { + s.B.Log.Printf("oscar: tls_cert's key is not RSA: AIM 6.2 to 7.5 can't sign on by TLS") + } + } 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)) + c.SetDeadline(time.Now().Add(loginTimeout)) + r := bufio.NewReader(c) + first, err := r.Peek(3) + if err != nil { + return + } + var tc interface { + net.Conn + Handshake() error + } + if oldtls.IsSSLv2Hello(first) { // AIM 6.2 to 7.5, which crypto/tls can't take + tc = oldtls.Server(&peeked{c, r}, &oldtls.Config{GetCertificate: src.GetCertificate}) + } else { + tc = tls.Server(&peeked{c, r}, cfg) + } if err := tc.Handshake(); err != nil { s.B.Log.Printf("oscar: %s: TLS: %v", c.RemoteAddr(), err) return diff --git a/internal/oscar/web_test.go b/internal/oscar/web_test.go index 4b9b660..e7ea96f 100644 --- a/internal/oscar/web_test.go +++ b/internal/oscar/web_test.go @@ -1,9 +1,8 @@ package oscar import ( - "crypto/ecdsa" - "crypto/elliptic" "crypto/rand" + "crypto/rsa" "crypto/tls" "crypto/x509" "crypto/x509/pkix" @@ -198,23 +197,23 @@ func TestKerberos(t *testing.T) { // 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) + key, err := rsa.GenerateKey(rand.Reader, 2048) // RSA, as TLS 1.0's RSA key exchange needs 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, + NotAfter: time.Now().Add(time.Hour), KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment, 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) + kb := x509.MarshalPKCS1PrivateKey(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) + os.WriteFile(kf, pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: kb}), 0o600) return crt, kf } @@ -259,3 +258,28 @@ func TestKerberosTLS(t *testing.T) { t.Errorf("service %v", res) } } + +// TestSSLv2HelloTLS: a TLS hello in SSL 2.0's format, as AIM 6.2 to 7.5 +// send it, is answered with TLS 1.0's ServerHello on the TLS port. +func TestSSLv2HelloTLS(t *testing.T) { + crt, key := selfSigned(t) + tlsAddr := freeAddr(t) + start(t, func(s *Settings) { s.TLSAddress, s.TLSCert, s.TLSKey = tlsAddr, crt, key }) + c, err := net.Dial("tcp", tlsAddr) + if err != nil { + t.Fatal(err) + } + defer c.Close() + c.SetDeadline(time.Now().Add(5 * time.Second)) + // CLIENT-HELLO, version 3.1: TLS_RSA_WITH_AES_128_CBC_SHA, a 16-byte challenge + m := []byte{1, 3, 1, 0, 3, 0, 0, 0, 16, 0, 0x00, 0x2f} + m = append(m, make([]byte, 16)...) + c.Write(append([]byte{0x80, byte(len(m))}, m...)) + var h [10]byte + if _, err := io.ReadFull(c, h[:]); err != nil { + t.Fatal(err) + } + if h[0] != 22 || h[1] != 3 || h[2] != 1 || h[5] != 2 { + t.Errorf("answer %x", h) + } +}