Skip to content

Commit c327c53

Browse files
Prevent panic on malformed auth data (#557)
Handle malformed data in readAuthData
1 parent 5ec8d51 commit c327c53

File tree

2 files changed

+39
-4
lines changed

2 files changed

+39
-4
lines changed

server/handshake_resp.go

+9-4
Original file line numberDiff line numberDiff line change
@@ -128,10 +128,15 @@ func (c *Conn) readPluginName(data []byte, pos int) int {
128128
return pos
129129
}
130130

131-
func (c *Conn) readAuthData(data []byte, pos int) ([]byte, int, int, error) {
131+
func (c *Conn) readAuthData(data []byte, pos int) (auth []byte, authLen int, newPos int, err error) {
132+
// prevent 'panic: runtime error: index out of range' error
133+
defer func() {
134+
if recover() != nil {
135+
err = NewDefaultError(ER_HANDSHAKE_ERROR)
136+
}
137+
}()
138+
132139
// length encoded data
133-
var auth []byte
134-
var authLen int
135140
if c.capability&CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA != 0 {
136141
authData, isNULL, readBytes, err := LengthEncodedString(data[pos:])
137142
if err != nil {
@@ -144,7 +149,7 @@ func (c *Conn) readAuthData(data []byte, pos int) ([]byte, int, int, error) {
144149
auth = authData
145150
authLen = readBytes
146151
} else if c.capability&CLIENT_SECURE_CONNECTION != 0 {
147-
//auth length and auth
152+
// auth length and auth
148153
authLen = int(data[pos])
149154
pos++
150155
auth = data[pos : pos+authLen]

server/handshake_resp_test.go

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package server
2+
3+
import (
4+
"testing"
5+
6+
"github.com/go-mysql-org/go-mysql/mysql"
7+
)
8+
9+
func TestReadAuthData(t *testing.T) {
10+
c := &Conn{
11+
capability: mysql.CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA,
12+
}
13+
14+
data := []byte{141, 174, 255, 1, 0, 0, 0, 1, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 114, 111, 111, 116, 0, 20, 190, 183, 72, 209, 170, 60, 191, 100, 227, 81, 203, 221, 190, 14, 213, 116, 244, 140, 90, 121, 109, 121, 115, 113, 108, 95, 112, 101, 114, 102, 0, 109, 121, 115, 113, 108, 95, 110, 97, 116, 105, 118, 101, 95, 112, 97, 115, 115, 119, 111, 114, 100, 0}
15+
16+
// test out of range index returns 'bad handshake' error
17+
_, _, _, err := c.readAuthData(data, len(data))
18+
if err == nil || err.Error() != "ERROR 1043 (08S01): Bad handshake" {
19+
t.Fatal("expected error, got nil")
20+
}
21+
22+
// test good index position reads auth data
23+
_, _, readBytes, err := c.readAuthData(data, len(data)-1)
24+
if err != nil {
25+
t.Fatalf("expected nil error, got %v", err)
26+
}
27+
if readBytes != len(data)-1 {
28+
t.Fatalf("expected %d read bytes, got %d", len(data)-1, readBytes)
29+
}
30+
}

0 commit comments

Comments
 (0)