Skip to content

Commit 09a16f2

Browse files
authored
fix: prevent panic on malformed handshake (#819)
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 ```
1 parent cfe6012 commit 09a16f2

File tree

2 files changed

+16
-4
lines changed

2 files changed

+16
-4
lines changed

server/handshake_resp.go

+7-2
Original file line numberDiff line numberDiff line change
@@ -60,8 +60,13 @@ func (c *Conn) readFirstPart() ([]byte, int, error) {
6060
return c.decodeFirstPart(data)
6161
}
6262

63-
func (c *Conn) decodeFirstPart(data []byte) ([]byte, int, error) {
64-
pos := 0
63+
func (c *Conn) decodeFirstPart(data []byte) (newData []byte, pos int, err error) {
64+
// prevent 'panic: runtime error: index out of range' error
65+
defer func() {
66+
if recover() != nil {
67+
err = NewDefaultError(ER_HANDSHAKE_ERROR)
68+
}
69+
}()
6570

6671
// check CLIENT_PROTOCOL_41
6772
if uint32(binary.LittleEndian.Uint16(data[:2]))&CLIENT_PROTOCOL_41 == 0 {

server/handshake_resp_test.go

+9-2
Original file line numberDiff line numberDiff line change
@@ -28,10 +28,17 @@ func TestReadAuthData(t *testing.T) {
2828
}
2929

3030
func TestDecodeFirstPart(t *testing.T) {
31-
data := []byte{141, 174, 255, 1, 0, 0, 0, 1, 8}
32-
3331
c := &Conn{}
3432

33+
// test out of range index returns 'bad handshake' error
34+
_, _, err := c.decodeFirstPart([]byte{141, 174})
35+
if err == nil || err.Error() != "ERROR 1043 (08S01): Bad handshake" {
36+
t.Fatal("expected error, got nil")
37+
}
38+
39+
// test good index position
40+
data := []byte{141, 174, 255, 1, 0, 0, 0, 1, 8}
41+
3542
result, pos, err := c.decodeFirstPart(data)
3643
if err != nil {
3744
t.Fatalf("expected nil error, got %v", err)

0 commit comments

Comments
 (0)