Skip to content

Commit

Permalink
Change minimal packet size to 4 bytes
Browse files Browse the repository at this point in the history
A valid packet without token+options+payload will takes only 4 bytes.

The bug was found with the help of go-fuzz
(https://github.com/dvyukov/go-fuzz).
  • Loading branch information
dubek committed Oct 12, 2015
1 parent a2260b9 commit f6a4ce0
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
2 changes: 1 addition & 1 deletion message.go
Original file line number Diff line number Diff line change
Expand Up @@ -553,7 +553,7 @@ func parseMessage(data []byte) (Message, error) {

// UnmarshalBinary parses the given binary slice as a Message.
func (m *Message) UnmarshalBinary(data []byte) error {
if len(data) < 6 {
if len(data) < 4 {
return errors.New("short packet")
}

Expand Down
43 changes: 43 additions & 0 deletions message_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,25 @@ func TestCodeString(t *testing.T) {
}
}

func TestEncodeMessageWithoutOptionsAndPayload(t *testing.T) {
req := Message{
Type: Confirmable,
Code: GET,
MessageID: 12345,
}

data, err := req.MarshalBinary()
if err != nil {
t.Fatalf("Error encoding request: %v", err)
}

// Inspected by hand.
exp := []byte{0x40, 0x1, 0x30, 0x39}
if !bytes.Equal(exp, data) {
t.Fatalf("Expected\n%#v\ngot\n%#v", exp, data)
}
}

func TestEncodeMessageSmall(t *testing.T) {
req := Message{
Type: Confirmable,
Expand Down Expand Up @@ -221,6 +240,30 @@ func TestOptionsWithIllegalLengthAreIgnoredDuringParsing(t *testing.T) {
}
}

func TestDecodeMessageWithoutOptionsAndPayload(t *testing.T) {
input := []byte{0x40, 0x1, 0x30, 0x39}
msg, err := parseMessage(input)
if err != nil {
t.Fatalf("Error parsing message: %v", err)
}

if msg.Type != Confirmable {
t.Errorf("Expected message type confirmable, got %v", msg.Type)
}
if msg.Code != GET {
t.Errorf("Expected message code GET, got %v", msg.Code)
}
if msg.MessageID != 12345 {
t.Errorf("Expected message ID 12345, got %v", msg.MessageID)
}
if len(msg.Token) != 0 {
t.Errorf("Incorrect token: %q", msg.Token)
}
if len(msg.Payload) != 0 {
t.Errorf("Incorrect payload: %q", msg.Payload)
}
}

func TestDecodeMessageSmallWithPayload(t *testing.T) {
input := []byte{
0x40, 0x1, 0x30, 0x39, 0x21, 0x3,
Expand Down

0 comments on commit f6a4ce0

Please sign in to comment.