Skip to content

fix: prevent panic on malformed handshake #819

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

Merged
merged 1 commit into from
Sep 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
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
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