forked from trdtnguyen/mysql-plnvm
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsql_authentication.cc
4181 lines (3582 loc) · 125 KB
/
sql_authentication.cc
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
/* Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
#include "sql_base.h" /* close_mysql_tables */
#include "sql_parse.h" /* check_access */
#include "log.h" /* sql_print_warning, query_logger */
#include <sql_common.h> /* mpvio_info */
#include "sql_connect.h" /* thd_init_client_charset */
/* get_or_create_user_conn */
/* check_for_max_user_connections */
/* release_user_connection */
#include "hostname.h" /* Host_errors, inc_host_errors */
#include "password.h" // my_make_scrambled_password
#include "sql_db.h" /* mysql_change_db */
#include "connection_handler_manager.h"
#include "crypt_genhash_impl.h" /* generate_user_salt */
#include <mysql/plugin_validate_password.h> /* validate_password plugin */
#include <mysql/service_my_plugin_log.h>
#include "sys_vars.h"
#include <fstream> /* std::fstream */
#include <string> /* std::string */
#include <algorithm> /* for_each */
#include <stdexcept> /* Exception handling */
#include <vector> /* std::vector */
#include <stdint.h>
#if defined(HAVE_OPENSSL) && !defined(HAVE_YASSL)
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#include <openssl/x509v3.h>
#endif /* HAVE OPENSSL && !HAVE_YASSL */
#include "auth_internal.h"
#include "sql_auth_cache.h"
#include "sql_authentication.h"
#include "tztime.h"
#include "sql_time.h"
#include <mutex_lock.h>
/****************************************************************************
AUTHENTICATION CODE
including initial connect handshake, invoking appropriate plugins,
client-server plugin negotiation, COM_CHANGE_USER, and native
MySQL authentication plugins.
****************************************************************************/
LEX_CSTRING native_password_plugin_name= {
C_STRING_WITH_LEN("mysql_native_password")
};
LEX_CSTRING sha256_password_plugin_name= {
C_STRING_WITH_LEN("sha256_password")
};
LEX_CSTRING validate_password_plugin_name= {
C_STRING_WITH_LEN("validate_password")
};
LEX_CSTRING default_auth_plugin_name;
plugin_ref native_password_plugin;
my_bool disconnect_on_expired_password= TRUE;
/** Size of the header fields of an authentication packet. */
#define AUTH_PACKET_HEADER_SIZE_PROTO_41 32
#define AUTH_PACKET_HEADER_SIZE_PROTO_40 5
#if defined(HAVE_OPENSSL)
#define MAX_CIPHER_LENGTH 1024
#if !defined(HAVE_YASSL)
#define AUTH_DEFAULT_RSA_PRIVATE_KEY "private_key.pem"
#define AUTH_DEFAULT_RSA_PUBLIC_KEY "public_key.pem"
#define DEFAULT_SSL_CLIENT_CERT "client-cert.pem"
#define DEFAULT_SSL_CLIENT_KEY "client-key.pem"
#define MAX_CN_NAME_LENGTH 64
my_bool opt_auto_generate_certs= TRUE;
char *auth_rsa_private_key_path;
char *auth_rsa_public_key_path;
my_bool auth_rsa_auto_generate_rsa_keys= TRUE;
static bool do_auto_rsa_keys_generation();
static Rsa_authentication_keys g_rsa_keys;
#endif /* HAVE_YASSL */
#endif /* HAVE_OPENSSL */
bool
Thd_charset_adapter::init_client_charset(uint cs_number)
{
if (thd_init_client_charset(thd, cs_number))
return true;
thd->update_charset();
return thd->is_error();
}
const CHARSET_INFO *
Thd_charset_adapter::charset()
{
return thd->charset();
}
#if defined(HAVE_OPENSSL)
#ifndef HAVE_YASSL
/**
@brief Set key file path
@param key[in] Points to either auth_rsa_private_key_path or
auth_rsa_public_key_path.
@param key_file_path[out] Stores value of actual key file path.
*/
void
Rsa_authentication_keys::get_key_file_path(char *key, String *key_file_path)
{
/*
If a fully qualified path is entered use that, else assume the keys are
stored in the data directory.
*/
if (strchr(key, FN_LIBCHAR) != NULL
#ifdef _WIN32
|| strchr(key, FN_LIBCHAR2) != NULL
#endif
)
key_file_path->set_quick(key, strlen(key), system_charset_info);
else
{
key_file_path->append(mysql_real_data_home, strlen(mysql_real_data_home));
if ((*key_file_path)[key_file_path->length()] != FN_LIBCHAR)
key_file_path->append(FN_LIBCHAR);
key_file_path->append(key);
}
}
/**
@brief Read a key file and store its value in RSA structure
@param key_ptr[out] Address of pointer to RSA. This is set to
point to a non null value if key is correctly
read.
@param is_priv_key[in] Whether we are reading private key or public
key.
@param key_text_buffer[out] To store key file content of public key.
@return Error status
@retval false Success : Either both keys are read or none
are.
@retval true Failure : An appropriate error is raised.
*/
bool
Rsa_authentication_keys::read_key_file(RSA **key_ptr,
bool is_priv_key,
char **key_text_buffer)
{
String key_file_path;
char *key;
const char *key_type;
FILE *key_file= NULL;
key= is_priv_key ? auth_rsa_private_key_path : auth_rsa_public_key_path;
key_type= is_priv_key ? "private" : "public";
*key_ptr= NULL;
get_key_file_path(key, &key_file_path);
/*
Check for existance of private key/public key file.
*/
if ((key_file= fopen(key_file_path.c_ptr(), "r")) == NULL)
{
sql_print_information("RSA %s key file not found: %s."
" Some authentication plugins will not work.",
key_type, key_file_path.c_ptr());
}
else
{
*key_ptr= is_priv_key ? PEM_read_RSAPrivateKey(key_file, 0, 0, 0) :
PEM_read_RSA_PUBKEY(key_file, 0, 0, 0);
if (!(*key_ptr))
{
char error_buf[MYSQL_ERRMSG_SIZE];
ERR_error_string_n(ERR_get_error(), error_buf, MYSQL_ERRMSG_SIZE);
sql_print_error("Failure to parse RSA %s key (file exists): %s:"
" %s", key_type, key_file_path.c_ptr(), error_buf);
/*
Call ERR_clear_error() just in case there are more than 1 entry in the
OpenSSL thread's error queue.
*/
ERR_clear_error();
return true;
}
/* For public key, read key file content into a char buffer. */
bool read_error= false;
if (!is_priv_key)
{
int filesize;
fseek(key_file, 0, SEEK_END);
filesize= ftell(key_file);
fseek(key_file, 0, SEEK_SET);
*key_text_buffer= new char[filesize+1];
int items_read= fread(*key_text_buffer, filesize, 1, key_file);
read_error= items_read != 1;
if (read_error)
{
char errbuf[MYSQL_ERRMSG_SIZE];
sql_print_error("Failure to read key file: %s",
my_strerror(errbuf, MYSQL_ERRMSG_SIZE, my_errno()));
}
(*key_text_buffer)[filesize]= '\0';
}
fclose(key_file);
return read_error;
}
return false;
}
Rsa_authentication_keys::Rsa_authentication_keys()
{
m_cipher_len= 0;
m_private_key= 0;
m_public_key= 0;
m_pem_public_key= 0;
}
void
Rsa_authentication_keys::free_memory()
{
if (m_private_key)
RSA_free(m_private_key);
if (m_public_key)
{
RSA_free(m_public_key);
m_cipher_len= 0;
}
if (m_pem_public_key)
delete [] m_pem_public_key;
}
void *
Rsa_authentication_keys::allocate_pem_buffer(size_t buffer_len)
{
m_pem_public_key= new char[buffer_len];
return m_pem_public_key;
}
int
Rsa_authentication_keys::get_cipher_length()
{
return (m_cipher_len= RSA_size(m_public_key));
}
/**
@brief Read RSA private key and public key from file and store them
in m_private_key and m_public_key. Also, read public key in
text format and store it in m_pem_public_key.
@return Error status
@retval false Success : Either both keys are read or none are.
@retval true Failure : An appropriate error is raised.
*/
bool
Rsa_authentication_keys::read_rsa_keys()
{
RSA *rsa_private_key_ptr= NULL;
RSA *rsa_public_key_ptr= NULL;
char *pub_key_buff= NULL;
if ((strlen(auth_rsa_private_key_path) == 0) &&
(strlen(auth_rsa_public_key_path) == 0))
{
sql_print_information("RSA key files not found."
" Some authentication plugins will not work.");
return false;
}
/*
Read private key in RSA format.
*/
if (read_key_file(&rsa_private_key_ptr, true, NULL))
return true;
/*
Read public key in RSA format.
*/
if (read_key_file(&rsa_public_key_ptr, false, &pub_key_buff))
{
if (rsa_private_key_ptr)
RSA_free(rsa_private_key_ptr);
return true;
}
/*
If both key files are read successfully then assign values to following
members of the class
1. m_pem_public_key
2. m_private_key
3. m_public_key
Else clean up.
*/
if (rsa_private_key_ptr && rsa_public_key_ptr)
{
size_t buff_len= strlen(pub_key_buff);
char *pem_file_buffer= (char *)allocate_pem_buffer(buff_len + 1);
strncpy(pem_file_buffer, pub_key_buff, buff_len);
pem_file_buffer[buff_len]= '\0';
m_private_key= rsa_private_key_ptr;
m_public_key= rsa_public_key_ptr;
delete [] pub_key_buff;
}
else
{
if (rsa_private_key_ptr)
RSA_free(rsa_private_key_ptr);
if (rsa_public_key_ptr)
{
delete [] pub_key_buff;
RSA_free(rsa_public_key_ptr);
}
}
return false;
}
#endif /* HAVE_YASSL */
#endif /* HAVE_OPENSSL */
/**
Initialize default authentication plugin based on command line options or
configuration file settings.
@param plugin_name Name of the plugin
@param plugin_name_length Length of the string
*/
int set_default_auth_plugin(char *plugin_name, size_t plugin_name_length)
{
default_auth_plugin_name.str= plugin_name;
default_auth_plugin_name.length= plugin_name_length;
optimize_plugin_compare_by_pointer(&default_auth_plugin_name);
#if defined(HAVE_OPENSSL)
if (default_auth_plugin_name.str == sha256_password_plugin_name.str)
{
/*
Adjust default password algorithm to fit the default authentication
method.
*/
global_system_variables.old_passwords= 2;
}
else
#endif /* HAVE_OPENSSL */
if (default_auth_plugin_name.str != native_password_plugin_name.str)
return 1;
return 0;
}
void optimize_plugin_compare_by_pointer(LEX_CSTRING *plugin_name)
{
#if defined(HAVE_OPENSSL)
if (my_strcasecmp(system_charset_info, sha256_password_plugin_name.str,
plugin_name->str) == 0)
{
plugin_name->str= sha256_password_plugin_name.str;
plugin_name->length= sha256_password_plugin_name.length;
}
else
#endif
if (my_strcasecmp(system_charset_info, native_password_plugin_name.str,
plugin_name->str) == 0)
{
plugin_name->str= native_password_plugin_name.str;
plugin_name->length= native_password_plugin_name.length;
}
}
bool auth_plugin_is_built_in(const char *plugin_name)
{
return (plugin_name == native_password_plugin_name.str
#if defined(HAVE_OPENSSL)
|| plugin_name == sha256_password_plugin_name.str
#endif
);
}
/**
Only the plugins that are known to use the mysql.user table
to store their passwords support password expiration atm.
TODO: create a service and extend the plugin API to support
password expiration for external plugins.
@retval false expiration not supported
@retval true expiration supported
*/
bool auth_plugin_supports_expiration(const char *plugin_name)
{
return (!plugin_name || !*plugin_name ||
plugin_name == native_password_plugin_name.str
#if defined(HAVE_OPENSSL)
|| plugin_name == sha256_password_plugin_name.str
#endif
);
}
/* few defines to have less ifdef's in the code below */
#ifdef EMBEDDED_LIBRARY
#undef HAVE_OPENSSL
#ifdef NO_EMBEDDED_ACCESS_CHECKS
#define initialized 0
#endif /* NO_EMBEDDED_ACCESS_CHECKS */
#endif /* EMBEDDED_LIBRARY */
#ifndef HAVE_OPENSSL
#define ssl_acceptor_fd 0
#define sslaccept(A,B,C) 1
#endif /* HAVE_OPENSSL */
/**
a helper function to report an access denied error in all the proper places
*/
static void login_failed_error(MPVIO_EXT *mpvio, int passwd_used)
{
THD *thd= current_thd;
if (passwd_used == 2)
{
my_error(ER_ACCESS_DENIED_NO_PASSWORD_ERROR, MYF(0),
mpvio->auth_info.user_name,
mpvio->auth_info.host_or_ip);
query_logger.general_log_print(thd, COM_CONNECT,
ER(ER_ACCESS_DENIED_NO_PASSWORD_ERROR),
mpvio->auth_info.user_name,
mpvio->auth_info.host_or_ip);
/*
Log access denied messages to the error log when log-warnings = 2
so that the overhead of the general query log is not required to track
failed connections.
*/
sql_print_information(ER(ER_ACCESS_DENIED_NO_PASSWORD_ERROR),
mpvio->auth_info.user_name,
mpvio->auth_info.host_or_ip);
}
else
{
my_error(ER_ACCESS_DENIED_ERROR, MYF(0),
mpvio->auth_info.user_name,
mpvio->auth_info.host_or_ip,
passwd_used ? ER(ER_YES) : ER(ER_NO));
query_logger.general_log_print(thd, COM_CONNECT, ER(ER_ACCESS_DENIED_ERROR),
mpvio->auth_info.user_name,
mpvio->auth_info.host_or_ip,
passwd_used ? ER(ER_YES) : ER(ER_NO));
/*
Log access denied messages to the error log when log-warnings = 2
so that the overhead of the general query log is not required to track
failed connections.
*/
sql_print_information(ER(ER_ACCESS_DENIED_ERROR),
mpvio->auth_info.user_name,
mpvio->auth_info.host_or_ip,
passwd_used ? ER(ER_YES) : ER(ER_NO));
}
}
/**
sends a server handshake initialization packet, the very first packet
after the connection was established
Packet format:
Bytes Content
----- ----
1 protocol version (always 10)
n server version string, \0-terminated
4 thread id
8 first 8 bytes of the plugin provided data (scramble)
1 \0 byte, terminating the first part of a scramble
2 server capabilities (two lower bytes)
1 server character set
2 server status
2 server capabilities (two upper bytes)
1 length of the scramble
10 reserved, always 0
n rest of the plugin provided data (at least 12 bytes)
1 \0 byte, terminating the second part of a scramble
@retval 0 ok
@retval 1 error
*/
static bool send_server_handshake_packet(MPVIO_EXT *mpvio,
const char *data, uint data_len)
{
DBUG_ASSERT(mpvio->status == MPVIO_EXT::FAILURE);
DBUG_ASSERT(data_len <= 255);
Protocol_classic *protocol= mpvio->protocol;
char *buff= (char *) my_alloca(1 + SERVER_VERSION_LENGTH + data_len + 64);
char scramble_buf[SCRAMBLE_LENGTH];
char *end= buff;
DBUG_ENTER("send_server_handshake_packet");
*end++= protocol_version;
protocol->set_client_capabilities(CLIENT_BASIC_FLAGS);
if (opt_using_transactions)
protocol->add_client_capability(CLIENT_TRANSACTIONS);
protocol->add_client_capability(CAN_CLIENT_COMPRESS);
if (ssl_acceptor_fd)
{
protocol->add_client_capability(CLIENT_SSL);
protocol->add_client_capability(CLIENT_SSL_VERIFY_SERVER_CERT);
}
if (data_len)
{
mpvio->cached_server_packet.pkt= (char*) memdup_root(mpvio->mem_root,
data, data_len);
mpvio->cached_server_packet.pkt_len= data_len;
}
if (data_len < SCRAMBLE_LENGTH)
{
if (data_len)
{
/*
the first packet *must* have at least 20 bytes of a scramble.
if a plugin provided less, we pad it to 20 with zeros
*/
memcpy(scramble_buf, data, data_len);
memset(scramble_buf + data_len, 0, SCRAMBLE_LENGTH - data_len);
data= scramble_buf;
}
else
{
/*
if the default plugin does not provide the data for the scramble at
all, we generate a scramble internally anyway, just in case the
user account (that will be known only later) uses a
native_password_plugin (which needs a scramble). If we don't send a
scramble now - wasting 20 bytes in the packet -
native_password_plugin will have to send it in a separate packet,
adding one more round trip.
*/
generate_user_salt(mpvio->scramble, SCRAMBLE_LENGTH + 1);
data= mpvio->scramble;
}
data_len= SCRAMBLE_LENGTH;
}
end= my_stpnmov(end, server_version, SERVER_VERSION_LENGTH) + 1;
DBUG_ASSERT(sizeof(my_thread_id) == 4);
int4store((uchar*) end, mpvio->thread_id);
end+= 4;
/*
Old clients does not understand long scrambles, but can ignore packet
tail: that's why first part of the scramble is placed here, and second
part at the end of packet.
*/
end= (char*) memcpy(end, data, AUTH_PLUGIN_DATA_PART_1_LENGTH);
end+= AUTH_PLUGIN_DATA_PART_1_LENGTH;
*end++= 0;
int2store(end, static_cast<uint16>(protocol->get_client_capabilities()));
/* write server characteristics: up to 16 bytes allowed */
end[2]= (char) default_charset_info->number;
int2store(end + 3, mpvio->server_status[0]);
int2store(end + 5, protocol->get_client_capabilities() >> 16);
end[7]= data_len;
DBUG_EXECUTE_IF("poison_srv_handshake_scramble_len", end[7]= -100;);
memset(end + 8, 0, 10);
end+= 18;
/* write scramble tail */
end= (char*) memcpy(end, data + AUTH_PLUGIN_DATA_PART_1_LENGTH,
data_len - AUTH_PLUGIN_DATA_PART_1_LENGTH);
end+= data_len - AUTH_PLUGIN_DATA_PART_1_LENGTH;
end= strmake(end, plugin_name(mpvio->plugin)->str,
plugin_name(mpvio->plugin)->length);
int res= protocol->write((uchar*) buff, (size_t) (end - buff + 1)) ||
protocol->flush_net();
DBUG_RETURN (res);
}
/**
sends a "change plugin" packet, requesting a client to restart authentication
using a different authentication plugin
Packet format:
Bytes Content
----- ----
1 byte with the value 254
n client plugin to use, \0-terminated
n plugin provided data
@retval 0 ok
@retval 1 error
*/
static bool send_plugin_request_packet(MPVIO_EXT *mpvio,
const uchar *data, uint data_len)
{
DBUG_ASSERT(mpvio->packets_written == 1);
DBUG_ASSERT(mpvio->packets_read == 1);
static uchar switch_plugin_request_buf[]= { 254 };
DBUG_ENTER("send_plugin_request_packet");
mpvio->status= MPVIO_EXT::FAILURE; // the status is no longer RESTART
const char *client_auth_plugin=
((st_mysql_auth *) (plugin_decl(mpvio->plugin)->info))->client_auth_plugin;
DBUG_ASSERT(client_auth_plugin);
/*
If we're dealing with an older client we can't just send a change plugin
packet to re-initiate the authentication handshake, because the client
won't understand it. The good thing is that we don't need to : the old client
expects us to just check the user credentials here, which we can do by just reading
the cached data that are placed there by parse_com_change_user_packet()
In this case we just do nothing and behave as if normal authentication
should continue.
*/
if (!(mpvio->protocol->has_client_capability(CLIENT_PLUGIN_AUTH)))
{
DBUG_PRINT("info", ("old client sent a COM_CHANGE_USER"));
DBUG_ASSERT(mpvio->cached_client_reply.pkt);
/* get the status back so the read can process the cached result */
mpvio->status= MPVIO_EXT::RESTART;
DBUG_RETURN(0);
}
DBUG_PRINT("info", ("requesting client to use the %s plugin",
client_auth_plugin));
DBUG_RETURN(net_write_command(mpvio->protocol->get_net(),
switch_plugin_request_buf[0],
(uchar*) client_auth_plugin,
strlen(client_auth_plugin) + 1,
(uchar*) data, data_len));
}
#ifndef NO_EMBEDDED_ACCESS_CHECKS
/* Return true if there is no users that can match the given host */
bool acl_check_host(const char *host, const char *ip)
{
mysql_mutex_lock(&acl_cache->lock);
if (allow_all_hosts)
{
mysql_mutex_unlock(&acl_cache->lock);
return 0;
}
if ((host && my_hash_search(&acl_check_hosts,(uchar*) host,strlen(host))) ||
(ip && my_hash_search(&acl_check_hosts,(uchar*) ip, strlen(ip))))
{
mysql_mutex_unlock(&acl_cache->lock);
return 0; // Found host
}
for (ACL_HOST_AND_IP *acl= acl_wild_hosts->begin();
acl != acl_wild_hosts->end(); ++acl)
{
if (acl->compare_hostname(host, ip))
{
mysql_mutex_unlock(&acl_cache->lock);
return 0; // Host ok
}
}
mysql_mutex_unlock(&acl_cache->lock);
if (ip != NULL)
{
/* Increment HOST_CACHE.COUNT_HOST_ACL_ERRORS. */
Host_errors errors;
errors.m_host_acl= 1;
inc_host_errors(ip, &errors);
}
return 1; // Host is not allowed
}
/**
When authentication is attempted using an unknown username a dummy user
account with no authentication capabilites is assigned to the connection.
This is done increase the cost of enumerating user accounts based on
authentication protocol.
*/
ACL_USER *decoy_user(const LEX_STRING &username,
MEM_ROOT *mem)
{
ACL_USER *user= (ACL_USER *) alloc_root(mem, sizeof(ACL_USER));
user->can_authenticate= false;
user->user= strdup_root(mem, username.str);
user->user[username.length]= '\0';
user->auth_string= empty_lex_str;
user->ssl_cipher= empty_c_string;
user->x509_issuer= empty_c_string;
user->x509_subject= empty_c_string;
user->salt_len= 0;
user->password_last_changed.time_type= MYSQL_TIMESTAMP_ERROR;
user->password_lifetime= 0;
user->use_default_password_lifetime= true;
user->account_locked= false;
/*
For now the common default account is used. Improvements might involve
mapping a consistent hash of a username to a range of plugins.
*/
user->plugin= default_auth_plugin_name;
return user;
}
/**
Finds acl entry in user database for authentication purposes.
Finds a user and copies it into mpvio. Reports an authentication
failure if a user is not found.
@note find_acl_user is not the same, because it doesn't take into
account the case when user is not empty, but acl_user->user is empty
@retval 0 found
@retval 1 not found
*/
static bool find_mpvio_user(MPVIO_EXT *mpvio)
{
DBUG_ENTER("find_mpvio_user");
DBUG_PRINT("info", ("entry: %s", mpvio->auth_info.user_name));
DBUG_ASSERT(mpvio->acl_user == 0);
mysql_mutex_lock(&acl_cache->lock);
for (ACL_USER *acl_user_tmp= acl_users->begin();
acl_user_tmp != acl_users->end(); ++acl_user_tmp)
{
if ((!acl_user_tmp->user ||
!strcmp(mpvio->auth_info.user_name, acl_user_tmp->user)) &&
acl_user_tmp->host.compare_hostname(mpvio->host, mpvio->ip))
{
mpvio->acl_user= acl_user_tmp->copy(mpvio->mem_root);
/*
When setting mpvio->acl_user_plugin we can save memory allocation if
this is a built in plugin.
*/
if (auth_plugin_is_built_in(acl_user_tmp->plugin.str))
mpvio->acl_user_plugin= mpvio->acl_user->plugin;
else
make_lex_string_root(mpvio->mem_root,
&mpvio->acl_user_plugin,
acl_user_tmp->plugin.str,
acl_user_tmp->plugin.length, 0);
break;
}
}
mysql_mutex_unlock(&acl_cache->lock);
if (!mpvio->acl_user)
{
/*
Pretend the user exists; let the plugin decide how to handle
bad credentials.
*/
LEX_STRING usr= { mpvio->auth_info.user_name,
mpvio->auth_info.user_name_length };
mpvio->acl_user= decoy_user(usr, mpvio->mem_root);
mpvio->acl_user_plugin= mpvio->acl_user->plugin;
}
if (my_strcasecmp(system_charset_info, mpvio->acl_user->plugin.str,
native_password_plugin_name.str) != 0 &&
!(mpvio->protocol->has_client_capability(CLIENT_PLUGIN_AUTH)))
{
/* user account requires non-default plugin and the client is too old */
DBUG_ASSERT(my_strcasecmp(system_charset_info, mpvio->acl_user->plugin.str,
native_password_plugin_name.str));
my_error(ER_NOT_SUPPORTED_AUTH_MODE, MYF(0));
query_logger.general_log_print(current_thd, COM_CONNECT,
ER(ER_NOT_SUPPORTED_AUTH_MODE));
DBUG_RETURN (1);
}
mpvio->auth_info.auth_string= mpvio->acl_user->auth_string.str;
mpvio->auth_info.auth_string_length=
(unsigned long) mpvio->acl_user->auth_string.length;
strmake(mpvio->auth_info.authenticated_as, mpvio->acl_user->user ?
mpvio->acl_user->user : "", USERNAME_LENGTH);
DBUG_PRINT("info", ("exit: user=%s, auth_string=%s, authenticated as=%s"
", plugin=%s",
mpvio->auth_info.user_name,
mpvio->auth_info.auth_string,
mpvio->auth_info.authenticated_as,
mpvio->acl_user->plugin.str));
DBUG_RETURN(0);
}
static bool
read_client_connect_attrs(char **ptr, size_t *max_bytes_available,
const CHARSET_INFO *from_cs)
{
size_t length, length_length;
char *ptr_save;
/* not enough bytes to hold the length */
if (*max_bytes_available < 1)
return true;
/* read the length */
ptr_save= *ptr;
length= static_cast<size_t>(net_field_length_ll((uchar **) ptr));
length_length= *ptr - ptr_save;
if (*max_bytes_available < length_length)
return true;
*max_bytes_available-= length_length;
/* length says there're more data than can fit into the packet */
if (length > *max_bytes_available)
return true;
/* impose an artificial length limit of 64k */
if (length > 65535)
return true;
#ifdef HAVE_PSI_THREAD_INTERFACE
if (PSI_THREAD_CALL(set_thread_connect_attrs)(*ptr, length, from_cs))
sql_print_warning("Connection attributes of length %lu were truncated",
(unsigned long) length);
#endif /* HAVE_PSI_THREAD_INTERFACE */
return false;
}
static bool acl_check_ssl(THD *thd, const ACL_USER *acl_user)
{
#if defined(HAVE_OPENSSL)
Vio *vio= thd->get_protocol_classic()->get_vio();
SSL *ssl= thd->get_protocol()->get_ssl();
X509 *cert;
#endif /* HAVE_OPENSSL */
/*
At this point we know that user is allowed to connect
from given host by given username/password pair. Now
we check if SSL is required, if user is using SSL and
if X509 certificate attributes are OK
*/
switch (acl_user->ssl_type) {
case SSL_TYPE_NOT_SPECIFIED: // Impossible
case SSL_TYPE_NONE: // SSL is not required
return 0;
#if defined(HAVE_OPENSSL)
case SSL_TYPE_ANY: // Any kind of SSL is ok
return vio_type(vio) != VIO_TYPE_SSL;
case SSL_TYPE_X509: /* Client should have any valid certificate. */
/*
Connections with non-valid certificates are dropped already
in sslaccept() anyway, so we do not check validity here.
We need to check for absence of SSL because without SSL
we should reject connection.
*/
if (vio_type(vio) == VIO_TYPE_SSL &&
SSL_get_verify_result(ssl) == X509_V_OK &&
(cert= SSL_get_peer_certificate(ssl)))
{
X509_free(cert);
return 0;
}
return 1;
case SSL_TYPE_SPECIFIED: /* Client should have specified attrib */
/* If a cipher name is specified, we compare it to actual cipher in use. */
if (vio_type(vio) != VIO_TYPE_SSL ||
SSL_get_verify_result(ssl) != X509_V_OK)
return 1;
if (acl_user->ssl_cipher)
{
DBUG_PRINT("info", ("comparing ciphers: '%s' and '%s'",
acl_user->ssl_cipher, SSL_get_cipher(ssl)));
if (strcmp(acl_user->ssl_cipher, SSL_get_cipher(ssl)))
{
sql_print_information("X509 ciphers mismatch: should be '%s' but is '%s'",
acl_user->ssl_cipher, SSL_get_cipher(ssl));
return 1;
}
}
/* Prepare certificate (if exists) */
if (!(cert= SSL_get_peer_certificate(ssl)))
return 1;
/* If X509 issuer is specified, we check it... */
if (acl_user->x509_issuer)
{
char *ptr= X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0);
DBUG_PRINT("info", ("comparing issuers: '%s' and '%s'",
acl_user->x509_issuer, ptr));
if (strcmp(acl_user->x509_issuer, ptr))
{
sql_print_information("X509 issuer mismatch: should be '%s' "
"but is '%s'", acl_user->x509_issuer, ptr);
OPENSSL_free(ptr);
X509_free(cert);
return 1;
}
OPENSSL_free(ptr);
}
/* X509 subject is specified, we check it .. */
if (acl_user->x509_subject)
{
char *ptr= X509_NAME_oneline(X509_get_subject_name(cert), 0, 0);
DBUG_PRINT("info", ("comparing subjects: '%s' and '%s'",
acl_user->x509_subject, ptr));
if (strcmp(acl_user->x509_subject, ptr))
{
sql_print_information("X509 subject mismatch: should be '%s' but is '%s'",
acl_user->x509_subject, ptr);
OPENSSL_free(ptr);
X509_free(cert);
return 1;
}
OPENSSL_free(ptr);
}
X509_free(cert);
return 0;
#else /* HAVE_OPENSSL */
default:
/*
If we don't have SSL but SSL is required for this user the
authentication should fail.
*/
return 1;
#endif /* HAVE_OPENSSL */
}
return 1;
}
/**
Check if server has valid public key/private key
pair for RSA communication.
@return
@retval false RSA support is available
@retval true RSA support is not available
*/
bool rsa_auth_status()
{
#if !defined(HAVE_OPENSSL) || defined(HAVE_YASSL)
return false;
#else
return (!g_rsa_keys.get_private_key() || !g_rsa_keys.get_public_key());
#endif /* !HAVE_OPENSSL || HAVE_YASSL */
}