Skip to content

Commit

Permalink
fix: prevent panic on malformed handshake
Browse files Browse the repository at this point in the history
This PR resolves a panic in decodeFirstPart when the functions receives malformed data.
```
panic: runtime error: slice bounds out of range [:2] with capacity 0
```
  • Loading branch information
btoonk committed Sep 4, 2023
1 parent cfe6012 commit 277d959
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 4 deletions.
9 changes: 7 additions & 2 deletions server/handshake_resp.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,13 @@ func (c *Conn) readFirstPart() ([]byte, int, error) {
return c.decodeFirstPart(data)
}

func (c *Conn) decodeFirstPart(data []byte) ([]byte, int, error) {
pos := 0
func (c *Conn) decodeFirstPart(data []byte) (newData []byte, pos int, err error) {
// prevent 'panic: runtime error: index out of range' error
defer func() {
if recover() != nil {
err = NewDefaultError(ER_HANDSHAKE_ERROR)
}
}()

// check CLIENT_PROTOCOL_41
if uint32(binary.LittleEndian.Uint16(data[:2]))&CLIENT_PROTOCOL_41 == 0 {
Expand Down
11 changes: 9 additions & 2 deletions server/handshake_resp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,17 @@ func TestReadAuthData(t *testing.T) {
}

func TestDecodeFirstPart(t *testing.T) {
data := []byte{141, 174, 255, 1, 0, 0, 0, 1, 8}

c := &Conn{}

// test out of range index returns 'bad handshake' error
_, _, err := c.decodeFirstPart([]byte{141, 174})
if err == nil || err.Error() != "ERROR 1043 (08S01): Bad handshake" {
t.Fatal("expected error, got nil")
}

// test good index position
data := []byte{141, 174, 255, 1, 0, 0, 0, 1, 8}

result, pos, err := c.decodeFirstPart(data)
if err != nil {
t.Fatalf("expected nil error, got %v", err)
Expand Down

0 comments on commit 277d959

Please sign in to comment.