Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prevent zero length values in slices and maps in codec #2819

Merged
merged 5 commits into from
Mar 8, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Prevent zero length values in codec
  • Loading branch information
StephenButtolph committed Mar 6, 2024
commit 8e72e65623783dc1c6d404777c97a760c3fb75a0
2 changes: 2 additions & 0 deletions codec/codec.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ var (
ErrDoesNotImplementInterface = errors.New("does not implement interface")
ErrUnexportedField = errors.New("unexported field")
ErrExtraSpace = errors.New("trailing buffer space")
ErrMarshalZeroLength = errors.New("can't marshal zero length value")
ErrUnmarshalZeroLength = errors.New("can't unmarshal zero length value")
)

// Codec marshals and unmarshals
Expand Down
23 changes: 21 additions & 2 deletions codec/reflectcodec/type_codec.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ func (c *genericCodec) size(
case reflect.Array:
numElts := value.Len()
if numElts == 0 {
return 0, true, nil
return 0, false, fmt.Errorf("can't marshal array: %w", codec.ErrMarshalZeroLength)
}

size, constSize, err := c.size(value.Index(0), typeStack)
Expand Down Expand Up @@ -205,6 +205,9 @@ func (c *genericCodec) size(
if err != nil {
return 0, false, err
}
if len(serializedFields) == 0 {
return 0, false, fmt.Errorf("can't marshal struct: %w", codec.ErrMarshalZeroLength)
}

var (
size int
Expand Down Expand Up @@ -400,12 +403,16 @@ func (c *genericCodec) marshal(
}
return nil
case reflect.Array:
numElts := value.Len()
if numElts == 0 {
return fmt.Errorf("couldn't marshal array: %w", codec.ErrMarshalZeroLength)
}

if elemKind := value.Type().Kind(); elemKind == reflect.Uint8 {
sliceVal := value.Convert(reflect.TypeOf([]byte{}))
p.PackFixedBytes(sliceVal.Bytes())
return p.Err
}
numElts := value.Len()
for i := 0; i < numElts; i++ { // Process each element in the array
if err := c.marshal(value.Index(i), p, typeStack); err != nil {
return err
Expand All @@ -417,6 +424,10 @@ func (c *genericCodec) marshal(
if err != nil {
return err
}
if len(serializedFields) == 0 {
return fmt.Errorf("couldn't marshal struct: %w", codec.ErrMarshalZeroLength)
}

for _, fieldIndex := range serializedFields { // Go through all fields of this struct that are serialized
if err := c.marshal(value.Field(fieldIndex), p, typeStack); err != nil { // Serialize the field and write to byte array
return err
Expand Down Expand Up @@ -632,6 +643,10 @@ func (c *genericCodec) unmarshal(
return nil
case reflect.Array:
numElts := value.Len()
if numElts == 0 {
return fmt.Errorf("couldn't unmarshal array: %w", codec.ErrUnmarshalZeroLength)
}

if elemKind := value.Type().Elem().Kind(); elemKind == reflect.Uint8 {
unpackedBytes := p.UnpackFixedBytes(numElts)
if p.Errored() {
Expand Down Expand Up @@ -679,6 +694,10 @@ func (c *genericCodec) unmarshal(
if err != nil {
return fmt.Errorf("couldn't unmarshal struct: %w", err)
}
if len(serializedFieldIndices) == 0 {
return fmt.Errorf("couldn't unmarshal struct: %w", codec.ErrUnmarshalZeroLength)
}

// Go through the fields and umarshal into them
for _, fieldIndex := range serializedFieldIndices {
if err := c.unmarshal(p, value.Field(fieldIndex), typeStack); err != nil {
Expand Down
43 changes: 26 additions & 17 deletions codec/test_codec.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ var (
TestNilSliceSerialization,
TestEmptySliceSerialization,
TestSliceWithEmptySerialization,
TestSliceWithEmptySerializationOutOfMemory,
TestSliceWithEmptySerializationError,
TestSliceTooLarge,
TestNegativeNumbers,
TestTooLargeUnmarshal,
Expand Down Expand Up @@ -731,7 +731,7 @@ func TestEmptySliceSerialization(codec GeneralCodec, t testing.TB) {
require.Equal(val, valUnmarshaled)
}

// Test marshaling slice that is not nil and not empty
// Test marshaling empty slice of zero length structs
func TestSliceWithEmptySerialization(codec GeneralCodec, t testing.TB) {
require := require.New(t)

Expand All @@ -745,9 +745,9 @@ func TestSliceWithEmptySerialization(codec GeneralCodec, t testing.TB) {
require.NoError(manager.RegisterCodec(0, codec))

val := &nestedSliceStruct{
Arr: make([]emptyStruct, 1000),
Arr: make([]emptyStruct, 0),
}
expected := []byte{0x00, 0x00, 0x00, 0x00, 0x03, 0xE8} // codec version (0x00, 0x00) then 1000 for numElts
expected := []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00} // codec version (0x00, 0x00) then (0x00, 0x00, 0x00, 0x00) for numElts
result, err := manager.Marshal(0, val)
require.NoError(err)
require.Equal(expected, result)
Expand All @@ -760,10 +760,10 @@ func TestSliceWithEmptySerialization(codec GeneralCodec, t testing.TB) {
version, err := manager.Unmarshal(expected, &unmarshaled)
require.NoError(err)
require.Zero(version)
require.Len(unmarshaled.Arr, 1000)
require.Empty(unmarshaled.Arr)
}

func TestSliceWithEmptySerializationOutOfMemory(codec GeneralCodec, t testing.TB) {
func TestSliceWithEmptySerializationError(codec GeneralCodec, t testing.TB) {
require := require.New(t)

type emptyStruct struct{}
Expand All @@ -776,14 +776,19 @@ func TestSliceWithEmptySerializationOutOfMemory(codec GeneralCodec, t testing.TB
require.NoError(manager.RegisterCodec(0, codec))

val := &nestedSliceStruct{
Arr: make([]emptyStruct, math.MaxInt32),
Arr: make([]emptyStruct, 1),
}
_, err := manager.Marshal(0, val)
require.ErrorIs(err, ErrMaxSliceLenExceeded)
require.ErrorIs(err, ErrMarshalZeroLength)

bytesLen, err := manager.Size(0, val)
require.NoError(err)
require.Equal(6, bytesLen) // 2 byte codec version + 4 byte length prefix
_, err = manager.Size(0, val)
require.ErrorIs(err, ErrMarshalZeroLength)

b := []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x01} // codec version (0x00, 0x00) then (0x00, 0x00, 0x00, 0x01) for numElts

unmarshaled := nestedSliceStruct{}
_, err = manager.Unmarshal(b, &unmarshaled)
require.ErrorIs(err, ErrUnmarshalZeroLength)
}

func TestSliceTooLarge(codec GeneralCodec, t testing.TB) {
Expand Down Expand Up @@ -845,20 +850,24 @@ func TestTooLargeUnmarshal(codec GeneralCodec, t testing.TB) {
}

type outerInterface interface {
ToInt() int
ToInt() uint64
}

type outer struct {
Interface outerInterface `serialize:"true"`
}

type innerInterface struct{}
type innerInterface struct {
Val uint64 `serialize:"true"`
}

func (*innerInterface) ToInt() int {
func (*innerInterface) ToInt() uint64 {
return 0
}

type innerNoInterface struct{}
type innerNoInterface struct {
Val uint64 `serialize:"true"`
}

// Ensure deserializing structs into the wrong interface errors gracefully
func TestUnmarshalInvalidInterface(codec GeneralCodec, t testing.TB) {
Expand All @@ -870,14 +879,14 @@ func TestUnmarshalInvalidInterface(codec GeneralCodec, t testing.TB) {
require.NoError(manager.RegisterCodec(0, codec))

{
bytes := []byte{0, 0, 0, 0, 0, 0}
bytes := []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
s := outer{}
version, err := manager.Unmarshal(bytes, &s)
require.NoError(err)
require.Zero(version)
}
{
bytes := []byte{0, 0, 0, 0, 0, 1}
bytes := []byte{0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0}
s := outer{}
_, err := manager.Unmarshal(bytes, &s)
require.ErrorIs(err, ErrDoesNotImplementInterface)
Expand Down
Loading