-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathprot_auth.go
360 lines (294 loc) · 9.57 KB
/
prot_auth.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
/*
The MIT License (MIT)
Copyright (c) 2015 Nirbhay Choubey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package mysql
import (
"crypto/sha1"
"encoding/binary"
)
//<!-- connection phase packets -->
// parseGreetingPacket parses handshake initialization packet received from
// the server.
func (c *Conn) parseGreetingPacket(b []byte) {
var (
off, n int
authData []byte // authentication plugin data
authDataLength int
authDataOff_1, authDataOff_2 int
)
off++ // [0a] protocol version
c.serverVersion, n = getNullTerminatedString(b[off:]) // server version (null-terminated)
off += n
c.connectionId = binary.LittleEndian.Uint32(b[off : off+4]) // connection ID
off += 4
// auth-plugin-data-part-1 (8 bytes) : note the offset & length
authDataOff_1 = off
authDataLength = 8
off += 8
off++ // [00] filler
// capacity flags (lower 2 bytes)
c.serverCapabilities = uint32(binary.LittleEndian.Uint16(b[off : off+2]))
off += 2
if len(b) > off {
c.serverCharset = uint8(b[off])
off++
c.statusFlags = binary.LittleEndian.Uint16(b[off : off+2]) // status flags
off += 2
// capacity flags (upper 2 bytes)
c.serverCapabilities |= (uint32(binary.LittleEndian.Uint16(b[off:off+2])) << 16)
off += 2
if (c.serverCapabilities & _CLIENT_PLUGIN_AUTH) != 0 {
// update the auth plugin data length
authDataLength = int(b[off])
off++
} else {
off++ // [00]
}
off += 10 // reserved (all [00])
if (c.serverCapabilities & _CLIENT_SECURE_CONNECTION) != 0 {
// auth-plugin-data-part-2 : note the offset & update
// the length (max(13, authDataLength- 8)
if (authDataLength - 8) > 13 {
authDataLength = 13 + 8
}
authDataOff_2 = off
off += (authDataLength - 8)
authDataLength-- // ignore the 13th 0x00 byte
}
authData = make([]byte, authDataLength)
copy(authData[0:8], b[authDataOff_1:authDataOff_1+8])
if authDataLength > 8 {
copy(authData[8:], b[authDataOff_2:authDataOff_2+(authDataLength-8)])
}
c.authPluginData = authData
if (c.serverCapabilities & _CLIENT_PLUGIN_AUTH) != 0 {
// auth-plugin name (null-terminated)
c.authPluginName, n = getNullTerminatedString(b[off:])
off += n
}
}
}
// createHandshakeResponsePacket generates the handshake response packet.
func (c *Conn) createHandshakeResponsePacket() ([]byte, error) {
var (
authData []byte // auth response data
b []byte
off, payloadLength int
err error
)
payloadLength = (4 + 4 + 1 + 23)
authData = c.authResponseData()
payloadLength += c.handshakeResponse2Length(len(authData))
if b, err = c.buff.Reset(4 + payloadLength); err != nil {
return nil, err
}
off += 4 // placeholder for protocol packet header
off += c.populateHandshakeResponse1(b[off:])
off += c.populateHandshakeResponse2(b[off:], authData)
return b[0:off], nil
}
// createSSLRequestPacket generates the SSL request packet to initiate SSL
// handshake. It is sent to the server over plain connection after which the
// communication switches to SSL.
func (c *Conn) createSSLRequestPacket() ([]byte, error) {
var (
b []byte
off, payloadLength int
err error
)
payloadLength = (4 + 4 + 1 + 23)
if b, err = c.buff.Reset(4 + payloadLength); err != nil {
return nil, err
}
off += 4
off += c.populateHandshakeResponse1(b[4:])
return b[0:off], nil
}
// populateHandshakeResponse1 populates the specified slice with the
// information from 1st part of protocol's handshake response packet
// (before user name) and returns the final offset.
func (c *Conn) populateHandshakeResponse1(b []byte) int {
var off int
// client capability flags
binary.LittleEndian.PutUint32(b[off:off+4], c.p.clientCapabilities)
off += 4
// max packet size
binary.LittleEndian.PutUint32(b[off:off+4], c.p.maxPacketSize)
off += 4
// client character set
b[off] = byte(c.clientCharset) // client character set
off++
zerofy(b[off : off+23])
off += 23 // reserved (all [0])
return off
}
// populateHandshakeResponse2 populates the specified slice with the
// information from 2st part of protocol's handshake response packet
// (starting user name) and returns the final offset.
func (c *Conn) populateHandshakeResponse2(b []byte, authData []byte) int {
var off int
off += putNullTerminatedString(b[off:], c.p.username)
if (c.serverCapabilities & _CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA) != 0 {
off += putLenencString(b[off:], string(authData))
} else if (c.serverCapabilities & _CLIENT_SECURE_CONNECTION) != 0 {
b[off] = byte(len(authData))
off++
off += copy(b[off:], authData)
} else {
off += putNullTerminatedString(b[off:], string(authData))
}
if (c.p.schema != "") && ((c.serverCapabilities & _CLIENT_CONNECT_WITH_DB) != 0) {
off += putNullTerminatedString(b[off:], c.p.schema)
}
if (c.serverCapabilities & _CLIENT_PLUGIN_AUTH) != 0 {
off += putNullTerminatedString(b[off:], c.authPluginName)
}
if (c.serverCapabilities & _CLIENT_CONNECT_ATTRS) != 0 {
// TODO: handle connection attributes
}
return off
}
// handshakeResponse2Length returns the extra payload length of the handshake
// response packet starting user name.
func (c *Conn) handshakeResponse2Length(authLength int) (length int) {
length += (len(c.p.username) + 1) // null-terminated username
length += authLength
if (c.serverCapabilities & _CLIENT_CONNECT_WITH_DB) != 0 {
length += (len(c.p.schema) + 1) // null-terminated schema name
}
if (c.serverCapabilities & _CLIENT_PLUGIN_AUTH) != 0 {
length += (len(c.authPluginName) + 1) // null-terminated authentication plugin name
}
if (c.serverCapabilities & _CLIENT_CONNECT_ATTRS) != 0 {
// TODO: handle connection attributes
}
return
}
// handshake performs handshake during connection establishment
func (c *Conn) handshake() error {
var (
b []byte
useSSL bool
useCompression bool
err error
)
// read handshake initialization packet.
if b, err = c.readPacket(); err != nil {
return err
}
c.parseGreetingPacket(b)
// note : server capabilities can only be checked after receiving the
// "greeting" packet
if c.p.clientCapabilities&_CLIENT_SSL != 0 {
if c.serverCapabilities&_CLIENT_SSL == 0 {
// error: client requested for SSL but server doesn't
// support SSL.
return myError(ErrSSLSupport)
} else {
useSSL = true
}
}
if c.p.clientCapabilities&_CLIENT_COMPRESS != 0 {
if c.serverCapabilities&_CLIENT_COMPRESS == 0 {
// error: client requested for packet compression but server doesn't
// support compression protocol.
return myError(ErrCompressionSupport)
} else {
useCompression = true
}
}
if !useSSL {
// send plain handshake response packet
if b, err = c.createHandshakeResponsePacket(); err != nil {
return err
}
if err = c.writePacket(b); err != nil {
return err
}
} else {
// send SSL request packet (1st part of handshake response
// packet)
if b, err = c.createSSLRequestPacket(); err != nil {
return err
}
if err = c.writePacket(b); err != nil {
return err
}
// switch to tls
if err = c.sslConnect(); err != nil {
return err
}
// <!-- SSL activated -->
// now send the entire handshake response packet
if b, err = c.createHandshakeResponsePacket(); err != nil {
return err
}
if err = c.writePacket(b); err != nil {
return err
}
}
// read server response
if b, err = c.readPacket(); err != nil {
return err
}
switch b[0] {
case _PACKET_ERR:
c.parseErrPacket(b)
return &c.e
case _PACKET_OK:
c.parseOkPacket(b)
default:
// TODO: invalid packet
}
if useCompression { // switch to compression protocol
c.rw = &compressRW{}
c.rw.init(c)
// <!-- Compression activated -->
}
return nil
}
// authResponseData returns the authentication response data to be sent to the
// server.
func (c *Conn) authResponseData() []byte {
return scramble41(c.p.password, c.authPluginData)
}
// scraamble41 returns a scramble buffer based on the following formula:
// SHA1(password) XOR SHA1("20-byte public seed from server" <concat> SHA1( SHA1( password)))
func scramble41(password string, seed []byte) (buf []byte) {
if len(password) == 0 {
return
}
hash := sha1.New()
// stage 1: SHA1(password)
hash.Write([]byte(password))
hashStage1 := hash.Sum(nil)
// stage 2: SHA1(SHA1(password))
hash.Reset()
hash.Write(hashStage1)
hashStage2 := hash.Sum(nil)
// SHA1("20-byte public seed from server" <concat> SHA1(SHA1(password)))
hash.Reset()
hash.Write(seed)
hash.Write(hashStage2)
buf = hash.Sum(nil)
for i := 0; i < sha1.Size; i++ {
buf[i] ^= hashStage1[i]
}
return
}