-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathHandshakeTest.cs
More file actions
297 lines (252 loc) · 13.2 KB
/
HandshakeTest.cs
File metadata and controls
297 lines (252 loc) · 13.2 KB
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
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using SuperSocket.MySQL;
using SuperSocket.MySQL.Packets;
using System.Buffers.Binary;
namespace SuperSocket.MySQL.Test
{
public class HandshakeTest
{
[Fact]
public void HandshakePacket_Decode_ShouldParseCorrectly()
{
// Arrange - Create a mock handshake packet payload
var protocolVersion = (byte)10;
var serverVersion = "8.0.32-MySQL";
var connectionId = (uint)12345;
var authPluginDataPart1 = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 };
var capabilityFlagsLower = (ushort)0x3FFF;
var characterSet = (byte)0x21;
var statusFlags = (ushort)0x0002;
var capabilityFlagsUpper = (ushort)0x807F;
var authPluginDataLength = (byte)20;
var authPluginDataPart2 = new byte[] { 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14 };
var authPluginName = "mysql_native_password";
// Create packet data
var packetData = new List<byte>();
packetData.Add(protocolVersion);
packetData.AddRange(Encoding.UTF8.GetBytes(serverVersion));
packetData.Add(0); // null terminator
packetData.AddRange(BitConverter.GetBytes(connectionId));
packetData.AddRange(authPluginDataPart1);
packetData.Add(0); // filler
packetData.AddRange(BitConverter.GetBytes(capabilityFlagsLower));
packetData.Add(characterSet);
packetData.AddRange(BitConverter.GetBytes(statusFlags));
packetData.AddRange(BitConverter.GetBytes(capabilityFlagsUpper));
packetData.Add(authPluginDataLength);
packetData.AddRange(new byte[10]); // reserved
packetData.AddRange(authPluginDataPart2);
if (authPluginDataPart2.Length < 13)
{
packetData.AddRange(new byte[13 - authPluginDataPart2.Length]); // pad to 13 bytes
}
packetData.AddRange(Encoding.UTF8.GetBytes(authPluginName));
packetData.Add(0); // null terminator
var sequence = new ReadOnlySequence<byte>(packetData.ToArray());
var reader = new SequenceReader<byte>(sequence);
// Act
var handshakePacket = new HandshakePacket();
handshakePacket.Decode(ref reader, null);
// Assert
Assert.Equal(protocolVersion, handshakePacket.ProtocolVersion);
Assert.Equal(serverVersion, handshakePacket.ServerVersion);
Assert.Equal(connectionId, handshakePacket.ConnectionId);
Assert.Equal(authPluginDataPart1, handshakePacket.AuthPluginDataPart1);
Assert.Equal(capabilityFlagsLower, handshakePacket.CapabilityFlagsLower);
Assert.Equal(characterSet, handshakePacket.CharacterSet);
Assert.Equal(statusFlags, handshakePacket.StatusFlags);
Assert.Equal(capabilityFlagsUpper, handshakePacket.CapabilityFlagsUpper);
Assert.Equal(authPluginDataLength, handshakePacket.AuthPluginDataLength);
Assert.Equal(authPluginName, handshakePacket.AuthPluginName);
}
[Fact]
public void HandshakeResponsePacket_Encode_ShouldCreateCorrectPayload()
{
// Arrange
var handshakeResponse = new HandshakeResponsePacket
{
CapabilityFlags = (uint)(ClientCapabilities.CLIENT_PROTOCOL_41 |
ClientCapabilities.CLIENT_SECURE_CONNECTION),
MaxPacketSize = 16777216,
CharacterSet = 0x21,
Username = "testuser",
AuthResponse = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05 },
Database = "testdb",
AuthPluginName = "mysql_native_password"
};
var buffer = new ArrayBufferWriter<byte>();
// Act
var bytesWritten = handshakeResponse.Encode(buffer);
// Assert
Assert.True(bytesWritten > 0, "Should write some bytes");
Assert.True(buffer.WrittenSpan.Length > 0, "Should have written data");
// Verify capability flags are written (first 4 bytes)
var capabilityFlags = BinaryPrimitives.ReadUInt32LittleEndian(buffer.WrittenSpan.Slice(0, 4));
Assert.Equal(handshakeResponse.CapabilityFlags, capabilityFlags);
}
[Fact]
public void OKPacket_Decode_ShouldParseCorrectly()
{
// Arrange
var packetData = new List<byte>();
//packetData.Add(0x00); // OK header
packetData.Add(0x01); // affected rows (length-encoded)
packetData.Add(0x02); // last insert id (length-encoded)
packetData.AddRange(BitConverter.GetBytes((ushort)0x0002)); // status flags
packetData.AddRange(BitConverter.GetBytes((ushort)0x0000)); // warnings
var sequence = new ReadOnlySequence<byte>(packetData.ToArray());
var reader = new SequenceReader<byte>(sequence);
// Act
var okPacket = new OKPacket();
okPacket.Decode(ref reader, null);
// Assert
//Assert.Equal(0x00, okPacket.Header);
Assert.Equal(1UL, okPacket.AffectedRows);
Assert.Equal(2UL, okPacket.LastInsertId);
Assert.Equal(0x0002, okPacket.StatusFlags);
Assert.Equal(0x0000, okPacket.Warnings);
}
[Fact]
public void ErrorPacket_Decode_ShouldParseCorrectly()
{
// Arrange
var errorCode = (ushort)1045;
var sqlState = "28000";
var errorMessage = "Access denied for user";
var packetData = new List<byte>();
//packetData.Add(0xFF); // Error header
packetData.AddRange(BitConverter.GetBytes(errorCode));
packetData.Add((byte)'#'); // SQL state marker
packetData.AddRange(Encoding.UTF8.GetBytes(sqlState));
packetData.AddRange(Encoding.UTF8.GetBytes(errorMessage));
var sequence = new ReadOnlySequence<byte>(packetData.ToArray());
var reader = new SequenceReader<byte>(sequence);
// Act
var errorPacket = new ErrorPacket();
errorPacket.Decode(ref reader, null);
// Assert
//Assert.Equal(0xFF, errorPacket.Header);
Assert.Equal(errorCode, errorPacket.ErrorCode);
Assert.Equal("#", errorPacket.SqlStateMarker);
Assert.Equal(sqlState, errorPacket.SqlState);
Assert.Equal(errorMessage, errorPacket.ErrorMessage);
}
[Fact]
public void ClientCapabilities_FlagsTest()
{
// Test that capability flags can be combined correctly
var capabilities = ClientCapabilities.CLIENT_PROTOCOL_41 |
ClientCapabilities.CLIENT_SECURE_CONNECTION |
ClientCapabilities.CLIENT_PLUGIN_AUTH;
Assert.True((capabilities & ClientCapabilities.CLIENT_PROTOCOL_41) != 0);
Assert.True((capabilities & ClientCapabilities.CLIENT_SECURE_CONNECTION) != 0);
Assert.True((capabilities & ClientCapabilities.CLIENT_PLUGIN_AUTH) != 0);
Assert.False((capabilities & ClientCapabilities.CLIENT_SSL) != 0);
}
[Theory]
[InlineData("")]
[InlineData("password")]
[InlineData("complex_p@ssw0rd_123")]
public void MySQLConnection_GenerateAuthResponse_ShouldHandleDifferentPasswords(string password)
{
// This test verifies that the auth response generation doesn't crash with different password inputs
// We can't easily test the actual authentication without a real MySQL server,
// but we can ensure the method doesn't throw exceptions
// Arrange
var handshakePacket = new HandshakePacket
{
AuthPluginDataPart1 = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 },
AuthPluginDataPart2 = new byte[] { 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14 },
AuthPluginDataLength = 20
};
// We need to use reflection to test the private method, or make it internal for testing
var connection = new MySQLConnection("localhost", 3306, "user", password);
// Act & Assert
// Since GenerateAuthResponse is private, we can't directly test it here
// In a real scenario, you might make it internal and use InternalsVisibleTo attribute
// For now, we just verify the constructor doesn't throw
Assert.NotNull(connection);
}
[Fact]
public void MySQLConnection_GenerateCachingSha2Response_ShouldMatchExpected()
{
// Arrange
const string password = "test_password";
var connection = new MySQLConnection("localhost", 3306, "user", password);
// Include a trailing null byte to validate trimming of the salt.
var salt = new byte[] { 0x33, 0x21, 0x55, 0x42, 0x19, 0x76, 0xA1, 0x0B, 0x10, 0x5C, 0x2D, 0x48, 0x5A, 0x00 };
// Act
var response = connection.GenerateCachingSha2Response(salt);
// Assert
var trimmedSaltLength = salt[^1] == 0 ? salt.Length - 1 : salt.Length;
var trimmedSalt = new byte[trimmedSaltLength];
Array.Copy(salt, trimmedSalt, trimmedSaltLength);
using var sha256 = SHA256.Create();
var passwordBytes = Encoding.UTF8.GetBytes(password);
var sha256Password = sha256.ComputeHash(passwordBytes);
var sha256Sha256Password = sha256.ComputeHash(sha256Password);
var hashAndSalt = new byte[sha256Sha256Password.Length + trimmedSalt.Length];
Array.Copy(sha256Sha256Password, 0, hashAndSalt, 0, sha256Sha256Password.Length);
Array.Copy(trimmedSalt, 0, hashAndSalt, sha256Sha256Password.Length, trimmedSalt.Length);
var sha256Combined = sha256.ComputeHash(hashAndSalt);
var expected = new byte[sha256Password.Length];
for (int i = 0; i < expected.Length; i++)
{
expected[i] = (byte)(sha256Password[i] ^ sha256Combined[i]);
}
Assert.Equal(expected, response);
}
[Fact]
public void EOFPacket_ShouldNotIndicateAuthenticationSuccess()
{
// This test verifies that EOF packets are correctly decoded but should NOT be treated
// as authentication success during the handshake. The MySQL protocol specifies that
// only OKPacket (0x00) indicates successful authentication, while EOFPacket (0xFE)
// during authentication typically indicates an auth switch request.
// Arrange - Create an EOF packet with various status flags
var packetData = new List<byte>();
packetData.AddRange(BitConverter.GetBytes((ushort)0x0000)); // warning count
packetData.AddRange(BitConverter.GetBytes((ushort)0x0002)); // status flags with SERVER_STATUS_AUTOCOMMIT
var sequence = new ReadOnlySequence<byte>(packetData.ToArray());
var reader = new SequenceReader<byte>(sequence);
// Act
var eofPacket = new EOFPacket();
eofPacket.Decode(ref reader, null);
// Assert
Assert.Equal((ushort)0x0002, eofPacket.StatusFlags);
Assert.Equal(0xFE, eofPacket.Header);
// NOTE: The key assertion here is conceptual - an EOF packet during authentication
// should NOT be interpreted as successful authentication regardless of status flags.
// The status flag 0x0002 is SERVER_STATUS_AUTOCOMMIT, not an authentication indicator.
// This test documents that the packet is correctly decoded, but the authentication
// logic in MySQLConnection.ConnectAsync should reject EOF packets.
}
[Fact]
public void EOFPacket_DecodeVariousStatusFlags_ShouldParseCorrectly()
{
// Test EOF packet decoding with different status flag combinations
ushort[] testFlags = { 0x0000, 0x0001, 0x0002, 0x0003, 0x8000, 0xFFFF };
foreach (var flags in testFlags)
{
// Arrange
var packetData = new List<byte>();
packetData.AddRange(BitConverter.GetBytes((ushort)0x0005)); // warning count
packetData.AddRange(BitConverter.GetBytes(flags)); // status flags
var sequence = new ReadOnlySequence<byte>(packetData.ToArray());
var reader = new SequenceReader<byte>(sequence);
// Act
var eofPacket = new EOFPacket();
eofPacket.Decode(ref reader, null);
// Assert
Assert.Equal((ushort)5, eofPacket.WarningCount);
Assert.Equal(flags, eofPacket.StatusFlags);
}
}
}
}