From 83f903569da12b5468d3b3e7466a4899a4c917dd Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 13:10:58 +0000 Subject: [PATCH 1/2] Use retrossl in place of internal/oldtls The TLS 1.0 server for SSL 2.0-format hellos moved to D-Modem/retrossl, which also serves SSL 3.0. The OSCAR TLS port now sends SSL 3.0-only clients there too; the shared ports still send only SSL 2.0-format hellos, to the route that takes them. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01B82eRRH4kntyPfrY1bFWC3 --- docs/wiki/AIM-and-ICQ.md | 5 +- go.mod | 1 + go.sum | 2 + internal/oldtls/conn.go | 566 ----------------------------------- internal/oldtls/conn_test.go | 328 -------------------- internal/oldtls/record.go | 173 ----------- internal/oscar/server.go | 10 +- internal/vhost/vhost.go | 8 +- 8 files changed, 17 insertions(+), 1076 deletions(-) delete mode 100644 internal/oldtls/conn.go delete mode 100644 internal/oldtls/conn_test.go delete mode 100644 internal/oldtls/record.go diff --git a/docs/wiki/AIM-and-ICQ.md b/docs/wiki/AIM-and-ICQ.md index 0a29d6a..32859e1 100644 --- a/docs/wiki/AIM-and-ICQ.md +++ b/docs/wiki/AIM-and-ICQ.md @@ -127,8 +127,9 @@ five minutes. 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 +answers those clients with [retrossl](https://github.com/D-Modem/retrossl), +D-Modem's SSL 3.0 and TLS 1.0 server (AES, 3DES, RC4 or DES, by RSA), as it +does clients that offer only SSL 3.0; 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. diff --git a/go.mod b/go.mod index 0b2136b..29728d1 100644 --- a/go.mod +++ b/go.mod @@ -8,6 +8,7 @@ require ( blitiri.com.ar/go/spf v1.5.1 github.com/D-Modem/go3270 v0.9.14-0.20261105104944-a6550eb72c38 github.com/D-Modem/menu v0.0.0-20261106031303-853189d86fb2 + github.com/D-Modem/retrossl v0.0.0-20261111130219-1b844ee3e801 github.com/coder/websocket v1.8.13 github.com/dop251/goja v0.0.0-20260603125802-cfe4039cb6d7 github.com/emersion/go-imap/v2 v2.0.0-beta.8 diff --git a/go.sum b/go.sum index 8036ff8..e312bc1 100644 --- a/go.sum +++ b/go.sum @@ -6,6 +6,8 @@ github.com/D-Modem/go3270 v0.9.14-0.20261105104944-a6550eb72c38 h1:fHnFrNziFJico github.com/D-Modem/go3270 v0.9.14-0.20261105104944-a6550eb72c38/go.mod h1:WgdusPrfmqSMltzVXhywre6YHt9XHsKhfo9nWidkoUA= github.com/D-Modem/menu v0.0.0-20261106031303-853189d86fb2 h1:D7hJgxHbKQzr8850CdRuDIokcgcGOSlN1zGsh/ZuZqg= github.com/D-Modem/menu v0.0.0-20261106031303-853189d86fb2/go.mod h1:A+lNApUdQ5HSXW07R5aRm97MkhHYTQ1DkN0m+Vgorwg= +github.com/D-Modem/retrossl v0.0.0-20261111130219-1b844ee3e801 h1:QsbvUo6CAawdQTChTwd5wFMS7g2bYMoVL6d1OxnLFdI= +github.com/D-Modem/retrossl v0.0.0-20261111130219-1b844ee3e801/go.mod h1:+/qpHsaYk4DslA351ZMumscq9/Iwl/K5vS4PhUVLOR8= github.com/Masterminds/semver/v3 v3.2.1 h1:RN9w6+7QoMeJVGyfmbcgs28Br8cvmnucEXnY0rYXWg0= github.com/Masterminds/semver/v3 v3.2.1/go.mod h1:qvl/7zhW3nngYb5+80sSMF+FG2BjYrf8m9wsX0PNOMQ= github.com/alexbrainman/sspi v0.0.0-20180613141037-e580b900e9f5 h1:P5U+E4x5OkVEKQDklVPmzs71WM56RTTRqV4OrDC//Y4= diff --git a/internal/oldtls/conn.go b/internal/oldtls/conn.go deleted file mode 100644 index e6d45ff..0000000 --- a/internal/oldtls/conn.go +++ /dev/null @@ -1,566 +0,0 @@ -// 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 deleted file mode 100644 index e425f39..0000000 --- a/internal/oldtls/conn_test.go +++ /dev/null @@ -1,328 +0,0 @@ -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 deleted file mode 100644 index f5c98b7..0000000 --- a/internal/oldtls/record.go +++ /dev/null @@ -1,173 +0,0 @@ -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 eef052a..993a1a1 100644 --- a/internal/oscar/server.go +++ b/internal/oscar/server.go @@ -27,11 +27,11 @@ 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" "github.com/D-Modem/bbs/internal/vhost" + "github.com/D-Modem/retrossl" ) // timeouts @@ -147,7 +147,7 @@ func (s *Server) Serve(ctx context.Context, ln net.Listener) error { Refuse: refuse, Handle: func(c net.Conn) { c.SetDeadline(time.Now().Add(loginTimeout)) r := bufio.NewReader(c) - first, err := r.Peek(3) + old, err := retrossl.Sniff(r) if err != nil { return } @@ -155,8 +155,10 @@ func (s *Server) Serve(ctx context.Context, ln net.Listener) error { 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}) + // AIM 6.2 to 7.5 (an SSL 2.0-format hello) and SSL 3.0-only + // clients, which crypto/tls can't take + if old { + tc = retrossl.Server(&peeked{c, r}, &retrossl.Config{GetCertificate: src.GetCertificate}) } else { tc = tls.Server(&peeked{c, r}, cfg) } diff --git a/internal/vhost/vhost.go b/internal/vhost/vhost.go index 400ee57..5247169 100644 --- a/internal/vhost/vhost.go +++ b/internal/vhost/vhost.go @@ -28,8 +28,8 @@ import ( "time" "github.com/D-Modem/bbs/internal/certs" - "github.com/D-Modem/bbs/internal/oldtls" "github.com/D-Modem/bbs/internal/tcpserv" + "github.com/D-Modem/retrossl" ) // Route is one front end's part of a shared port. @@ -107,13 +107,15 @@ func (p *Port) Handle(c net.Conn) { net.Conn Handshake() error } - if oldtls.IsSSLv2Hello(first) { + // Three bytes tell an SSL 2.0-format hello, which only the route + // for AIM 6.2 to 7.5 takes; everything else is crypto/tls's. + if retrossl.Wants(first) { rt := p.sslv2() if rt == nil { p.logf("%s: an SSL 2.0-format hello, which nothing here takes", c.RemoteAddr()) return } - tc = oldtls.Server(&peeked{c, r}, &oldtls.Config{GetCertificate: rt.Cert}) + tc = retrossl.Server(&peeked{c, r}, &retrossl.Config{GetCertificate: rt.Cert}) } else { tc = tls.Server(&peeked{c, r}, legacyTLS(p.certificate)) } From 730bbea88bc79f0aa00dd3a7f0f759b3be5e1aa1 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 13:26:47 +0000 Subject: [PATCH 2/2] Keep retrossl sessions for old clients to resume retrossl now resumes sessions; give the OSCAR and shared ports a cache, which spares old machines an RSA operation on every connection. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01B82eRRH4kntyPfrY1bFWC3 --- go.mod | 2 +- go.sum | 4 ++-- internal/oscar/server.go | 6 +++++- internal/vhost/vhost.go | 6 +++++- 4 files changed, 13 insertions(+), 5 deletions(-) diff --git a/go.mod b/go.mod index 29728d1..1e21562 100644 --- a/go.mod +++ b/go.mod @@ -8,7 +8,7 @@ require ( blitiri.com.ar/go/spf v1.5.1 github.com/D-Modem/go3270 v0.9.14-0.20261105104944-a6550eb72c38 github.com/D-Modem/menu v0.0.0-20261106031303-853189d86fb2 - github.com/D-Modem/retrossl v0.0.0-20261111130219-1b844ee3e801 + github.com/D-Modem/retrossl v0.0.0-20261111132527-5c74d8027d9e github.com/coder/websocket v1.8.13 github.com/dop251/goja v0.0.0-20260603125802-cfe4039cb6d7 github.com/emersion/go-imap/v2 v2.0.0-beta.8 diff --git a/go.sum b/go.sum index e312bc1..f5e97a5 100644 --- a/go.sum +++ b/go.sum @@ -6,8 +6,8 @@ github.com/D-Modem/go3270 v0.9.14-0.20261105104944-a6550eb72c38 h1:fHnFrNziFJico github.com/D-Modem/go3270 v0.9.14-0.20261105104944-a6550eb72c38/go.mod h1:WgdusPrfmqSMltzVXhywre6YHt9XHsKhfo9nWidkoUA= github.com/D-Modem/menu v0.0.0-20261106031303-853189d86fb2 h1:D7hJgxHbKQzr8850CdRuDIokcgcGOSlN1zGsh/ZuZqg= github.com/D-Modem/menu v0.0.0-20261106031303-853189d86fb2/go.mod h1:A+lNApUdQ5HSXW07R5aRm97MkhHYTQ1DkN0m+Vgorwg= -github.com/D-Modem/retrossl v0.0.0-20261111130219-1b844ee3e801 h1:QsbvUo6CAawdQTChTwd5wFMS7g2bYMoVL6d1OxnLFdI= -github.com/D-Modem/retrossl v0.0.0-20261111130219-1b844ee3e801/go.mod h1:+/qpHsaYk4DslA351ZMumscq9/Iwl/K5vS4PhUVLOR8= +github.com/D-Modem/retrossl v0.0.0-20261111132527-5c74d8027d9e h1:4v6nEr6aSiE8H/RmTpg29q+P/RFvjzUlnTFRCdvu8XQ= +github.com/D-Modem/retrossl v0.0.0-20261111132527-5c74d8027d9e/go.mod h1:+/qpHsaYk4DslA351ZMumscq9/Iwl/K5vS4PhUVLOR8= github.com/Masterminds/semver/v3 v3.2.1 h1:RN9w6+7QoMeJVGyfmbcgs28Br8cvmnucEXnY0rYXWg0= github.com/Masterminds/semver/v3 v3.2.1/go.mod h1:qvl/7zhW3nngYb5+80sSMF+FG2BjYrf8m9wsX0PNOMQ= github.com/alexbrainman/sspi v0.0.0-20180613141037-e580b900e9f5 h1:P5U+E4x5OkVEKQDklVPmzs71WM56RTTRqV4OrDC//Y4= diff --git a/internal/oscar/server.go b/internal/oscar/server.go index 993a1a1..49af4dc 100644 --- a/internal/oscar/server.go +++ b/internal/oscar/server.go @@ -158,7 +158,7 @@ func (s *Server) Serve(ctx context.Context, ln net.Listener) error { // AIM 6.2 to 7.5 (an SSL 2.0-format hello) and SSL 3.0-only // clients, which crypto/tls can't take if old { - tc = retrossl.Server(&peeked{c, r}, &retrossl.Config{GetCertificate: src.GetCertificate}) + tc = retrossl.Server(&peeked{c, r}, &retrossl.Config{GetCertificate: src.GetCertificate, SessionCache: oldSessions}) } else { tc = tls.Server(&peeked{c, r}, cfg) } @@ -180,6 +180,10 @@ func (s *Server) Serve(ctx context.Context, ln net.Listener) error { return err } +// oldSessions are the TLS sessions of clients served by retrossl, kept +// for them to resume. +var oldSessions = retrossl.NewSessionCache(0, 0) + // Clients is how many sessions are signed on. func (s *Server) Clients() int { s.mu.Lock() diff --git a/internal/vhost/vhost.go b/internal/vhost/vhost.go index 5247169..121f350 100644 --- a/internal/vhost/vhost.go +++ b/internal/vhost/vhost.go @@ -115,7 +115,7 @@ func (p *Port) Handle(c net.Conn) { p.logf("%s: an SSL 2.0-format hello, which nothing here takes", c.RemoteAddr()) return } - tc = retrossl.Server(&peeked{c, r}, &retrossl.Config{GetCertificate: rt.Cert}) + tc = retrossl.Server(&peeked{c, r}, &retrossl.Config{GetCertificate: rt.Cert, SessionCache: oldSessions}) } else { tc = tls.Server(&peeked{c, r}, legacyTLS(p.certificate)) } @@ -233,6 +233,10 @@ func (p *Port) certificate(hello *tls.ClientHelloInfo) (*tls.Certificate, error) return nil, errors.New("no certificate") } +// oldSessions are the sessions of clients served by retrossl, kept for +// them to resume (each goes only with its own certificate). +var oldSessions = retrossl.NewSessionCache(0, 0) + func (p *Port) sslv2() *Route { for _, rt := range p.Routes { if rt.SSLv2 && rt.Cert != nil {