You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@plc4x.apache.org by sr...@apache.org on 2026/08/18 08:59:11 UTC

(plc4x) 01/05: fix(plc4go): harden shared codegen and transport runtime against hostile wire input

This is an automated email from the ASF dual-hosted git repository.

sruehl pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/plc4x.git

commit 2b947b5dbc6572d96db08a68938ad2a5ef4082c4
Author: Sebastian Rühl <sr...@apache.org>
AuthorDate: Tue Aug 18 10:03:38 2026 +0200

    fix(plc4go): harden shared codegen and transport runtime against hostile wire input
    
    Ports the Java runtime's allocate-after-validate hardening to the Go spi
    runtime, closing several DoS/panic sinks reachable from a single malicious
    frame:
    
    - f017: cap initial slice capacity for wire-declared element counts and
      validate byte-array sizes (negative/over-buffer) before allocating in the
      codegen runtime (FieldReaderArray, ReadBufferByteBased); recover the
      DefaultCodec receive goroutine so an allocation panic fails the cycle, not
      the process.
    - f018: stop pre-allocating the attacker-announced 32-bit frame length in the
      buffered and UDP transports; grow only with bytes actually received under a
      configurable ceiling.
    - f045: cap recursive-descent nesting depth at the shared PullContext
      chokepoint (default 255) so wire-controlled recursion can no longer exhaust
      the goroutine stack (fatal in Go).
    - f055: add a fail-hard crypto/rand RandomBytes helper for security nonces.
    
    Runtime-only; no generated sources need regeneration.
---
 plc4go/spi/codegen/fields/FieldReaderArray.go      | 17 ++++++--
 plc4go/spi/default/DefaultCodec.go                 | 12 ++++++
 plc4go/spi/transports/udp/TransportInstance.go     | 24 ++++++++---
 .../utils/DefaultBufferedTransportInstance.go      | 49 ++++++++++++++++++++--
 plc4go/spi/utils/ReadBufferByteBased.go            | 44 ++++++++++++++++++-
 plc4go/spi/utils/StringUtils.go                    | 17 +++++++-
 6 files changed, 147 insertions(+), 16 deletions(-)

diff --git a/plc4go/spi/codegen/fields/FieldReaderArray.go b/plc4go/spi/codegen/fields/FieldReaderArray.go
index fe6d787dae..46abafa1cd 100644
--- a/plc4go/spi/codegen/fields/FieldReaderArray.go
+++ b/plc4go/spi/codegen/fields/FieldReaderArray.go
@@ -31,6 +31,12 @@ import (
 	"github.com/apache/plc4x/plc4go/spi/utils"
 )
 
+// maxInitialArrayCapacity caps the capacity allocated up front for a
+// wire-declared element count (mirrors MAX_INITIAL_CAPACITY in the Java
+// FieldReaderArray): the count is attacker-controlled, so a forged huge value
+// must not be able to demand gigabytes before a single element was read.
+const maxInitialArrayCapacity = 1024
+
 type FieldReaderArray[T any] struct {
 	codegen.FieldCommons[T]
 
@@ -54,9 +60,12 @@ func (f *FieldReaderArray[T]) ReadFieldCount(ctx context.Context, logicalName st
 		return nil, errors.Wrapf(err, "error pulling context for %s", logicalName)
 	}
 	itemCount := int(max(0, count))
-	var result = make([]T, itemCount)
-	if itemCount == 0 {
-		result = nil
+	// Cap the initial allocation and grow by append: reading an element consumes
+	// at least one bit, so an oversized forged count fails with a read error long
+	// before the slice can grow anywhere near the claimed size.
+	var result []T
+	if itemCount > 0 {
+		result = make([]T, 0, min(itemCount, maxInitialArrayCapacity))
 	}
 	for curItem := range itemCount {
 		// Make some variables available that would be otherwise challenging to forward.
@@ -67,7 +76,7 @@ func (f *FieldReaderArray[T]) ReadFieldCount(ctx context.Context, logicalName st
 		if err != nil {
 			return nil, errors.Wrapf(err, "error reading item %d", curItem)
 		}
-		result[curItem] = read
+		result = append(result, read)
 	}
 	if err := dataReader.CloseContext(logicalName, readerArgs...); err != nil {
 		return nil, errors.Wrapf(err, "error closing context for %s", logicalName)
diff --git a/plc4go/spi/default/DefaultCodec.go b/plc4go/spi/default/DefaultCodec.go
index e1d7ad4cb6..a65b54f0fe 100644
--- a/plc4go/spi/default/DefaultCodec.go
+++ b/plc4go/spi/default/DefaultCodec.go
@@ -500,6 +500,18 @@ mainLoop:
 			syncer := make(chan struct{})
 			m.wg.Go(func() {
 				defer close(syncer)
+				// A malformed frame can panic generated parsers (e.g. allocation
+				// panics on wire-declared sizes); recover here so a poisoned frame
+				// fails this receive cycle instead of killing the process.
+				defer func() {
+					if r := recover(); r != nil {
+						m.log.Error().
+							Str("stack", string(debug.Stack())).
+							Interface("err", r).
+							Msg("panic-ed while receiving")
+						err = errors.Errorf("panic while receiving: %v", r)
+					}
+				}()
 				if !m.running.Load() {
 					err = errors.New("not running")
 					return
diff --git a/plc4go/spi/transports/udp/TransportInstance.go b/plc4go/spi/transports/udp/TransportInstance.go
index 4634d6daa7..c6a0f599b4 100644
--- a/plc4go/spi/transports/udp/TransportInstance.go
+++ b/plc4go/spi/transports/udp/TransportInstance.go
@@ -35,6 +35,7 @@ import (
 	"github.com/apache/plc4x/plc4go/spi/errors"
 	"github.com/apache/plc4x/plc4go/spi/options"
 	"github.com/apache/plc4x/plc4go/spi/transports"
+	transportUtils "github.com/apache/plc4x/plc4go/spi/transports/utils"
 	"github.com/apache/plc4x/plc4go/spi/utils"
 )
 
@@ -51,9 +52,10 @@ type TransportInstance struct {
 	// can absorb the signature change.
 	SoReUse bool
 
-	transport *Transport
-	udpConn   *net.UDPConn
-	reader    *bufio.Reader
+	transport    *Transport
+	udpConn      *net.UDPConn
+	reader       *bufio.Reader
+	maxFrameSize uint32
 
 	connected        atomic.Bool
 	stateChangeMutex sync.RWMutex
@@ -70,6 +72,7 @@ func NewTransportInstance(localAddress *net.UDPAddr, remoteAddress *net.UDPAddr,
 		RemoteAddress: remoteAddress,
 		SoReUse:       soReUse,
 		transport:     transport,
+		maxFrameSize:  transportUtils.ExtractMaxFrameSize(_options...),
 
 		log: logger,
 	}
@@ -215,19 +218,28 @@ func (m *TransportInstance) Read(ctx context.Context, numBytes uint32) ([]byte,
 	if !m.IsConnected() {
 		return nil, errors.New("working on a unconnected connection")
 	}
-	data := make([]byte, numBytes)
+	// numBytes is usually a wire-announced frame length: enforce a ceiling and
+	// never pre-allocate the announced size — grow only with bytes actually read.
+	maxFrameSize := m.maxFrameSize
+	if maxFrameSize == 0 {
+		maxFrameSize = transportUtils.DefaultMaxFrameSize
+	}
+	if numBytes > maxFrameSize {
+		return nil, errors.Errorf("requested %d bytes exceeds the maximum frame size of %d bytes", numBytes, maxFrameSize)
+	}
 	if deadline, ok := ctx.Deadline(); ok {
 		m.log.Trace().Time("deadline", deadline).Msg("deadline set")
 		if err := m.udpConn.SetReadDeadline(deadline); err != nil {
 			return nil, errors.Wrap(err, "error setting read deadline")
 		}
 	}
-	for i := range numBytes {
+	data := make([]byte, 0, min(numBytes, 4096))
+	for range numBytes {
 		val, err := m.reader.ReadByte()
 		if err != nil {
 			return nil, errors.Wrap(err, "error reading")
 		}
-		data[i] = val
+		data = append(data, val)
 	}
 	return data, nil
 }
diff --git a/plc4go/spi/transports/utils/DefaultBufferedTransportInstance.go b/plc4go/spi/transports/utils/DefaultBufferedTransportInstance.go
index 980e7efc2d..997ec91e31 100644
--- a/plc4go/spi/transports/utils/DefaultBufferedTransportInstance.go
+++ b/plc4go/spi/transports/utils/DefaultBufferedTransportInstance.go
@@ -44,11 +44,41 @@ type DefaultBufferedTransportInstance interface {
 	Read(ctx context.Context, numBytes uint32) ([]byte, error)
 }
 
+// DefaultMaxFrameSize is the ceiling applied to wire-announced frame lengths
+// passed to Read when no WithMaxFrameSize option is given. Frame lengths come
+// straight off the wire (raw 32-bit values in ADS/OPC UA headers), so they
+// must never be allocated or read unbounded.
+const DefaultMaxFrameSize uint32 = 1 << 24 // 16 MiB
+
+// WithMaxFrameSize overrides the maximum number of bytes a single Read call
+// accepts (default DefaultMaxFrameSize).
+func WithMaxFrameSize(maxFrameSize uint32) options.WithOption {
+	return withMaxFrameSize{maxFrameSize: maxFrameSize}
+}
+
+type withMaxFrameSize struct {
+	options.Option
+	maxFrameSize uint32
+}
+
+// ExtractMaxFrameSize returns the explicitly configured max frame size, or 0
+// when no WithMaxFrameSize option is present. A stored 0 is interpreted as
+// DefaultMaxFrameSize at Read time, so the zero value is a safe "use default".
+func ExtractMaxFrameSize(_options ...options.WithOption) uint32 {
+	for _, option := range _options {
+		if option, ok := option.(withMaxFrameSize); ok {
+			return option.maxFrameSize
+		}
+	}
+	return 0
+}
+
 func NewDefaultBufferedTransportInstance(defaultBufferedTransportInstanceRequirements DefaultBufferedTransportInstanceRequirements, _options ...options.WithOption) DefaultBufferedTransportInstance {
 	customLogger := options.ExtractCustomLoggerOrDefaultToGlobal(_options...)
 	return &defaultBufferedTransportInstance{
 		DefaultBufferedTransportInstanceRequirements: defaultBufferedTransportInstanceRequirements,
-		log: customLogger,
+		maxFrameSize: ExtractMaxFrameSize(_options...),
+		log:          customLogger,
 	}
 }
 
@@ -57,6 +87,8 @@ type defaultBufferedTransportInstance struct {
 
 	wg sync.WaitGroup // use to track spawned go routines
 
+	maxFrameSize uint32
+
 	log zerolog.Logger
 }
 
@@ -115,19 +147,28 @@ func (m *defaultBufferedTransportInstance) Read(ctx context.Context, numBytes ui
 	if m.GetReader() == nil {
 		return nil, errors.New("error reading from transport. No reader available")
 	}
+	// numBytes is usually a wire-announced frame length: enforce a ceiling and
+	// never pre-allocate the announced size — grow only with bytes actually read.
+	maxFrameSize := m.maxFrameSize
+	if maxFrameSize == 0 {
+		maxFrameSize = DefaultMaxFrameSize
+	}
+	if numBytes > maxFrameSize {
+		return nil, errors.Errorf("requested %d bytes exceeds the maximum frame size of %d bytes", numBytes, maxFrameSize)
+	}
 	if deadline, ok := ctx.Deadline(); ok {
 		m.log.Trace().Time("deadline", deadline).Msg("deadline set")
 		if err := m.SetReadDeadline(deadline); err != nil {
 			return nil, errors.Wrap(err, "error setting read deadline")
 		}
 	}
-	data := make([]byte, numBytes)
-	for i := range numBytes {
+	data := make([]byte, 0, min(numBytes, 4096))
+	for range numBytes {
 		val, err := m.GetReader().ReadByte()
 		if err != nil {
 			return nil, errors.Wrap(err, "error reading")
 		}
-		data[i] = val
+		data = append(data, val)
 	}
 	return data, nil
 }
diff --git a/plc4go/spi/utils/ReadBufferByteBased.go b/plc4go/spi/utils/ReadBufferByteBased.go
index 829b66daed..ef6598fc40 100644
--- a/plc4go/spi/utils/ReadBufferByteBased.go
+++ b/plc4go/spi/utils/ReadBufferByteBased.go
@@ -35,6 +35,13 @@ type ReadBufferByteBased interface {
 	PeekByte(offset byte) byte
 }
 
+// DefaultMaxReadBufferDepth is the default bound for nested PullContext calls.
+// Generated parsers are plain recursive-descent, so wire-controlled recursion
+// (e.g. self-nesting mspec types) would otherwise exhaust the goroutine stack,
+// which is fatal and cannot be recovered. 255 is far beyond any legitimate
+// message nesting.
+const DefaultMaxReadBufferDepth = 255
+
 func NewReadBufferByteBased(data []byte, options ...ReadBufferByteBasedOptions) ReadBufferByteBased {
 	b := &byteReadBuffer{
 		data:      data,
@@ -56,6 +63,16 @@ func WithByteOrderForReadBufferByteBased(byteOrder binary.ByteOrder) ReadBufferB
 	}
 }
 
+// WithMaxDepthForReadBufferByteBased overrides the maximum nesting depth of
+// PullContext calls (default DefaultMaxReadBufferDepth, applied when left at the
+// zero value). A negative value disables the check entirely — only do that for
+// trusted input.
+func WithMaxDepthForReadBufferByteBased(maxDepth int) ReadBufferByteBasedOptions {
+	return func(b *byteReadBuffer) {
+		b.maxDepth = maxDepth
+	}
+}
+
 ///////////////////////////////////////
 ///////////////////////////////////////
 //
@@ -67,6 +84,8 @@ type byteReadBuffer struct {
 	bits      *ReadBitBuffer
 	pos       uint64
 	byteOrder binary.ByteOrder
+	depth     int
+	maxDepth  int
 }
 
 var _ ReadBuffer = (*byteReadBuffer)(nil)
@@ -110,7 +129,18 @@ func (rb *byteReadBuffer) PeekByte(offset uint8) uint8 {
 	return rb.data[rb.GetPos()+uint16(offset)]
 }
 
-func (rb *byteReadBuffer) PullContext(_ string, _ ...WithReaderArgs) error {
+func (rb *byteReadBuffer) PullContext(logicalName string, _ ...WithReaderArgs) error {
+	// Depth guard against wire-controlled recursion: every generated parser
+	// funnels through PullContext/CloseContext, so bounding the nesting here
+	// turns otherwise fatal goroutine-stack exhaustion into a normal parse error.
+	rb.depth++
+	maxDepth := rb.maxDepth
+	if maxDepth == 0 {
+		maxDepth = DefaultMaxReadBufferDepth
+	}
+	if maxDepth > 0 && rb.depth > maxDepth {
+		return errors.Errorf("nesting depth %d at context %s exceeds the maximum of %d (use WithMaxDepthForReadBufferByteBased to raise it for trusted input)", rb.depth, logicalName, maxDepth)
+	}
 	return nil
 }
 
@@ -125,6 +155,15 @@ func (rb *byteReadBuffer) ReadByte(_ string, _ ...WithReaderArgs) (byte, error)
 }
 
 func (rb *byteReadBuffer) ReadByteArray(_ string, numberOfBytes int, _ ...WithReaderArgs) ([]byte, error) {
+	// numberOfBytes is typically a raw wire value: validate it against the
+	// remaining buffer BEFORE allocating, so a forged negative or huge size
+	// cannot panic makeslice or demand gigabytes up front.
+	if numberOfBytes < 0 {
+		return nil, errors.Errorf("cannot read a negative number of bytes (%d)", numberOfBytes)
+	}
+	if remainingBits := rb.bits.BitsRemaining(); uint64(numberOfBytes) > remainingBits/8 {
+		return nil, errors.Errorf("requested %d bytes but only %d bits remain in the buffer", numberOfBytes, remainingBits)
+	}
 	byteArray := make([]byte, numberOfBytes)
 	for i := range numberOfBytes {
 		rb.pos += 8
@@ -339,5 +378,8 @@ func (rb *byteReadBuffer) ReadString(logicalName string, bitLength uint32, _ ...
 }
 
 func (rb *byteReadBuffer) CloseContext(_ string, _ ...WithReaderArgs) error {
+	if rb.depth > 0 {
+		rb.depth--
+	}
 	return nil
 }
diff --git a/plc4go/spi/utils/StringUtils.go b/plc4go/spi/utils/StringUtils.go
index 9cc8f5fb3d..1c14b01fc0 100644
--- a/plc4go/spi/utils/StringUtils.go
+++ b/plc4go/spi/utils/StringUtils.go
@@ -20,6 +20,8 @@
 package utils
 
 import (
+	cryptoRand "crypto/rand"
+	"fmt"
 	"math/rand"
 	"time"
 )
@@ -34,7 +36,20 @@ func init() {
 	}
 }
 
-// RandomString returns a random string using the alphabet
+// RandomBytes returns length cryptographically secure random bytes. It is intended for
+// security-sensitive values such as nonces and fails hard (panics) if the system CSPRNG is
+// unavailable, because silently continuing with predictable values would undermine any key
+// material derived from them.
+func RandomBytes(length int) []byte {
+	randomBytes := make([]byte, length)
+	if _, err := cryptoRand.Read(randomBytes); err != nil {
+		panic(fmt.Sprintf("unable to generate %d secure random bytes: %v", length, err))
+	}
+	return randomBytes
+}
+
+// RandomString returns a random string using the alphabet.
+// Not cryptographically secure: use RandomBytes for nonces and other security-sensitive values.
 func RandomString(length int) string {
 	r := rand.New(rand.NewSource(time.Now().UnixNano()))
 	randomString := make([]rune, length)