Просмотр исходного кода

server: recover per-connection panics and length-check TLV getters

Mike 1 день назад
Родитель
Сommit
3c82d500d9
6 измененных файлов с 124 добавлено и 29 удалено
  1. 2 3
      foodgroup/auth.go
  2. 16 0
      server/icq_legacy/server.go
  3. 20 1
      server/oscar/server.go
  4. 38 12
      server/toc/server.go
  5. 20 4
      wire/tlv.go
  6. 28 9
      wire/tlv_test.go

+ 2 - 3
foodgroup/auth.go

@@ -3,7 +3,6 @@ package foodgroup
 import (
 	"bytes"
 	"context"
-	"encoding/binary"
 	"encoding/xml"
 	"errors"
 	"fmt"
@@ -516,8 +515,8 @@ func (l *loginProperties) fromTLV(list wire.TLVList) error {
 	}
 
 	l.tokenTTL = state.DefaultCookieTTL
-	if b, found := list.Bytes(wire.LoginTLVTagsTokenTTL); found {
-		ttl := time.Duration(binary.BigEndian.Uint32(b)) * time.Second
+	if seconds, found := list.Uint32BE(wire.LoginTLVTagsTokenTTL); found {
+		ttl := time.Duration(seconds) * time.Second
 		if ttl <= 0 || ttl > maxTokenTTL {
 			return errInvalidTokenTTL
 		}

+ 16 - 0
server/icq_legacy/server.go

@@ -6,6 +6,7 @@ import (
 	"fmt"
 	"log/slog"
 	"net"
+	"runtime/debug"
 	"sync"
 	"time"
 
@@ -23,8 +24,17 @@ const (
 var (
 	ErrServerClosed     = errors.New("server closed")
 	ErrUnsupportedProto = errors.New("unsupported protocol version")
+
+	// errPanic wraps a value recovered from a panic while handling a packet
+	errPanic = errors.New("recovered from panic")
 )
 
+// panicError wraps a recovered panic value as an error annotated with the stack
+// trace at the point of recovery.
+func panicError(r any) error {
+	return fmt.Errorf("%w: %v\n%s", errPanic, r, debug.Stack())
+}
+
 // LegacyServer handles legacy ICQ protocol connections over UDP
 type LegacyServer struct {
 	conn       *net.UDPConn
@@ -186,6 +196,12 @@ func (s *LegacyServer) receiveLoop(ctx context.Context) {
 
 // handlePacket processes a single incoming packet
 func (s *LegacyServer) handlePacket(addr *net.UDPAddr, packet []byte) {
+	defer func() {
+		if r := recover(); r != nil {
+			s.logger.Error("recovered from panic handling packet", "err", panicError(r), "addr", addr)
+		}
+	}()
+
 	// Detect protocol version
 	version, err := DetectProtocolVersion(packet)
 	if err != nil {

+ 20 - 1
server/oscar/server.go

@@ -10,6 +10,7 @@ import (
 	"net"
 	"net/netip"
 	"os"
+	"runtime/debug"
 	"sync"
 	"time"
 
@@ -205,6 +206,15 @@ func (s *Server) acceptLoop(ln net.Listener, endpointCfg config.Endpoint) {
 // down.
 var ErrServerClosed = errors.New("OSCAR server closed")
 
+// errPanic wraps a value recovered from a panic while handling a connection.
+var errPanic = errors.New("recovered from panic")
+
+// panicError wraps a recovered panic value as an error annotated with the stack
+// trace at the point of recovery.
+func panicError(r any) error {
+	return fmt.Errorf("%w: %v\n%s", errPanic, r, debug.Stack())
+}
+
 // ServeConn serves a connection that didn't come from one of the server's
 // listeners, such as an in-memory connection opened by the TOC server, as if
 // it had arrived on the plain listener of the server's first listener group.
@@ -236,6 +246,10 @@ func (s *Server) trackConn(conn net.Conn) bool {
 
 func (s *Server) handleConnection(ctx context.Context, conn net.Conn, endpointCfg config.Endpoint) {
 	defer func() {
+		if r := recover(); r != nil {
+			s.logger.ErrorContext(ctx, "recovered from panic in connection handler", "err", panicError(r))
+		}
+
 		// untrack connections
 		s.connMu.Lock()
 		delete(s.conns, conn)
@@ -521,7 +535,7 @@ func (s oscarServer) authenticate(ctx context.Context, flap wire.FLAPSignonFrame
 	// presence of the roasted password TLV, however that proved an unreliable
 	// indicator of FLAP-auth because older ICQ clients appear to omit the
 	// roasted password TLV when the password is not stored client-side.
-	if _, hasScreenName := flap.Uint16BE(wire.LoginTLVTagsScreenName); hasScreenName {
+	if flap.HasTag(wire.LoginTLVTagsScreenName) {
 		return s.processFLAPAuth(ctx, flap, flapc, endpointCfg)
 	}
 
@@ -654,6 +668,11 @@ func (s oscarServer) dispatchIncomingMessages(
 	go func() {
 		defer close(msgCh)
 		defer close(errCh)
+		defer func() {
+			if r := recover(); r != nil {
+				errCh <- panicError(r)
+			}
+		}()
 
 		for {
 			frame := wire.FLAPFrame{}

+ 38 - 12
server/toc/server.go

@@ -10,6 +10,7 @@ import (
 	"log/slog"
 	"net"
 	"net/http"
+	"runtime/debug"
 	"sync"
 	"syscall"
 	"time"
@@ -18,6 +19,7 @@ import (
 	"golang.org/x/sync/errgroup"
 	"golang.org/x/time/rate"
 
+	"github.com/mk6i/open-oscar-server/server/oscar/middleware"
 	"github.com/mk6i/open-oscar-server/wire"
 )
 
@@ -30,14 +32,21 @@ var (
 
 	// errTOCProcessing indicates that an error occurred in the TOC handler
 	errTOCProcessing = errors.New("failed to process TOC request")
-)
-
-type contextKey string
 
-const (
-	screenNameContextKey contextKey = "screenName"
+	// errPanic wraps a value recovered from a panic while handling a connection
+	errPanic = errors.New("recovered from panic")
 )
 
+// catchPanic recovers an in-flight panic into *err, joined with any error
+// already there, so a panic while handling untrusted input drops the session
+// rather than the whole process. Defer it directly (defer catchPanic(&err));
+// wrapping it in another deferred closure stops recover from seeing the panic.
+func catchPanic(err *error) {
+	if r := recover(); r != nil {
+		*err = errors.Join(*err, fmt.Errorf("%w: %v\n%s", errPanic, r, debug.Stack()))
+	}
+}
+
 // bufferedConn is a wrapper around net.Conn that allows peeking into the
 // incoming connection without consuming data. It is useful for multiplexing
 // TOC/HTTP and TOC/FLAP connections.
@@ -264,8 +273,13 @@ func (s *Server) acceptLoop(ctx context.Context, ln net.Listener, httpCh chan ne
 		}
 
 		go func() {
+			ctx := middleware.WithIP(ctx, conn.RemoteAddr().String())
 			if err := s.handleConnection(conn, ctx, httpCh); err != nil {
-				s.logger.InfoContext(ctx, "user session failed", "err", err.Error())
+				if errors.Is(err, errPanic) {
+					s.logger.ErrorContext(ctx, "recovered from panic in connection handler", "err", err.Error())
+				} else {
+					s.logger.InfoContext(ctx, "user session failed", "err", err.Error())
+				}
 			}
 		}()
 	}
@@ -274,7 +288,9 @@ func (s *Server) acceptLoop(ctx context.Context, ln net.Listener, httpCh chan ne
 // handleConnection inspects and routes an incoming connection. If the connection
 // starts with "FLAP", handle as TOC/FLAP; otherwise, dispatch for HTTP
 // processing.
-func (s *Server) handleConnection(conn net.Conn, ctx context.Context, httpCh chan net.Conn) error {
+func (s *Server) handleConnection(conn net.Conn, ctx context.Context, httpCh chan net.Conn) (err error) {
+	defer catchPanic(&err)
+
 	bufCon := newBufferedConn(conn)
 
 	doFlap := "FLAP"
@@ -342,8 +358,13 @@ func (s *Server) dispatchFLAP(ctx context.Context, conn net.Conn) error {
 	// the group runs every goroutine of the TOC session, starting with the
 	// BOS connection's reader during signon
 	g, ctx := errgroup.WithContext(ctx)
-	goAsync := func(f func(ctx context.Context) error) {
-		g.Go(func() error { return f(ctx) })
+	// launch f on g with a panic net, so a panic while handling untrusted input
+	// drops the session rather than the whole process
+	goAsync := func(f func(context.Context) error) {
+		g.Go(func() (err error) {
+			defer catchPanic(&err)
+			return f(ctx)
+		})
 	}
 
 	me, err := s.login(ctx, clientFlap, conn.RemoteAddr(), goAsync)
@@ -356,7 +377,7 @@ func (s *Server) dispatchFLAP(ctx context.Context, conn net.Conn) error {
 		return nil // signon failed
 	}
 
-	ctx = context.WithValue(ctx, screenNameContextKey, me.IdentScreenName())
+	ctx = middleware.WithScreenName(ctx, me.IdentScreenName())
 
 	return s.handleTOCRequest(ctx, g, closeConn, me, clientFlap)
 }
@@ -380,8 +401,13 @@ func (s *Server) handleTOCRequest(
 	msgCh := make(chan []string, 1)
 
 	me.toCh = msgCh
-	me.goAsync = func(f func(ctx context.Context) error) {
-		g.Go(func() error { return f(ctx) })
+	// launch f on g with a panic net, so a panic while handling untrusted input
+	// drops the session rather than the whole process
+	me.goAsync = func(f func(context.Context) error) {
+		g.Go(func() (err error) {
+			defer catchPanic(&err)
+			return f(ctx)
+		})
 	}
 
 	// process TOC client requests and enqueue TOC server responses

+ 20 - 4
wire/tlv.go

@@ -44,23 +44,39 @@ func (t TLV) Uint8() uint8 {
 	return 0
 }
 
-// Uint16LE returns a uint16 little-endian representation of the TLV.
+// Uint16LE returns a uint16 little-endian representation of the TLV. It returns
+// 0 if the value is shorter than 2 bytes.
 func (t TLV) Uint16LE() uint16 {
+	if len(t.Value) < 2 {
+		return 0
+	}
 	return binary.LittleEndian.Uint16(t.Value)
 }
 
-// Uint16BE returns a uint16 big-endian representation of the TLV.
+// Uint16BE returns a uint16 big-endian representation of the TLV. It returns 0
+// if the value is shorter than 2 bytes.
 func (t TLV) Uint16BE() uint16 {
+	if len(t.Value) < 2 {
+		return 0
+	}
 	return binary.BigEndian.Uint16(t.Value)
 }
 
-// Uint32LE returns a uint32 little-endian representation of the TLV.
+// Uint32LE returns a uint32 little-endian representation of the TLV. It returns
+// 0 if the value is shorter than 4 bytes.
 func (t TLV) Uint32LE() uint32 {
+	if len(t.Value) < 4 {
+		return 0
+	}
 	return binary.LittleEndian.Uint32(t.Value)
 }
 
-// Uint32BE returns a uint32 big-endian representation of the TLV.
+// Uint32BE returns a uint32 big-endian representation of the TLV. It returns 0
+// if the value is shorter than 4 bytes.
 func (t TLV) Uint32BE() uint32 {
+	if len(t.Value) < 4 {
+		return 0
+	}
 	return binary.BigEndian.Uint32(t.Value)
 }
 

+ 28 - 9
wire/tlv_test.go

@@ -84,7 +84,6 @@ func TestTLVList_Getters(t *testing.T) {
 		lookup func(TLVList) (any, bool)
 		expect any
 		found  bool
-		panic  bool
 	}{
 		{
 			name: "given a TLV of big-endian uint32, expect found value",
@@ -269,7 +268,7 @@ func TestTLVList_Getters(t *testing.T) {
 			found:  false,
 		},
 		{
-			name: "expect a panic when there's a type mismatch between big-endian uint16 and uint32",
+			name: "given a big-endian value too short for uint32, expect zero value",
 			given: []TLV{
 				NewTLVBE(0, uint16(12)),
 				NewTLVBE(1, uint16(34)),
@@ -278,10 +277,11 @@ func TestTLVList_Getters(t *testing.T) {
 			lookup: func(l TLVList) (any, bool) {
 				return l.Uint32BE(1)
 			},
-			panic: true,
+			expect: uint32(0),
+			found:  true,
 		},
 		{
-			name: "expect a panic when there's a type mismatch between little-endian uint16 and uint32",
+			name: "given a little-endian value too short for uint32, expect zero value",
 			given: []TLV{
 				NewTLVLE(0, uint16(12)),
 				NewTLVLE(1, uint16(34)),
@@ -290,7 +290,30 @@ func TestTLVList_Getters(t *testing.T) {
 			lookup: func(l TLVList) (any, bool) {
 				return l.Uint32LE(1)
 			},
-			panic: true,
+			expect: uint32(0),
+			found:  true,
+		},
+		{
+			name: "given a big-endian value too short for uint16, expect zero value",
+			given: []TLV{
+				NewTLVBE(1, uint8(34)),
+			},
+			lookup: func(l TLVList) (any, bool) {
+				return l.Uint16BE(1)
+			},
+			expect: uint16(0),
+			found:  true,
+		},
+		{
+			name: "given a little-endian value too short for uint16, expect zero value",
+			given: []TLV{
+				NewTLVLE(1, uint8(34)),
+			},
+			lookup: func(l TLVList) (any, bool) {
+				return l.Uint16LE(1)
+			},
+			expect: uint16(0),
+			found:  true,
 		},
 		{
 			name: "given a TLV of big-endian uint16 slice, expect found value",
@@ -317,10 +340,6 @@ func TestTLVList_Getters(t *testing.T) {
 	}
 	for _, tt := range tests {
 		t.Run(tt.name, func(t *testing.T) {
-			if tt.panic {
-				assert.Panics(t, func() { tt.lookup(tt.given) })
-				return
-			}
 			have, found := tt.lookup(tt.given)
 			assert.Equal(t, tt.expect, have)
 			assert.Equal(t, tt.found, found)