mysql 协议分析-握手协议

★ 握手过程:
sync -> ack, sync -> ack
hanshake req -> handshake rsp -> ok/err

★ 主要内容
1 capability交换

The client should only announce the capabilities in the Handshake Response Packet that it has in common with the server.

2 authentication 方法选择
authentication mismatch实验

00:33:05.588690 IP (tos 0x0, ttl 64, id 63881, offset 0, flags [DF], proto TCP (6), length 130)
127.0.0.1.mysql > 127.0.0.1.52507: Flags [P.], cksum 0xfe76 (incorrect -> 0x595e), seq 1298605168:1298605246, ack 1520500850, win 342, options [nop,nop,TS val 2542525945 ecr 2542525945], length 78

0x0000:  4500 0082 f989 4000 4006 42ea 7f00 0001  E.....@[email protected].....
0x0010:  7f00 0001 0cea cd1b 4d67 2470 5aa1 0072  ........Mg$pZ..r
0x0020:  8018 0156 fe76 0000 0101 080a 978b ddf9  ...V.v..........
0x0030:  978b ddf9 4a00 0000 0a35 2e37 2e32 3000  ....J....5.7.20.
0x0040:  0900 0000 2822 474a 261c 1b5c 00ff f708  ....("GJ&..\....
0x0050:  0200 ff81 1500 0000 0000 0000 0000 0027  ...............'
0x0060:  274f 1e0a 1f64 7e51 0d29 4400 6d79 7371  'O...d~Q.)D.mysq
0x0070:  6c5f 6e61 7469 7665 5f70 6173 7377 6f72  l_native_passwor
0x0080:  6400                                     d.

130 - 78 = 52 可见tcp包头占了52个字节。

image.png

红色为tcp包头52字节, 蓝色为mysql 包头4字节, 黄色为mysql协议包体,74字节
mysql包头4字节,
MysqlHeader:
payload len: 3字节表示包体长度(小端存储)0x00004a (74字节)。
sequence id: 1字节表示序列号0x00 (第一个包)。sequence (0~255)每次交互期间从0开始累加,到255后回绕到0。 myql使用tcp协议可以保证有序和不丢包, 使用sequence id 可能是为了防止应用层误用,例如多线程使用同一个connection,使用sequence id可以很容易发现问题。
Protocol Version: 自从3.21.0之后就开始使用V10版本协议,因此该值都是0x0a
server version 服务器版本号,以 '\0'字符结尾。eg: 5.7.20
connection id 连接id, 整个mysql server唯一, 也就是show processlist命令中显示的Id。
auth plugin data 分成两个部分,part1, part2,主要是为了兼容旧协议。
part1是8字节随机字符串 + '\0'.
part2是1字节标志总长度auth length + 剩余部分的随机字符串。
client server之间鉴权方式有多种:
1 mysql_old_password:
2 mysql_native_password:
这两种都是用SHA加密(TODO:研究下具体SHA算法)。server传送一段随机数据给client, client通过如下算法计算,将结果传输给server进行对比。

SHA1( password ) XOR SHA1( "20-bytes random data from server" SHA1( SHA1( password ) ) )

3 mysql_clear_password : 明文校验, client直接把明文密码发送给server.
此外,还有sha256,
4 Pluggable Authentication
https://dev.mysql.com/doc/refman/5.5/en/pluggable-authentication.html

capability 同样分成两个16字节分别存储。 eg: 低字节 0xff f7. 高字节:0x ff 81. 对应的capacitiy为 0x81fff7ff (小端字节序)。
charset 服务器默认字符集。 eg: 0x8 latin1_swedish_ci
status 2字节,服务器状态标志(是否默认autocommit等等)
auth plugin name eg: mysql_native_password
TODO mysql plugin 和old/native password的关系?
支持的authentication plugin:
1

Authentication Plugins & Pluggable Authentication & ssl handshake关系。

★ 画一个脑图
handshake----plain hanshake
---- ssl handshake

★ SSL连接

★ 总结下 密码相关信息在schema中如何存储展示

★ Unix socket方式 & TCP 方式 区别
mysql.sock的作用

你可能感兴趣的:(mysql 协议分析-握手协议)