-
Notifications
You must be signed in to change notification settings - Fork 329
/
ServerSession.cs
1426 lines (1280 loc) · 55.7 KB
/
ServerSession.cs
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Buffers.Text;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using System.IO;
#if !NETSTANDARD1_3
using System.IO.Pipes;
#endif
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Reflection;
using System.Security.Authentication;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using MySqlConnector.Logging;
using MySqlConnector.Protocol;
using MySqlConnector.Protocol.Payloads;
using MySqlConnector.Protocol.Serialization;
using MySqlConnector.Utilities;
namespace MySqlConnector.Core
{
internal sealed class ServerSession
{
public ServerSession()
: this(null, 0, Interlocked.Increment(ref s_lastId))
{
}
public ServerSession(ConnectionPool pool, int poolGeneration, int id)
{
m_lock = new object();
m_payloadCache = new ArraySegmentHolder<byte>();
Id = (pool?.Id ?? 0) + "." + id;
CreatedTicks = unchecked((uint) Environment.TickCount);
Pool = pool;
PoolGeneration = poolGeneration;
HostName = "";
m_logArguments = new object[] { "{0}".FormatInvariant(Id), null };
Log.Debug("Session{0} created new session", m_logArguments);
}
public string Id { get; }
public ServerVersion ServerVersion { get; set; }
public int ConnectionId { get; set; }
public byte[] AuthPluginData { get; set; }
public uint CreatedTicks { get; }
public ConnectionPool Pool { get; }
public int PoolGeneration { get; }
public uint LastReturnedTicks { get; private set; }
public string DatabaseOverride { get; set; }
public string HostName { get; private set; }
public IPAddress IPAddress => (m_tcpClient?.Client.RemoteEndPoint as IPEndPoint)?.Address;
public WeakReference<MySqlConnection> OwningConnection { get; set; }
public bool SupportsDeprecateEof => m_supportsDeprecateEof;
public bool SupportsSessionTrack => m_supportsSessionTrack;
public bool ProcAccessDenied { get; set; }
public void ReturnToPool()
{
if (Log.IsDebugEnabled())
{
m_logArguments[1] = Pool?.Id;
Log.Debug("Session{0} returning to Pool{1}", m_logArguments);
}
LastReturnedTicks = unchecked((uint) Environment.TickCount);
Pool?.Return(this);
}
public bool IsConnected
{
get
{
lock (m_lock)
return m_state == State.Connected;
}
}
public bool TryStartCancel(MySqlCommand command)
{
lock (m_lock)
{
if (m_activeCommandId != command.CommandId)
return false;
VerifyState(State.Querying, State.CancelingQuery, State.Failed);
if (m_state != State.Querying)
return false;
if (command.CancelAttemptCount++ >= 10)
return false;
m_state = State.CancelingQuery;
}
Log.Info("Session{0} will cancel CommandId: {1} (CancelledAttempts={2}) CommandText: {3}", m_logArguments[0], command.CommandId, command.CancelAttemptCount, command.CommandText);
return true;
}
public void DoCancel(MySqlCommand commandToCancel, MySqlCommand killCommand)
{
Log.Info("Session{0} canceling CommandId {1}: CommandText: {2}", m_logArguments[0], commandToCancel.CommandId, commandToCancel.CommandText);
lock (m_lock)
{
if (m_activeCommandId != commandToCancel.CommandId)
return;
// NOTE: This command is executed while holding the lock to prevent race conditions during asynchronous cancellation.
// For example, if the lock weren't held, the current command could finish and the other thread could set m_activeCommandId
// to zero, then start executing a new command. By the time this "KILL QUERY" command reached the server, the wrong
// command would be killed (because "KILL QUERY" specifies the connection whose command should be killed, not
// a unique identifier of the command itself). As a mitigation, we set the CommandTimeout to a low value to avoid
// blocking the other thread for an extended duration.
killCommand.CommandTimeout = 3;
killCommand.ExecuteNonQuery();
}
}
public void AbortCancel(MySqlCommand command)
{
lock (m_lock)
{
if (m_activeCommandId == command.CommandId && m_state == State.CancelingQuery)
m_state = State.Querying;
}
}
public void AddPreparedStatement(string commandText, PreparedStatements preparedStatements)
{
if (m_preparedStatements is null)
m_preparedStatements = new Dictionary<string, PreparedStatements>();
m_preparedStatements.Add(commandText, preparedStatements);
}
public PreparedStatements TryGetPreparedStatement(string commandText)
{
if (m_preparedStatements != null)
{
if (m_preparedStatements.TryGetValue(commandText, out var statement))
return statement;
}
return null;
}
public void StartQuerying(MySqlCommand command)
{
lock (m_lock)
{
if (m_state == State.Querying || m_state == State.CancelingQuery)
{
m_logArguments[1] = m_state;
Log.Error("Session{0} can't execute new command when in SessionState: {1}: CommandText: {2}", m_logArguments[0], m_state, command.CommandText);
throw new InvalidOperationException("This MySqlConnection is already in use. See https://fl.vu/mysql-conn-reuse");
}
VerifyState(State.Connected);
m_state = State.Querying;
command.CancelAttemptCount = 0;
m_activeCommandId = command.CommandId;
}
}
public void FinishQuerying()
{
m_logArguments[1] = m_state;
Log.Debug("Session{0} entering FinishQuerying; SessionState={1}", m_logArguments);
bool clearConnection = false;
lock (m_lock)
{
if (m_state == State.CancelingQuery)
{
m_state = State.ClearingPendingCancellation;
clearConnection = true;
}
}
if (clearConnection)
{
// KILL QUERY will kill a subsequent query if the command it was intended to cancel has already completed.
// In order to handle this case, we issue a dummy query that will consume the pending cancellation.
// See https://bugs.mysql.com/bug.php?id=45679
Log.Info("Session{0} sending 'DO SLEEP(0)' command to clear pending cancellation", m_logArguments);
var payload = QueryPayload.Create("DO SLEEP(0);");
SendAsync(payload, IOBehavior.Synchronous, CancellationToken.None).GetAwaiter().GetResult();
payload = ReceiveReplyAsync(IOBehavior.Synchronous, CancellationToken.None).GetAwaiter().GetResult();
OkPayload.Create(payload.AsSpan(), SupportsDeprecateEof, SupportsSessionTrack);
}
lock (m_lock)
{
if (m_state == State.Querying || m_state == State.ClearingPendingCancellation)
m_state = State.Connected;
else
VerifyState(State.Failed);
m_activeCommandId = 0;
}
}
public void SetTimeout(int timeoutMilliseconds) => m_payloadHandler.ByteHandler.RemainingTimeout = timeoutMilliseconds;
public async Task DisposeAsync(IOBehavior ioBehavior, CancellationToken cancellationToken)
{
if (m_payloadHandler != null)
{
// attempt to gracefully close the connection, ignoring any errors (it may have been closed already by the server, etc.)
State state;
lock (m_lock)
{
if (m_state == State.Connected || m_state == State.Failed)
m_state = State.Closing;
state = m_state;
}
if (state == State.Closing)
{
try
{
Log.Info("Session{0} sending QUIT command", m_logArguments);
m_payloadHandler.StartNewConversation();
await m_payloadHandler.WritePayloadAsync(QuitPayload.Instance.ArraySegment, ioBehavior).ConfigureAwait(false);
}
catch (IOException)
{
}
catch (NotSupportedException)
{
}
catch (ObjectDisposedException)
{
}
catch (SocketException)
{
}
}
}
ClearPreparedStatements();
ShutdownSocket();
lock (m_lock)
m_state = State.Closed;
}
public async Task ConnectAsync(ConnectionSettings cs, ILoadBalancer loadBalancer, IOBehavior ioBehavior, CancellationToken cancellationToken)
{
try
{
lock (m_lock)
{
VerifyState(State.Created);
m_state = State.Connecting;
}
// TLS negotiation should automatically fall back to the best version supported by client and server. However,
// Windows Schannel clients will fail to connect to a yaSSL-based MySQL Server if TLS 1.2 is requested and
// have to use only TLS 1.1: https://github.com/mysql-net/MySqlConnector/pull/101
// In order to use the best protocol possible (i.e., not always default to TLS 1.1), we try the OS-default protocol
// (which is SslProtocols.None; see https://docs.microsoft.com/en-us/dotnet/framework/network-programming/tls),
// then fall back to SslProtocols.Tls11 if that fails and it's possible that the cause is a yaSSL server.
bool shouldRetrySsl;
var sslProtocols = Pool?.SslProtocols ?? Utility.GetDefaultSslProtocols();
PayloadData payload;
InitialHandshakePayload initialHandshake;
do
{
shouldRetrySsl = (sslProtocols == SslProtocols.None || (sslProtocols & SslProtocols.Tls12) == SslProtocols.Tls12) && Utility.IsWindows();
var connected = false;
if (cs.ConnectionProtocol == MySqlConnectionProtocol.Sockets)
connected = await OpenTcpSocketAsync(cs, loadBalancer, ioBehavior, cancellationToken).ConfigureAwait(false);
else if (cs.ConnectionProtocol == MySqlConnectionProtocol.UnixSocket)
connected = await OpenUnixSocketAsync(cs, ioBehavior, cancellationToken).ConfigureAwait(false);
else if (cs.ConnectionProtocol == MySqlConnectionProtocol.NamedPipe)
connected = await OpenNamedPipeAsync(cs, ioBehavior, cancellationToken).ConfigureAwait(false);
if (!connected)
{
lock (m_lock)
m_state = State.Failed;
Log.Error("Session{0} connecting failed", m_logArguments);
throw new MySqlException((int) MySqlErrorCode.UnableToConnectToHost, null, "Unable to connect to any of the specified MySQL hosts.");
}
var byteHandler = m_socket is null ? new StreamByteHandler(m_stream) : (IByteHandler) new SocketByteHandler(m_socket);
m_payloadHandler = new StandardPayloadHandler(byteHandler);
payload = await ReceiveAsync(ioBehavior, cancellationToken).ConfigureAwait(false);
initialHandshake = InitialHandshakePayload.Create(payload.AsSpan());
// if PluginAuth is supported, then use the specified auth plugin; else, fall back to protocol capabilities to determine the auth type to use
string authPluginName;
if ((initialHandshake.ProtocolCapabilities & ProtocolCapabilities.PluginAuth) != 0)
authPluginName = initialHandshake.AuthPluginName;
else
authPluginName = (initialHandshake.ProtocolCapabilities & ProtocolCapabilities.SecureConnection) == 0 ? "mysql_old_password" : "mysql_native_password";
m_logArguments[1] = authPluginName;
Log.Debug("Session{0} server sent AuthPluginName={1}", m_logArguments);
if (authPluginName != "mysql_native_password" && authPluginName != "sha256_password" && authPluginName != "caching_sha2_password")
{
Log.Error("Session{0} unsupported authentication method AuthPluginName={1}", m_logArguments);
throw new NotSupportedException("Authentication method '{0}' is not supported.".FormatInvariant(initialHandshake.AuthPluginName));
}
ServerVersion = new ServerVersion(initialHandshake.ServerVersion);
ConnectionId = initialHandshake.ConnectionId;
AuthPluginData = initialHandshake.AuthPluginData;
m_useCompression = cs.UseCompression && (initialHandshake.ProtocolCapabilities & ProtocolCapabilities.Compress) != 0;
m_supportsConnectionAttributes = (initialHandshake.ProtocolCapabilities & ProtocolCapabilities.ConnectionAttributes) != 0;
m_supportsDeprecateEof = (initialHandshake.ProtocolCapabilities & ProtocolCapabilities.DeprecateEof) != 0;
m_supportsSessionTrack = (initialHandshake.ProtocolCapabilities & ProtocolCapabilities.SessionTrack) != 0;
var serverSupportsSsl = (initialHandshake.ProtocolCapabilities & ProtocolCapabilities.Ssl) != 0;
m_characterSet = ServerVersion.Version >= ServerVersions.SupportsUtf8Mb4 ? CharacterSet.Utf8Mb4GeneralCaseInsensitive : CharacterSet.Utf8GeneralCaseInsensitive;
m_setNamesPayload = ServerVersion.Version >= ServerVersions.SupportsUtf8Mb4 ? s_setNamesUtf8mb4Payload : s_setNamesUtf8Payload;
Log.Info("Session{0} made connection; ServerVersion={1}; ConnectionId={2}; Compression={3}; Attributes={4}; DeprecateEof={5}; Ssl={6}; SessionTrack={7}",
m_logArguments[0], ServerVersion.OriginalString, ConnectionId,
m_useCompression, m_supportsConnectionAttributes, m_supportsDeprecateEof, serverSupportsSsl, m_supportsSessionTrack);
if (cs.SslMode != MySqlSslMode.None && (cs.SslMode != MySqlSslMode.Preferred || serverSupportsSsl))
{
if (!serverSupportsSsl)
{
Log.Error("Session{0} requires SSL but server doesn't support it", m_logArguments);
throw new MySqlException("Server does not support SSL");
}
try
{
await InitSslAsync(initialHandshake.ProtocolCapabilities, cs, sslProtocols, ioBehavior, cancellationToken).ConfigureAwait(false);
shouldRetrySsl = false;
}
catch (ArgumentException ex) when (ex.ParamName == "sslProtocolType" && sslProtocols == SslProtocols.None)
{
Log.Warn(ex, "Session{0} doesn't support SslProtocols.None; falling back to explicitly specifying SslProtocols", m_logArguments);
sslProtocols = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12;
}
catch (Exception ex) when (shouldRetrySsl && ((ex is MySqlException && ex.InnerException is IOException) || ex is IOException))
{
// negotiating TLS 1.2 with a yaSSL-based server throws an exception on Windows, see comment at top of method
Log.Warn(ex, "Session{0} failed negotiating TLS; falling back to TLS 1.1", m_logArguments);
sslProtocols = SslProtocols.Tls | SslProtocols.Tls11;
if (Pool != null)
Pool.SslProtocols = sslProtocols;
}
}
else
{
shouldRetrySsl = false;
}
} while (shouldRetrySsl);
if (m_supportsConnectionAttributes && cs.ConnectionAttributes is null)
cs.ConnectionAttributes = CreateConnectionAttributes(cs.ApplicationName);
using (var handshakeResponsePayload = HandshakeResponse41Payload.Create(initialHandshake, cs, m_useCompression, m_characterSet, m_supportsConnectionAttributes ? cs.ConnectionAttributes : null))
await SendReplyAsync(handshakeResponsePayload, ioBehavior, cancellationToken).ConfigureAwait(false);
payload = await ReceiveReplyAsync(ioBehavior, cancellationToken).ConfigureAwait(false);
// if server doesn't support the authentication fast path, it will send a new challenge
if (payload.HeaderByte == AuthenticationMethodSwitchRequestPayload.Signature)
{
payload = await SwitchAuthenticationAsync(cs, payload, ioBehavior, cancellationToken).ConfigureAwait(false);
}
OkPayload.Create(payload.AsSpan(), SupportsDeprecateEof, SupportsSessionTrack);
if (m_useCompression)
m_payloadHandler = new CompressedPayloadHandler(m_payloadHandler.ByteHandler);
// set 'collation_connection' to the server default
await SendAsync(m_setNamesPayload, ioBehavior, cancellationToken).ConfigureAwait(false);
payload = await ReceiveReplyAsync(ioBehavior, cancellationToken).ConfigureAwait(false);
OkPayload.Create(payload.AsSpan(), SupportsDeprecateEof, SupportsSessionTrack);
if (ShouldGetRealServerDetails())
await GetRealServerDetailsAsync(ioBehavior, CancellationToken.None).ConfigureAwait(false);
}
catch (ArgumentException ex)
{
Log.Error(ex, "Session{0} couldn't connect to server", m_logArguments);
throw new MySqlException("Couldn't connect to server", ex);
}
catch (IOException ex)
{
Log.Error(ex, "Session{0} couldn't connect to server", m_logArguments);
throw new MySqlException("Couldn't connect to server", ex);
}
}
public async Task<bool> TryResetConnectionAsync(ConnectionSettings cs, IOBehavior ioBehavior, CancellationToken cancellationToken)
{
VerifyState(State.Connected);
try
{
// clear all prepared statements; resetting the connection will clear them on the server
ClearPreparedStatements();
PayloadData payload;
if (DatabaseOverride is null && (ServerVersion.Version.CompareTo(ServerVersions.SupportsResetConnection) >= 0 || ServerVersion.MariaDbVersion?.CompareTo(ServerVersions.MariaDbSupportsResetConnection) >= 0))
{
m_logArguments[1] = ServerVersion.OriginalString;
Log.Debug("Session{0} ServerVersion={1} supports reset connection; sending reset connection request", m_logArguments);
await SendAsync(ResetConnectionPayload.Instance, ioBehavior, cancellationToken).ConfigureAwait(false);
payload = await ReceiveReplyAsync(ioBehavior, cancellationToken).ConfigureAwait(false);
OkPayload.Create(payload.AsSpan(), SupportsDeprecateEof, SupportsSessionTrack);
}
else
{
// optimistically hash the password with the challenge from the initial handshake (supported by MariaDB; doesn't appear to be supported by MySQL)
if (DatabaseOverride is null)
{
m_logArguments[1] = ServerVersion.OriginalString;
Log.Debug("Session{0} ServerVersion={1} doesn't support reset connection; sending change user request", m_logArguments);
}
else
{
m_logArguments[1] = DatabaseOverride;
Log.Debug("Session{0} sending change user request due to changed Database={1}", m_logArguments);
DatabaseOverride = null;
}
var hashedPassword = AuthenticationUtility.CreateAuthenticationResponse(AuthPluginData, 0, cs.Password);
using (var changeUserPayload = ChangeUserPayload.Create(cs.UserID, hashedPassword, cs.Database, m_characterSet, m_supportsConnectionAttributes ? cs.ConnectionAttributes : null))
await SendAsync(changeUserPayload, ioBehavior, cancellationToken).ConfigureAwait(false);
payload = await ReceiveReplyAsync(ioBehavior, cancellationToken).ConfigureAwait(false);
if (payload.HeaderByte == AuthenticationMethodSwitchRequestPayload.Signature)
{
Log.Debug("Session{0} optimistic reauthentication failed; logging in again", m_logArguments);
payload = await SwitchAuthenticationAsync(cs, payload, ioBehavior, cancellationToken).ConfigureAwait(false);
}
OkPayload.Create(payload.AsSpan(), SupportsDeprecateEof, SupportsSessionTrack);
}
// set 'collation_connection' to the server default
await SendAsync(m_setNamesPayload, ioBehavior, cancellationToken).ConfigureAwait(false);
payload = await ReceiveReplyAsync(ioBehavior, cancellationToken).ConfigureAwait(false);
OkPayload.Create(payload.AsSpan(), SupportsDeprecateEof, SupportsSessionTrack);
return true;
}
catch (IOException ex)
{
Log.Debug(ex, "Session{0} ignoring IOException in TryResetConnectionAsync", m_logArguments);
}
catch (SocketException ex)
{
Log.Debug(ex, "Session{0} ignoring SocketException in TryResetConnectionAsync", m_logArguments);
}
return false;
}
private async Task<PayloadData> SwitchAuthenticationAsync(ConnectionSettings cs, PayloadData payload, IOBehavior ioBehavior, CancellationToken cancellationToken)
{
// if the server didn't support the hashed password; rehash with the new challenge
var switchRequest = AuthenticationMethodSwitchRequestPayload.Create(payload.AsSpan());
m_logArguments[1] = switchRequest.Name;
Log.Debug("Session{0} switching to AuthenticationMethod '{1}'", m_logArguments);
switch (switchRequest.Name)
{
case "mysql_native_password":
AuthPluginData = switchRequest.Data;
var hashedPassword = AuthenticationUtility.CreateAuthenticationResponse(AuthPluginData, 0, cs.Password);
payload = new PayloadData(hashedPassword);
await SendReplyAsync(payload, ioBehavior, cancellationToken).ConfigureAwait(false);
return await ReceiveReplyAsync(ioBehavior, cancellationToken).ConfigureAwait(false);
case "mysql_clear_password":
if (!m_isSecureConnection)
{
Log.Error("Session{0} needs a secure connection to use AuthenticationMethod '{1}'", m_logArguments);
throw new MySqlException("Authentication method '{0}' requires a secure connection.".FormatInvariant(switchRequest.Name));
}
payload = new PayloadData(Encoding.UTF8.GetBytes(cs.Password));
await SendReplyAsync(payload, ioBehavior, cancellationToken).ConfigureAwait(false);
return await ReceiveReplyAsync(ioBehavior, cancellationToken).ConfigureAwait(false);
case "caching_sha2_password":
var scrambleBytes = AuthenticationUtility.CreateScrambleResponse(Utility.TrimZeroByte(switchRequest.Data), cs.Password);
payload = new PayloadData(scrambleBytes);
await SendReplyAsync(payload, ioBehavior, cancellationToken).ConfigureAwait(false);
payload = await ReceiveReplyAsync(ioBehavior, cancellationToken).ConfigureAwait(false);
// OK payload can be sent immediately (e.g., if password is empty( (short-circuiting the )
if (OkPayload.IsOk(payload.AsSpan(), SupportsDeprecateEof))
return payload;
var cachingSha2ServerResponsePayload = CachingSha2ServerResponsePayload.Create(payload.AsSpan());
if (cachingSha2ServerResponsePayload.Succeeded)
return await ReceiveReplyAsync(ioBehavior, cancellationToken).ConfigureAwait(false);
goto case "sha256_password";
case "sha256_password":
if (!m_isSecureConnection && cs.Password.Length > 1)
{
#if NET45
Log.Error("Session{0} can't use AuthenticationMethod '{1}' without secure connection on .NET 4.5", m_logArguments);
throw new MySqlException("Authentication method '{0}' requires a secure connection (prior to .NET 4.6).".FormatInvariant(switchRequest.Name));
#else
var publicKey = await GetRsaPublicKeyAsync(switchRequest.Name, cs, ioBehavior, cancellationToken).ConfigureAwait(false);
return await SendEncryptedPasswordAsync(switchRequest, publicKey, cs, ioBehavior, cancellationToken).ConfigureAwait(false);
#endif
}
else
{
return await SendClearPasswordAsync(cs, ioBehavior, cancellationToken).ConfigureAwait(false);
}
case "auth_gssapi_client":
return await AuthGSSAPI.AuthenticateAsync(cs, switchRequest.Data, this, ioBehavior, cancellationToken).ConfigureAwait(false);
case "mysql_old_password":
Log.Error("Session{0} is requesting AuthenticationMethod '{1}' which is not supported", m_logArguments);
throw new NotSupportedException("'MySQL Server is requesting the insecure pre-4.1 auth mechanism (mysql_old_password). The user password must be upgraded; see https://dev.mysql.com/doc/refman/5.7/en/account-upgrades.html.");
default:
Log.Error("Session{0} is requesting AuthenticationMethod '{1}' which is not supported", m_logArguments);
throw new NotSupportedException("Authentication method '{0}' is not supported.".FormatInvariant(switchRequest.Name));
}
}
private async Task<PayloadData> SendClearPasswordAsync(ConnectionSettings cs, IOBehavior ioBehavior, CancellationToken cancellationToken)
{
// add NUL terminator to password
var passwordBytes = Encoding.UTF8.GetBytes(cs.Password);
Array.Resize(ref passwordBytes, passwordBytes.Length + 1);
// send plaintext password
var payload = new PayloadData(passwordBytes);
await SendReplyAsync(payload, ioBehavior, cancellationToken).ConfigureAwait(false);
return await ReceiveReplyAsync(ioBehavior, cancellationToken).ConfigureAwait(false);
}
#if !NET45
private async Task<PayloadData> SendEncryptedPasswordAsync(
AuthenticationMethodSwitchRequestPayload switchRequest,
string rsaPublicKey,
ConnectionSettings cs,
IOBehavior ioBehavior,
CancellationToken cancellationToken)
{
// load the RSA public key
RSA rsa;
try
{
rsa = Utility.DecodeX509PublicKey(rsaPublicKey);
}
catch (Exception ex)
{
Log.Error(ex, "Session{0} couldn't load server's RSA public key", m_logArguments);
throw new MySqlException("Couldn't load server's RSA public key; try using a secure connection instead.", ex);
}
// add NUL terminator to password
var passwordBytes = Encoding.UTF8.GetBytes(cs.Password);
Array.Resize(ref passwordBytes, passwordBytes.Length + 1);
using (rsa)
{
// XOR the password bytes with the challenge
AuthPluginData = Utility.TrimZeroByte(switchRequest.Data);
for (var i = 0; i < passwordBytes.Length; i++)
passwordBytes[i] ^= AuthPluginData[i % AuthPluginData.Length];
// encrypt with RSA public key
var padding = RSAEncryptionPadding.OaepSHA1;
var encryptedPassword = rsa.Encrypt(passwordBytes, padding);
var payload = new PayloadData(encryptedPassword);
await SendReplyAsync(payload, ioBehavior, cancellationToken).ConfigureAwait(false);
return await ReceiveReplyAsync(ioBehavior, cancellationToken).ConfigureAwait(false);
}
}
#endif
private async Task<string> GetRsaPublicKeyAsync(string switchRequestName, ConnectionSettings cs, IOBehavior ioBehavior, CancellationToken cancellationToken)
{
if (!string.IsNullOrEmpty(cs.ServerRsaPublicKeyFile))
{
try
{
return File.ReadAllText(cs.ServerRsaPublicKeyFile);
}
catch (IOException ex)
{
m_logArguments[1] = cs.ServerRsaPublicKeyFile;
Log.Error(ex, "Session{0} couldn't load server's RSA public key from PublicKeyFile '{1}'", m_logArguments);
throw new MySqlException("Couldn't load server's RSA public key from '{0}'".FormatInvariant(cs.ServerRsaPublicKeyFile), ex);
}
}
if (cs.AllowPublicKeyRetrieval)
{
// request the RSA public key
var payloadContent = switchRequestName == "caching_sha2_password" ? (byte) 0x02 : (byte) 0x01;
await SendReplyAsync(new PayloadData(new[] { payloadContent }), ioBehavior, cancellationToken).ConfigureAwait(false);
var payload = await ReceiveReplyAsync(ioBehavior, cancellationToken).ConfigureAwait(false);
var publicKeyPayload = AuthenticationMoreDataPayload.Create(payload.AsSpan());
return Encoding.ASCII.GetString(publicKeyPayload.Data);
}
m_logArguments[1] = switchRequestName;
Log.Error("Session{0} couldn't use AuthenticationMethod '{1}' because RSA key wasn't specified or couldn't be retrieved", m_logArguments);
throw new MySqlException("Authentication method '{0}' failed. Either use a secure connection, specify the server's RSA public key with ServerRSAPublicKeyFile, or set AllowPublicKeyRetrieval=True.".FormatInvariant(switchRequestName));
}
public async ValueTask<bool> TryPingAsync(IOBehavior ioBehavior, CancellationToken cancellationToken)
{
VerifyState(State.Connected);
// send ping payload to verify client and server socket are still connected
try
{
Log.Debug("Session{0} pinging server", m_logArguments);
await SendAsync(PingPayload.Instance, ioBehavior, cancellationToken).ConfigureAwait(false);
var payload = await ReceiveReplyAsync(ioBehavior, cancellationToken).ConfigureAwait(false);
OkPayload.Create(payload.AsSpan(), SupportsDeprecateEof, SupportsSessionTrack);
Log.Info("Session{0} successfully pinged server", m_logArguments);
return true;
}
catch (IOException ex)
{
Log.Debug(ex, "Session{0} ping failed due to IOException", m_logArguments);
}
catch (SocketException ex)
{
Log.Debug(ex, "Session{0} ping failed due to SocketException", m_logArguments);
}
VerifyState(State.Failed);
return false;
}
// Starts a new conversation with the server by sending the first packet.
public ValueTask<int> SendAsync(PayloadData payload, IOBehavior ioBehavior, CancellationToken cancellationToken)
{
m_payloadHandler.StartNewConversation();
return SendReplyAsync(payload, ioBehavior, cancellationToken);
}
// Starts a new conversation with the server by receiving the first packet.
public ValueTask<PayloadData> ReceiveAsync(IOBehavior ioBehavior, CancellationToken cancellationToken)
{
m_payloadHandler.StartNewConversation();
return ReceiveReplyAsync(ioBehavior, cancellationToken);
}
// Continues a conversation with the server by receiving a response to a packet sent with 'Send' or 'SendReply'.
public ValueTask<PayloadData> ReceiveReplyAsync(IOBehavior ioBehavior, CancellationToken cancellationToken)
{
ValueTask<ArraySegment<byte>> task;
try
{
VerifyConnected();
task = m_payloadHandler.ReadPayloadAsync(m_payloadCache, ProtocolErrorBehavior.Throw, ioBehavior);
}
catch (Exception ex)
{
Log.Info(ex, "Session{0} failed in ReceiveReplyAsync", m_logArguments);
if ((ex as MySqlException)?.Number == (int) MySqlErrorCode.CommandTimeoutExpired)
HandleTimeout();
task = ValueTaskExtensions.FromException<ArraySegment<byte>>(ex);
}
if (task.IsCompletedSuccessfully)
{
var payload = new PayloadData(task.Result);
if (payload.HeaderByte != ErrorPayload.Signature)
return new ValueTask<PayloadData>(payload);
var exception = CreateExceptionForErrorPayload(payload.AsSpan());
return ValueTaskExtensions.FromException<PayloadData>(exception);
}
return new ValueTask<PayloadData>(task.AsTask().ContinueWith(TryAsyncContinuation, cancellationToken, TaskContinuationOptions.LazyCancellation | TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default));
}
// Continues a conversation with the server by sending a reply to a packet received with 'Receive' or 'ReceiveReply'.
public ValueTask<int> SendReplyAsync(PayloadData payload, IOBehavior ioBehavior, CancellationToken cancellationToken)
{
ValueTask<int> task;
try
{
VerifyConnected();
task = m_payloadHandler.WritePayloadAsync(payload.ArraySegment, ioBehavior);
}
catch (Exception ex)
{
Log.Info(ex, "Session{0} failed in SendReplyAsync", m_logArguments);
task = ValueTaskExtensions.FromException<int>(ex);
}
if (task.IsCompletedSuccessfully)
return task;
return new ValueTask<int>(task.AsTask().ContinueWith(TryAsyncContinuation, cancellationToken, TaskContinuationOptions.LazyCancellation | TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default));
}
internal void HandleTimeout()
{
if (OwningConnection != null && OwningConnection.TryGetTarget(out var connection))
connection.SetState(ConnectionState.Closed);
}
private void VerifyConnected()
{
lock (m_lock)
{
if (m_state == State.Closed)
throw new ObjectDisposedException(nameof(ServerSession));
if (m_state != State.Connected && m_state != State.Querying && m_state != State.CancelingQuery && m_state != State.ClearingPendingCancellation && m_state != State.Closing)
throw new InvalidOperationException("ServerSession is not connected.");
}
}
private async Task<bool> OpenTcpSocketAsync(ConnectionSettings cs, ILoadBalancer loadBalancer, IOBehavior ioBehavior, CancellationToken cancellationToken)
{
var hostNames = loadBalancer.LoadBalance(cs.HostNames);
foreach (var hostName in hostNames)
{
IPAddress[] ipAddresses;
try
{
if (ioBehavior == IOBehavior.Asynchronous)
{
ipAddresses = await Dns.GetHostAddressesAsync(hostName).ConfigureAwait(false);
}
else
{
#if NETSTANDARD1_3
// Dns.GetHostAddresses isn't available until netstandard 2.0: https://github.com/dotnet/corefx/pull/11950
ipAddresses = await Dns.GetHostAddressesAsync(hostName).ConfigureAwait(false);
#else
ipAddresses = Dns.GetHostAddresses(hostName);
#endif
}
}
catch (SocketException)
{
// name couldn't be resolved
continue;
}
// need to try IP Addresses one at a time: https://github.com/dotnet/corefx/issues/5829
foreach (var ipAddress in ipAddresses)
{
Log.Info("Session{0} connecting to IpAddress {1} for HostName '{2}'", m_logArguments[0], ipAddress, hostName);
TcpClient tcpClient = null;
try
{
tcpClient = new TcpClient(ipAddress.AddressFamily);
using (cancellationToken.Register(() => tcpClient.Client?.Dispose()))
{
try
{
if (ioBehavior == IOBehavior.Asynchronous)
{
await tcpClient.ConnectAsync(ipAddress, cs.Port).ConfigureAwait(false);
}
else
{
#if NETSTANDARD1_3
await tcpClient.ConnectAsync(ipAddress, cs.Port).ConfigureAwait(false);
#else
if (Utility.IsWindows())
{
tcpClient.Connect(ipAddress, cs.Port);
}
else
{
// non-windows platforms block on synchronous connect, use send/receive timeouts: https://github.com/dotnet/corefx/issues/20954
var originalSendTimeout = tcpClient.Client.SendTimeout;
var originalReceiveTimeout = tcpClient.Client.ReceiveTimeout;
tcpClient.Client.SendTimeout = cs.ConnectionTimeoutMilliseconds;
tcpClient.Client.ReceiveTimeout = cs.ConnectionTimeoutMilliseconds;
tcpClient.Connect(ipAddress, cs.Port);
tcpClient.Client.SendTimeout = originalSendTimeout;
tcpClient.Client.ReceiveTimeout = originalReceiveTimeout;
}
#endif
}
}
catch (ObjectDisposedException ex) when (cancellationToken.IsCancellationRequested)
{
SafeDispose(ref tcpClient);
Log.Info("Session{0} connect timeout expired connecting to IpAddress {1} for HostName '{2}'", m_logArguments[0], ipAddress, hostName);
throw new MySqlException((int) MySqlErrorCode.UnableToConnectToHost, null, "Connect Timeout expired.", ex);
}
}
}
catch (SocketException)
{
SafeDispose(ref tcpClient);
continue;
}
if (!tcpClient.Connected && cancellationToken.IsCancellationRequested)
{
SafeDispose(ref tcpClient);
Log.Info("Session{0} connect timeout expired connecting to IpAddress {1} for HostName '{2}'", m_logArguments[0], ipAddress, hostName);
throw new MySqlException("Connect Timeout expired.");
}
HostName = hostName;
m_tcpClient = tcpClient;
m_socket = m_tcpClient.Client;
m_stream = m_tcpClient.GetStream();
m_socket.SetKeepAlive(cs.Keepalive);
lock (m_lock)
m_state = State.Connected;
Log.Debug("Session{0} connected to IpAddress {1} for HostName '{2}' with local Port {3}", m_logArguments[0], ipAddress, hostName, (m_socket.LocalEndPoint as IPEndPoint)?.Port);
return true;
}
}
return false;
}
private async Task<bool> OpenUnixSocketAsync(ConnectionSettings cs, IOBehavior ioBehavior, CancellationToken cancellationToken)
{
m_logArguments[1] = cs.UnixSocket;
Log.Info("Session{0} connecting to UNIX Socket '{1}'", m_logArguments);
var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);
var unixEp = new UnixEndPoint(cs.UnixSocket);
try
{
using (cancellationToken.Register(() => socket.Dispose()))
{
try
{
if (ioBehavior == IOBehavior.Asynchronous)
{
#if NETSTANDARD1_3
await socket.ConnectAsync(unixEp).ConfigureAwait(false);
#else
await Task.Factory.FromAsync(socket.BeginConnect, socket.EndConnect, unixEp, null).ConfigureAwait(false);
#endif
}
else
{
socket.Connect(unixEp);
}
}
catch (ObjectDisposedException ex) when (cancellationToken.IsCancellationRequested)
{
Log.Info("Session{0} connect timeout expired connecting to UNIX Socket '{1}'", m_logArguments);
throw new MySqlException("Connect Timeout expired.", ex);
}
}
}
catch (SocketException)
{
socket.Dispose();
}
if (socket.Connected)
{
m_socket = socket;
m_stream = new NetworkStream(socket);
lock (m_lock)
m_state = State.Connected;
return true;
}
return false;
}
private Task<bool> OpenNamedPipeAsync(ConnectionSettings cs, IOBehavior ioBehavior, CancellationToken cancellationToken)
{
#if NETSTANDARD1_3
throw new NotSupportedException("Named pipe connections are not supported in netstandard1.3");
#else
if (Log.IsInfoEnabled())
Log.Info("Session{0} connecting to NamedPipe '{1}' on Server '{2}'", m_logArguments[0], cs.PipeName, cs.HostNames[0]);
var namedPipeStream = new NamedPipeClientStream(cs.HostNames[0], cs.PipeName, PipeDirection.InOut, PipeOptions.Asynchronous);
try
{
using (cancellationToken.Register(() => namedPipeStream.Dispose()))
{
try
{
namedPipeStream.Connect();
}
catch (ObjectDisposedException ex) when (cancellationToken.IsCancellationRequested)
{
m_logArguments[1] = cs.PipeName;
Log.Info("Session{0} connect timeout expired connecting to named pipe '{1}'", m_logArguments);
throw new MySqlException("Connect Timeout expired.", ex);
}
}
}
catch (IOException)
{
namedPipeStream.Dispose();
}
if (namedPipeStream.IsConnected)
{
m_stream = namedPipeStream;
lock (m_lock)
m_state = State.Connected;
return Task.FromResult(true);
}
return Task.FromResult(false);
#endif
}
private async Task InitSslAsync(ProtocolCapabilities serverCapabilities, ConnectionSettings cs, SslProtocols sslProtocols, IOBehavior ioBehavior, CancellationToken cancellationToken)
{
Log.Info("Session{0} initializing TLS connection", m_logArguments);
X509CertificateCollection clientCertificates = null;
if (cs.CertificateStoreLocation != MySqlCertificateStoreLocation.None)
{
try
{
var storeLocation = (cs.CertificateStoreLocation == MySqlCertificateStoreLocation.CurrentUser) ? StoreLocation.CurrentUser : StoreLocation.LocalMachine;
var store = new X509Store(StoreName.My, storeLocation);
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
if (cs.CertificateThumbprint is null)
{
if (store.Certificates.Count == 0)
{
Log.Error("Session{0} no certificates were found in the certificate store", m_logArguments);
throw new MySqlException("No certificates were found in the certificate store");
}
clientCertificates = new X509CertificateCollection(store.Certificates);
}
else
{
var requireValid = cs.SslMode == MySqlSslMode.VerifyCA || cs.SslMode == MySqlSslMode.VerifyFull;
var foundCertificates = store.Certificates.Find(X509FindType.FindByThumbprint, cs.CertificateThumbprint, requireValid);
if (foundCertificates.Count == 0)
{
m_logArguments[1] = cs.CertificateThumbprint;
Log.Error("Session{0} certificate with Thumbprint={1} not found in store", m_logArguments);
throw new MySqlException("Certificate with Thumbprint {0} not found".FormatInvariant(cs.CertificateThumbprint));
}
clientCertificates = new X509CertificateCollection(foundCertificates);
}
}
catch (CryptographicException ex)
{
m_logArguments[1] = cs.CertificateStoreLocation;
Log.Error(ex, "Session{0} couldn't load certificate from CertificateStoreLocation={1}", m_logArguments);
throw new MySqlException("Certificate couldn't be loaded from the CertificateStoreLocation", ex);
}
}
if (cs.CertificateFile != null)
{
try
{
var certificate = new X509Certificate2(cs.CertificateFile, cs.CertificatePassword, X509KeyStorageFlags.MachineKeySet);
if (!certificate.HasPrivateKey)
{
m_logArguments[1] = cs.CertificateFile;
Log.Error("Session{0} no private key included with CertificateFile '{1}'", m_logArguments);
throw new MySqlException("CertificateFile does not contain a private key. " +
"CertificateFile should be in PKCS #12 (.pfx) format and contain both a Certificate and Private Key");
}
m_clientCertificate = certificate;
clientCertificates = new X509CertificateCollection { certificate };
}
catch (CryptographicException ex)
{
m_logArguments[1] = cs.CertificateFile;
Log.Error(ex, "Session{0} couldn't load certificate from CertificateFile '{1}'", m_logArguments);
if (!File.Exists(cs.CertificateFile))
throw new MySqlException("Cannot find Certificate File", ex);
throw new MySqlException("Either the Certificate Password is incorrect or the Certificate File is invalid", ex);
}
}
X509Chain caCertificateChain = null;
if (cs.CACertificateFile != null)
{
var certificateChain = new X509Chain
{
ChainPolicy =
{
RevocationMode = X509RevocationMode.NoCheck,
VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority
}
};
try
{
// read the CA Certificate File
m_logArguments[1] = cs.CACertificateFile;