From d9098676fda3e3e14050e3f5c4f6efee22c9ca1c Mon Sep 17 00:00:00 2001 From: Tnze Date: Wed, 24 Jul 2019 14:14:33 +0800 Subject: [PATCH] Fix the NBT decoder panic if length less than 0 --- nbt/nbt_test.go | 19 ++++++++++++++++++- nbt/read.go | 7 +++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/nbt/nbt_test.go b/nbt/nbt_test.go index d69a620..debe38d 100644 --- a/nbt/nbt_test.go +++ b/nbt/nbt_test.go @@ -60,7 +60,7 @@ func TestUnmarshal_simple(t *testing.T) { } } -func TestUnmarshal_bittest(t *testing.T) { +func TestUnmarshal_bitTest(t *testing.T) { // Generated by vscode-hexdump data := []byte{ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, @@ -306,3 +306,20 @@ func TestUnmarshal_ByteArray(t *testing.T) { } // t.Log(infValue) } + +func TestUnmarshal_ErrorString(t *testing.T) { + var data = []byte{ + 0x08, 0x00, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0xFF, 0xFE, + 0x42, 0x61, 0x6e, 0x61, 0x6e, 0x72, 0x61, 0x6d, 0x61, + } + + //Unmarshal to string + var Name string + err := Unmarshal(data, &Name) + + if err == nil { + t.Error("should return a error if len < 0") + } + t.Log(err) + +} diff --git a/nbt/read.go b/nbt/read.go index af6e20f..2654d48 100644 --- a/nbt/read.go +++ b/nbt/read.go @@ -221,6 +221,9 @@ func (d *Decoder) unmarshal(val reflect.Value, tagType byte, tagName string) err if err != nil { return err } + if listLen < 0 { + return errors.New("list length less than 0") + } // If we need parse TAG_List into slice, make a new with right length. // Otherwise if we need parse into array, we check if len(array) are enough. @@ -394,6 +397,10 @@ func (d *Decoder) readTag() (tagType byte, tagName string, err error) { } func (d *Decoder) readNByte(n int) (buf []byte, err error) { + if n < 0 { + return nil, errors.New("read n byte cannot less than 0") + } + buf = make([]byte, n) _, err = d.r.Read(buf) //what happened if (returned n) != (argument n) ? return