Skip to content

Commit c35f4fd

Browse files
committed
rlp: check top-level value sizes against input limit
This is a preliminary fix for bnb-chain#420 (SEC-18 RLP decoder unsafe allocation). If a sane input limit is set on the rlp.Stream, it should no longer be possible to cause huge []byte allocations.
1 parent 4020258 commit c35f4fd

2 files changed

Lines changed: 171 additions & 56 deletions

File tree

‎rlp/decode.go‎

Lines changed: 91 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"io"
1010
"math/big"
1111
"reflect"
12+
"strings"
1213
)
1314

1415
var (
@@ -70,14 +71,22 @@ type Decoder interface {
7071
// Non-empty interface types are not supported, nor are booleans,
7172
// signed integers, floating point numbers, maps, channels and
7273
// functions.
74+
//
75+
// Note that Decode does not set an input limit for all readers
76+
// and may be vulnerable to panics cause by huge value sizes. If
77+
// you need an input limit, use
78+
//
79+
// NewStream(r, limit).Decode(val)
7380
func Decode(r io.Reader, val interface{}) error {
74-
return NewStream(r).Decode(val)
81+
// TODO: this could use a Stream from a pool.
82+
return NewStream(r, 0).Decode(val)
7583
}
7684

7785
// DecodeBytes parses RLP data from b into val.
7886
// Please see the documentation of Decode for the decoding rules.
7987
func DecodeBytes(b []byte, val interface{}) error {
80-
return NewStream(bytes.NewReader(b)).Decode(val)
88+
// TODO: this could use a Stream from a pool.
89+
return NewStream(bytes.NewReader(b), uint64(len(b))).Decode(val)
8190
}
8291

8392
type decodeError struct {
@@ -470,10 +479,12 @@ var (
470479
ErrExpectedList = errors.New("rlp: expected List")
471480
ErrCanonInt = errors.New("rlp: expected Int")
472481
ErrElemTooLarge = errors.New("rlp: element is larger than containing list")
482+
ErrValueTooLarge = errors.New("rlp: value size exceeds available input length")
473483

474484
// internal errors
475-
errNotInList = errors.New("rlp: call of ListEnd outside of any list")
476-
errNotAtEOL = errors.New("rlp: call of ListEnd not positioned at EOL")
485+
errNotInList = errors.New("rlp: call of ListEnd outside of any list")
486+
errNotAtEOL = errors.New("rlp: call of ListEnd not positioned at EOL")
487+
errUintOverflow = errors.New("rlp: uint overflow")
477488
)
478489

479490
// ByteReader must be implemented by any input reader for a Stream. It
@@ -496,7 +507,13 @@ type ByteReader interface {
496507
//
497508
// Stream is not safe for concurrent use.
498509
type Stream struct {
499-
r ByteReader
510+
r ByteReader
511+
512+
// number of bytes remaining to be read from r.
513+
remaining uint64
514+
limited bool
515+
516+
// auxiliary buffer for integer decoding
500517
uintbuf []byte
501518

502519
kind Kind // kind of value ahead
@@ -507,20 +524,34 @@ type Stream struct {
507524

508525
type listpos struct{ pos, size uint64 }
509526

510-
// NewStream creates a new stream reading from r.
511-
// If r does not implement ByteReader, the Stream will
512-
// introduce its own buffering.
513-
func NewStream(r io.Reader) *Stream {
527+
// NewStream creates a new decoding stream reading from r.
528+
//
529+
// If r implements the ByteReader interface, Stream will
530+
// not introduce any buffering.
531+
//
532+
// For non-toplevel values, Stream returns ErrElemTooLarge
533+
// for values that do not fit into the enclosing list.
534+
//
535+
// Stream supports an optional input limit. If a limit is set, the
536+
// size of any toplevel value will be checked against the remaining
537+
// input length. Stream operations that encounter a value exceeding
538+
// the remaining input length will return ErrValueTooLarge. The limit
539+
// can be set by passing a non-zero value for inputLimit.
540+
//
541+
// If r is a bytes.Reader or strings.Reader, the input limit is set to
542+
// the length of r's underlying data unless an explicit limit is
543+
// provided.
544+
func NewStream(r io.Reader, inputLimit uint64) *Stream {
514545
s := new(Stream)
515-
s.Reset(r)
546+
s.Reset(r, inputLimit)
516547
return s
517548
}
518549

519550
// NewListStream creates a new stream that pretends to be positioned
520551
// at an encoded list of the given length.
521552
func NewListStream(r io.Reader, len uint64) *Stream {
522553
s := new(Stream)
523-
s.Reset(r)
554+
s.Reset(r, len)
524555
s.kind = List
525556
s.size = len
526557
return s
@@ -574,8 +605,6 @@ func (s *Stream) Raw() ([]byte, error) {
574605
return buf, nil
575606
}
576607

577-
var errUintOverflow = errors.New("rlp: uint overflow")
578-
579608
// Uint reads an RLP string of up to 8 bytes and returns its contents
580609
// as an unsigned integer. If the input does not contain an RLP string, the
581610
// returned error will be ErrExpectedString.
@@ -667,14 +696,36 @@ func (s *Stream) Decode(val interface{}) error {
667696
}
668697

669698
// Reset discards any information about the current decoding context
670-
// and starts reading from r. If r does not also implement ByteReader,
671-
// Stream will do its own buffering.
672-
func (s *Stream) Reset(r io.Reader) {
699+
// and starts reading from r. This method is meant to facilitate reuse
700+
// of a preallocated Stream across many decoding operations.
701+
//
702+
// If r does not also implement ByteReader, Stream will do its own
703+
// buffering.
704+
func (s *Stream) Reset(r io.Reader, inputLimit uint64) {
705+
if inputLimit > 0 {
706+
s.remaining = inputLimit
707+
s.limited = true
708+
} else {
709+
// Attempt to automatically discover
710+
// the limit when reading from a byte slice.
711+
switch br := r.(type) {
712+
case *bytes.Reader:
713+
s.remaining = uint64(br.Len())
714+
s.limited = true
715+
case *strings.Reader:
716+
s.remaining = uint64(br.Len())
717+
s.limited = true
718+
default:
719+
s.limited = false
720+
}
721+
}
722+
// Wrap r with a buffer if it doesn't have one.
673723
bufr, ok := r.(ByteReader)
674724
if !ok {
675725
bufr = bufio.NewReader(r)
676726
}
677727
s.r = bufr
728+
// Reset the decoding context.
678729
s.stack = s.stack[:0]
679730
s.size = 0
680731
s.kind = -1
@@ -700,6 +751,8 @@ func (s *Stream) Kind() (kind Kind, size uint64, err error) {
700751
tos = &s.stack[len(s.stack)-1]
701752
}
702753
if s.kind < 0 {
754+
// don't read further if we're at the end of the
755+
// innermost list.
703756
if tos != nil && tos.pos == tos.size {
704757
return 0, 0, EOL
705758
}
@@ -709,8 +762,19 @@ func (s *Stream) Kind() (kind Kind, size uint64, err error) {
709762
}
710763
s.kind, s.size = kind, size
711764
}
712-
if tos != nil && tos.pos+s.size > tos.size {
713-
return 0, 0, ErrElemTooLarge
765+
// Make sure size is reasonable. This is done always
766+
// so Kind returns the same error when called multiple times.
767+
if tos == nil {
768+
// At toplevel, check that the value is smaller
769+
// than the remaining input length.
770+
if s.limited && s.size > s.remaining {
771+
return 0, 0, ErrValueTooLarge
772+
}
773+
} else {
774+
// Inside a list, check that the value doesn't overflow the list.
775+
if tos.pos+s.size > tos.size {
776+
return 0, 0, ErrElemTooLarge
777+
}
714778
}
715779
return s.kind, s.size, nil
716780
}
@@ -778,6 +842,9 @@ func (s *Stream) readUint(size byte) (uint64, error) {
778842
}
779843

780844
func (s *Stream) readFull(buf []byte) (err error) {
845+
if s.limited && s.remaining < uint64(len(buf)) {
846+
return ErrValueTooLarge
847+
}
781848
s.willRead(uint64(len(buf)))
782849
var nn, n int
783850
for n < len(buf) && err == nil {
@@ -791,6 +858,9 @@ func (s *Stream) readFull(buf []byte) (err error) {
791858
}
792859

793860
func (s *Stream) readByte() (byte, error) {
861+
if s.limited && s.remaining == 0 {
862+
return 0, io.EOF
863+
}
794864
s.willRead(1)
795865
b, err := s.r.ReadByte()
796866
if len(s.stack) > 0 && err == io.EOF {
@@ -801,6 +871,9 @@ func (s *Stream) readByte() (byte, error) {
801871

802872
func (s *Stream) willRead(n uint64) {
803873
s.kind = -1 // rearm Kind
874+
if s.limited {
875+
s.remaining -= n
876+
}
804877
if len(s.stack) > 0 {
805878
s.stack[len(s.stack)-1].pos += n
806879
}

0 commit comments

Comments
 (0)