forked from alibaba/AliSQL
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsql_user.cc
More file actions
3703 lines (3315 loc) · 134 KB
/
sql_user.cc
File metadata and controls
3703 lines (3315 loc) · 134 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
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, 2025, Oracle and/or its affiliates.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2.0,
as published by the Free Software Foundation.
This program is designed to work with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have either included with
the program or referenced in the documentation.
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, version 2.0, 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 <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <algorithm>
#include <memory>
#include <set>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include "lex_string.h"
#include "m_ctype.h"
#include "m_string.h"
#include "map_helpers.h"
#include "mutex_lock.h" // Mutex_lock
#include "my_alloc.h"
#include "my_base.h"
#include "my_cleanse.h"
#include "my_compiler.h"
#include "my_dbug.h"
#include "my_inttypes.h"
#include "my_loglevel.h"
#include "my_sqlcommand.h"
#include "my_sys.h"
#include "my_time.h"
#include "mysql/components/my_service.h"
#include "mysql/components/services/bits/psi_bits.h"
#include "mysql/components/services/log_builtins.h"
#include "mysql/components/services/log_shared.h"
#include "mysql/components/services/validate_password.h"
#include "mysql/mysql_lex_string.h"
#include "mysql/plugin.h"
#include "mysql/plugin_audit.h"
#include "mysql/plugin_auth.h"
#include "mysql/psi/mysql_mutex.h"
#include "mysql_com.h"
#include "mysql_time.h"
#include "mysqld_error.h"
#include "password.h" /* my_make_scrambled_password */
#include "scope_guard.h"
#include "sql/auth/auth_acls.h"
#include "sql/auth/auth_common.h"
#include "sql/auth/dynamic_privilege_table.h"
#include "sql/auth/sql_security_ctx.h"
#include "sql/dd/cache/dictionary_client.h"
#include "sql/dd/types/function.h" // dd::Function
#include "sql/dd/types/procedure.h" // dd::Procedure
#include "sql/dd/types/routine.h"
#include "sql/dd/types/table.h" // dd::Table
#include "sql/dd/types/trigger.h" // dd::Trigger
#include "sql/dd/types/view.h"
#include "sql/debug_sync.h" // DEBUG_SYNC
#include "sql/field.h"
#include "sql/handler.h"
#include "sql/item.h"
#include "sql/key.h"
#include "sql/log_event.h" /* append_query_string */
#include "sql/protocol.h"
#include "sql/sql_audit.h"
#include "sql/sql_base.h" // open table
#include "sql/sql_class.h"
#include "sql/sql_connect.h"
#include "sql/sql_const.h"
#include "sql/sql_error.h"
#include "sql/sql_lex.h"
#include "sql/sql_list.h"
#include "sql/sql_parse.h" /* check_access */
#include "sql/sql_plugin.h" /* lock_plugin_data etc. */
#include "sql/sql_plugin_ref.h"
#include "sql/strfunc.h"
#include "sql/system_variables.h"
#include "sql/table.h"
#include "sql/thd_raii.h"
#include "sql_string.h"
#include "violite.h"
/* key_restore */
#include "prealloced_array.h"
#include "sql/auth/auth_internal.h"
#include "sql/auth/sql_auth_cache.h"
#include "sql/auth/sql_authentication.h"
#include "sql/auth/sql_mfa.h"
#include "sql/auth/sql_user_table.h"
#include "sql/current_thd.h"
#include "sql/derror.h" /* ER_THD */
#include "sql/log.h"
#include "sql/mysqld.h"
#include "sql/sql_rewrite.h"
#include <openssl/rand.h> // RAND_bytes
/**
Auxiliary function for constructing a user list string.
This function is used for error reporting and logging.
@param thd Thread context
@param str A String to store the user list.
@param user A LEX_USER which will be appended into user list.
@param comma If true, append a ',' before the the user.
*/
void log_user(THD *thd, String *str, LEX_USER *user, bool comma = true) {
String from_user(user->user.str, user->user.length, system_charset_info);
String from_plugin(user->first_factor_auth_info.plugin.str,
user->first_factor_auth_info.plugin.length,
system_charset_info);
String from_auth(user->first_factor_auth_info.auth.str,
user->first_factor_auth_info.auth.length,
system_charset_info);
String from_host(user->host.str, user->host.length, system_charset_info);
if (comma) str->append(',');
append_query_string(thd, system_charset_info, &from_user, str);
str->append(STRING_WITH_LEN("@"));
append_query_string(thd, system_charset_info, &from_host, str);
}
extern bool initialized;
/*
Enumeration of various ACL's and Hashes used in handle_grant_struct()
*/
enum enum_acl_lists {
USER_ACL = 0,
DB_ACL,
COLUMN_PRIVILEGES_HASH,
PROC_PRIVILEGES_HASH,
FUNC_PRIVILEGES_HASH,
PROXY_USERS_ACL
};
bool check_change_password(THD *thd, const char *host, const char *user,
bool retain_current_password) {
Security_context *sctx;
assert(initialized);
sctx = thd->security_context();
if (!thd->slave_thread &&
(strcmp(sctx->user().str, user) ||
my_strcasecmp(system_charset_info, host, sctx->priv_host().str))) {
if (sctx->password_expired()) {
my_error(ER_MUST_CHANGE_PASSWORD, MYF(0));
return true;
}
if (check_access(thd, UPDATE_ACL, consts::mysql.c_str(), nullptr, nullptr,
true, false))
return true;
if (sctx->can_operate_with({user, host}, consts::system_user)) return true;
}
if (retain_current_password) {
if (check_access(thd, UPDATE_ACL, consts::mysql.c_str(), nullptr, nullptr,
true, true) &&
!(sctx->check_access(CREATE_USER_ACL, consts::mysql)) &&
!(sctx->has_global_grant(STRING_WITH_LEN("APPLICATION_PASSWORD_ADMIN"))
.first)) {
my_error(ER_SPECIFIC_ACCESS_DENIED_ERROR, MYF(0),
"CREATE USER or APPLICATION_PASSWORD_ADMIN");
return true;
}
}
if (!thd->slave_thread && likely((get_server_state() == SERVER_OPERATING)) &&
!strcmp(thd->security_context()->priv_user().str, "")) {
my_error(ER_PASSWORD_ANONYMOUS_USER, MYF(0));
return true;
}
return false;
}
/**
Auxiliary function for the CAN_ACCESS_USER internal function
used to check if a row from mysql.user can be accessed or not
by the current user
@arg thd the current thread
@arg user_arg the user account to check
@retval true the current user can access the user
@retval false the current user can't access the user
@sa @ref Item_func_can_access_user, @ref dd::system_views::User_attributes
*/
bool acl_can_access_user(THD *thd, LEX_USER *user_arg) {
/* if ACL is not initialized show everything */
if (!initialized) return true;
/* show everything if slave thread */
if (thd->slave_thread) return true;
LEX_USER *user = get_current_user(thd, user_arg);
/* hide the rows whose user can't be inited */
if (!user) return false;
Security_context *sctx = thd->security_context();
/* show if it's the same user */
if (!strcmp(sctx->priv_user().str, user->user.str) &&
!my_strcasecmp(system_charset_info, user->host.str,
sctx->priv_host().str))
return true;
/* show if the current user has UPDATE on mysql.* */
if (!check_access(thd, UPDATE_ACL, consts::mysql.c_str(), nullptr, nullptr,
true, true))
return true;
/* show if the current user has SELECT on mysql.* */
if (!check_access(thd, SELECT_ACL, consts::mysql.c_str(), nullptr, nullptr,
true, true))
return true;
/* disable if the current user doesn't have SYSTEM_USER and the user account
* checked does */
if (sctx->can_operate_with(user, consts::system_user, false, true, false))
return false;
/* show if the current user has CREATE ACL, otherwise hide */
return sctx->check_access(CREATE_USER_ACL, consts::mysql);
}
/**
Auxiliary function for constructing CREATE USER sql for a given user.
@param thd Thread context
@param user_name user for which the sql should be constructed.
@param are_both_users_same If the command is issued for self or not.
@retval
0 OK.
1 Error.
*/
bool mysql_show_create_user(THD *thd, LEX_USER *user_name,
bool are_both_users_same) {
int error = 0;
ACL_USER *acl_user;
LEX *lex = thd->lex;
Protocol *protocol = thd->get_protocol();
USER_RESOURCES tmp_user_resource;
enum SSL_type ssl_type;
const char *ssl_cipher, *x509_issuer, *x509_subject;
static const int COMMAND_BUFFER_LENGTH = 2048;
char buff[COMMAND_BUFFER_LENGTH];
Item_string *field = nullptr;
String sql_text(buff, sizeof(buff), system_charset_info);
LEX_ALTER alter_info;
List_of_auth_id_refs default_roles;
List<LEX_USER> *old_default_roles = lex->default_roles;
bool hide_password_hash = false;
DBUG_TRACE;
Table_ref table_list("mysql", "user", TL_READ, MDL_SHARED_READ_ONLY);
if (are_both_users_same) {
hide_password_hash =
check_table_access(thd, SELECT_ACL, &table_list, false, UINT_MAX, true);
}
/*
Open user table so we later can read the JSON data in the user_attribute
field. All tables must be opened before the acl_cache_lock
*/
if (open_and_lock_tables(thd, &table_list, MYSQL_LOCK_IGNORE_TIMEOUT)) {
if (!is_expected_or_transient_error(thd)) {
LogErr(ERROR_LEVEL, ER_AUTHCACHE_CANT_OPEN_AND_LOCK_PRIVILEGE_TABLES,
thd->get_stmt_da()->message_text());
}
return true;
}
Acl_cache_lock_guard acl_cache_lock(thd, Acl_cache_lock_mode::READ_MODE);
if (!acl_cache_lock.lock()) {
close_thread_tables(thd);
return true;
}
Acl_table_intact table_intact(thd);
if (table_intact.check(table_list.table, ACL_TABLES::TABLE_USER)) {
close_thread_tables(thd);
return true;
}
if (!(acl_user =
find_acl_user(user_name->host.str, user_name->user.str, true))) {
String wrong_users;
log_user(thd, &wrong_users, user_name, wrong_users.length() > 0);
my_error(ER_CANNOT_USER, MYF(0), "SHOW CREATE USER",
wrong_users.c_ptr_safe());
close_thread_tables(thd);
return true;
}
/* fill in plugin, auth_str from acl_user */
user_name->first_factor_auth_info.auth.str =
acl_user->credentials[PRIMARY_CRED].m_auth_string.str;
user_name->first_factor_auth_info.auth.length =
acl_user->credentials[PRIMARY_CRED].m_auth_string.length;
user_name->first_factor_auth_info.plugin = acl_user->plugin;
user_name->first_factor_auth_info.uses_identified_by_clause = true;
user_name->first_factor_auth_info.uses_identified_with_clause = false;
user_name->first_factor_auth_info.uses_authentication_string_clause = false;
user_name->retain_current_password = false;
user_name->discard_old_password = false;
/* fill in details related to MFA methods */
if (acl_user->m_mfa)
acl_user->m_mfa->get_info_for_query_rewrite(thd, user_name);
/* make a copy of user resources, ssl and password expire attributes */
tmp_user_resource = lex->mqh;
lex->mqh = acl_user->user_resource;
/* Set specified_limits flags so user resources are shown properly. */
if (lex->mqh.user_conn)
lex->mqh.specified_limits |= USER_RESOURCES::USER_CONNECTIONS;
if (lex->mqh.questions)
lex->mqh.specified_limits |= USER_RESOURCES::QUERIES_PER_HOUR;
if (lex->mqh.updates)
lex->mqh.specified_limits |= USER_RESOURCES::UPDATES_PER_HOUR;
if (lex->mqh.conn_per_hour)
lex->mqh.specified_limits |= USER_RESOURCES::CONNECTIONS_PER_HOUR;
ssl_type = lex->ssl_type;
ssl_cipher = lex->ssl_cipher;
x509_issuer = lex->x509_issuer;
x509_subject = lex->x509_subject;
lex->ssl_type = acl_user->ssl_type;
lex->ssl_cipher = acl_user->ssl_cipher;
lex->x509_issuer = acl_user->x509_issuer;
lex->x509_subject = acl_user->x509_subject;
alter_info = lex->alter_password;
lex->alter_password.update_password_expired_column =
acl_user->password_expired;
lex->alter_password.use_default_password_lifetime =
acl_user->use_default_password_lifetime;
lex->alter_password.expire_after_days = acl_user->password_lifetime;
lex->alter_password.update_account_locked_column = true;
lex->alter_password.account_locked = acl_user->account_locked;
lex->alter_password.update_password_expired_fields = true;
lex->alter_password.password_history_length =
acl_user->password_history_length;
lex->alter_password.use_default_password_history =
acl_user->use_default_password_history;
lex->alter_password.update_password_history =
!acl_user->use_default_password_history;
lex->alter_password.password_reuse_interval =
acl_user->password_reuse_interval;
lex->alter_password.use_default_password_reuse_interval =
acl_user->use_default_password_reuse_interval;
lex->alter_password.update_password_reuse_interval =
!acl_user->use_default_password_reuse_interval;
lex->alter_password.update_password_require_current =
acl_user->password_require_current;
lex->alter_password.failed_login_attempts =
acl_user->password_locked_state.get_failed_login_attempts();
lex->alter_password.password_lock_time =
acl_user->password_locked_state.get_password_lock_time_days();
lex->alter_password.update_failed_login_attempts =
lex->alter_password.failed_login_attempts != 0;
lex->alter_password.update_password_lock_time =
lex->alter_password.password_lock_time != 0;
/* send the metadata to client */
field = new Item_string("", 0, &my_charset_latin1);
field->max_length = 256;
strxmov(buff, "CREATE USER for ", user_name->user.str, "@",
user_name->host.str, NullS);
field->item_name.set(buff);
mem_root_deque<Item *> field_list(thd->mem_root);
field_list.push_back(field);
if (thd->send_result_metadata(field_list,
Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF)) {
error = 1;
goto err;
}
sql_text.length(0);
if (lex->sql_command == SQLCOM_SHOW_CREATE_USER ||
lex->sql_command == SQLCOM_CREATE_USER) {
/*
Recreate LEX for default roles given an ACL_USER. This will later be used
by rewrite_default_roles() called by Rewriter_show_create_user::rewrite()
*/
get_default_roles(create_authid_from(acl_user), default_roles);
if (default_roles.size() > 0) {
LEX_STRING *tmp_user = nullptr;
LEX_STRING *tmp_host = nullptr;
/*
Make sure we reallocate the default_roles list when using it outside of
parser code so it has the same mem root as its items.
*/
lex->default_roles = new (thd->mem_root) List<LEX_USER>;
for (auto &&role : default_roles) {
if (!(tmp_user = make_lex_string_root(thd->mem_root, role.first.str,
role.first.length)) ||
!(tmp_host = make_lex_string_root(thd->mem_root, role.second.str,
role.second.length))) {
error = 1;
goto err;
}
LEX_USER *lex_role = LEX_USER::alloc(thd, tmp_user, tmp_host);
if (lex_role == nullptr) {
error = 1;
goto err;
}
lex->default_roles->push_back(lex_role);
}
}
}
lex->users_list.push_back(user_name);
{
/* Read and extract JSON comments */
String metadata_str;
if (read_user_application_user_metadata_from_table(
user_name->user, user_name->host, &metadata_str, table_list.table,
thd->variables.sql_mode & MODE_NO_BACKSLASH_ESCAPES)) {
error = 1;
goto err;
}
Show_user_params show_user_params(
hide_password_hash, thd->variables.print_identified_with_as_hex,
&metadata_str);
/*
By disabling instrumentation, we're requesting a rewrite to our
local buffer, sql_text. The value on the THD and those seen in
instrumentation remain unchanged.
*/
mysql_rewrite_acl_query(thd, sql_text, Consumer_type::STDOUT,
&show_user_params, false);
}
/* send the result row to client */
protocol->start_row();
protocol->store_string(sql_text.ptr(), sql_text.length(), sql_text.charset());
if (protocol->end_row()) {
error = 1;
goto err;
}
err:
close_thread_tables(thd);
lex->default_roles = old_default_roles;
/* restore user resources, ssl and password expire attributes */
lex->mqh = tmp_user_resource;
lex->ssl_type = ssl_type;
lex->ssl_cipher = ssl_cipher;
lex->x509_issuer = x509_issuer;
lex->x509_subject = x509_subject;
lex->alter_password = alter_info;
if (!thd->get_stmt_da()->is_error()) my_eof(thd);
return error;
}
#include "sql/query_result.h" // Time_zone
#include "sql/tztime.h"
/**
Perform credentials history check and update the password history table
Note that the data for the checks are extracted from LEX_USER. So these
need to be up to date in all cases.
How credential history checks are performed:
~~~
count= 0;
FOR SELECT * FROM mysql.password_history ORDER BY USER,HOST,TS DESC
WHERE USER=::current_user AND HOST=::current_host
{
if (count >= ::password_history && (NOW() - ts) > ::password_reuse_time)
{
delete row;
continue;
}
if (CRED was produced by ::password)
signal("wrong password");
count = count + 1;
}
INSERT INTO mysql.password_history (USER,HOST,TS,CRED)
VALUES (::current_user, ::current_host, NOW(), ::hashed_password);
~~~
@param thd The current thread
@param user The user account user to operate on
@param host The user account host to operate on
@param password_history The effective password history value
@param password_reuse_interval The effective password reuse interval value
@param auth Auth plugin to use for verification
@param cleartext The clear text password supplied
@param cleartext_length length of cleartext password
@param cred_hash hash of the credential to be inserted into the history
@param cred_hash_length Length of cred_hash
@param history_table The opened history table
@param what_to_set The mask of what to set
@retval false Password is OK
@retval true Password is not OK
*/
static bool auth_verify_password_history(
THD *thd, LEX_CSTRING *user, LEX_CSTRING *host, uint32 password_history,
long password_reuse_interval, st_mysql_auth *auth, const char *cleartext,
unsigned int cleartext_length, const char *cred_hash,
unsigned int cred_hash_length, Table_ref *history_table,
ulong what_to_set) {
TABLE *table = history_table->table;
uchar user_key[MAX_KEY_LENGTH];
uint key_prefix_length;
int error;
Field *user_field, *host_field, *ts_field, *cred_field;
bool result = false;
Acl_table_intact intact(thd);
if (!table) {
if ((password_history || password_reuse_interval) && cred_hash_length) {
/* fail if there's no history table and we need to update it */
my_error(ER_NO_SUCH_TABLE, MYF(0), "mysql", "password_history");
return true;
}
/* threat missing table as absent and empty otherwise */
return false;
}
/* all good: we don't handle empty passwords in history */
if (!cleartext_length && !cred_hash_length) return false;
/* invalid table causes verification to fail */
if (intact.check(history_table->table, ACL_TABLES::TABLE_PASSWORD_HISTORY))
return true;
user_field = table->field[MYSQL_PASSWORD_HISTORY_FIELD_USER];
host_field = table->field[MYSQL_PASSWORD_HISTORY_FIELD_HOST];
ts_field = table->field[MYSQL_PASSWORD_HISTORY_FIELD_PASSWORD_TIMESTAMP];
cred_field = table->field[MYSQL_PASSWORD_HISTORY_FIELD_PASSWORD];
table->use_all_columns();
/* create the search key on user and host */
user_field->store(user->str, user->length, system_charset_info);
host_field->store(host->str, host->length, system_charset_info);
key_prefix_length = (table->key_info->key_part[0].store_length +
table->key_info->key_part[1].store_length);
key_copy(user_key, table->record[0], table->key_info, key_prefix_length);
uint32 count = 0;
int rc = table->file->ha_index_init(0, true);
if (rc) {
table->file->print_error(rc, MYF(0));
result = true;
goto end;
}
/* find the first matching record by the first 2 fields of a key */
error = table->file->ha_index_read_map(table->record[0], user_key,
(key_part_map)((1L << 0) | (1L << 1)),
HA_READ_KEY_EXACT);
/* fetch the current day */
MYSQL_TIME tm_now;
long now_day;
thd->time_zone()->gmt_sec_to_TIME(&tm_now, thd->query_start_timeval_trunc(6));
now_day = calc_daynr(tm_now.year, tm_now.month, tm_now.day);
/* iterate over the password history rows for the user */
while (!error) {
MYSQL_TIME ts_val;
char outbuf[MAX_FIELD_WIDTH] = {0};
long ts_day, date_diff;
String cred_val(&outbuf[0], sizeof(outbuf), &my_charset_bin);
int is_error = 0;
/* fetch the recorded time */
if (ts_field->get_date(&ts_val, 0)) goto get_next_row;
/* convert to a day number */
ts_day = calc_daynr(ts_val.year, ts_val.month, ts_val.day);
/* get the difference in days */
date_diff = now_day - ts_day;
count++;
/*
We check everything that's in any range, including the last row(s)
*/
if (count <= password_history || date_diff < password_reuse_interval) {
/* fetch the cred field */
cred_field->val_str(&cred_val);
/*
Check if the password matches the stored hash.
There can't possibly be a match when we're altering the plugin
used. So we check for that and just delete the rows in this case.
But we still check the validity of the hash in case someone has
tampered with the history table manually.
*/
if (cleartext_length && cleartext &&
0 == (what_to_set & DIFFERENT_PLUGIN_ATTR) &&
(auth->authentication_flags & AUTH_FLAG_USES_INTERNAL_STORAGE) &&
auth->validate_authentication_string &&
!auth->validate_authentication_string(cred_val.c_ptr_safe(),
(unsigned)cred_val.length()) &&
auth->compare_password_with_hash &&
!auth->compare_password_with_hash(
cred_val.c_ptr_safe(), (unsigned long)cred_val.length(),
cleartext, (unsigned long)cleartext_length, &is_error) &&
!is_error) {
my_error(ER_CREDENTIALS_CONTRADICT_TO_HISTORY, MYF(0), user->length,
user->str, host->length, host->str);
/* password found in history */
result = true;
goto end;
}
}
/*
Delete all rows outside all check ranges, including the last row in
history range count, since we're to add another one.
*/
if ((count >= password_history &&
(!password_reuse_interval || date_diff > password_reuse_interval)) ||
0L != (what_to_set & DIFFERENT_PLUGIN_ATTR)) {
int ignore_error;
/* delete and go on, even if there's an error deleting */
if (0 != (ignore_error = table->file->ha_delete_row(table->record[0])))
table->file->print_error(ignore_error, MYF(0));
goto get_next_row;
}
get_next_row:
error = table->file->ha_index_next_same(table->record[0], user_key,
key_prefix_length);
}
/* something went wrong reading */
if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE) {
table->file->print_error(error, MYF(0));
result = true;
goto end;
}
/* Update the history if a hash is supplied and the plugin supports it */
if ((password_history || password_reuse_interval) && cred_hash_length &&
(auth->authentication_flags & AUTH_FLAG_USES_INTERNAL_STORAGE)) {
/* add history if needed */
restore_record(table, s->default_values);
table->field[MYSQL_PASSWORD_HISTORY_FIELD_USER]->store(
user->str, user->length, system_charset_info);
table->field[MYSQL_PASSWORD_HISTORY_FIELD_HOST]->store(
host->str, host->length, system_charset_info);
table->field[MYSQL_PASSWORD_HISTORY_FIELD_PASSWORD_TIMESTAMP]->store_time(
&tm_now);
table->field[MYSQL_PASSWORD_HISTORY_FIELD_PASSWORD]->store(
cred_hash, cred_hash_length, &my_charset_utf8mb3_bin);
table->field[MYSQL_PASSWORD_HISTORY_FIELD_PASSWORD]->set_notnull();
if (0 != (error = table->file->ha_write_row(table->record[0]))) {
table->file->print_error(error, MYF(0));
result = true;
}
}
end:
if (table->file->inited != handler::NONE) {
int rc_end = table->file->ha_index_end();
if (rc_end) {
/* purecov: begin inspected */
table->file->print_error(rc_end, MYF(ME_ERRORLOG));
assert(false);
/* purecov: end */
}
}
return result;
}
/**
Updates the password history table for cases of deleting or renaming users
This function, unlike the other "update" functions does not handle the
addition of new data. That's done by auth_verify_password_history().
The function only handles renames and deletes of user accounts.
It does not go via the normal non-mysql.user handle_grant_data() route
since there is a (partial) key on user/host and hence no need to do a
full table scan.
@param thd The execution context
@param tables The list of opened ACL tables
@param drop True if it's a drop operation
@param user_from The user to rename from or the user to drop
@param user_to The user to rename to or the user to add
@param[out] row_existed Set to true if row matching user_from existed
@retval true operation failed
@retval false success
*/
static bool handle_password_history_table(THD *thd, Table_ref *tables,
bool drop, LEX_USER *user_from,
LEX_USER *user_to,
bool *row_existed) {
bool result = false;
TABLE *table = tables[ACL_TABLES::TABLE_PASSWORD_HISTORY].table;
uchar user_key[MAX_KEY_LENGTH];
uint key_prefix_length;
int error;
Field *user_field, *host_field;
Acl_table_intact table_intact(thd);
*row_existed = false;
if (!table) {
/* table not preset is considered empty if not adding to it */
return false;
}
if (table_intact.check(table, ACL_TABLES::TABLE_PASSWORD_HISTORY)) {
result = true;
goto end;
}
user_field = table->field[MYSQL_PASSWORD_HISTORY_FIELD_USER];
host_field = table->field[MYSQL_PASSWORD_HISTORY_FIELD_HOST];
table->use_all_columns();
/* create the search key on user and host */
user_field->store(user_from->user.str, user_from->user.length,
system_charset_info);
host_field->store(user_from->host.str, user_from->host.length,
system_charset_info);
key_prefix_length = (table->key_info->key_part[0].store_length +
table->key_info->key_part[1].store_length);
key_copy(user_key, table->record[0], table->key_info, key_prefix_length);
int rc;
rc = table->file->ha_index_init(0, true);
if (rc) {
table->file->print_error(rc, MYF(0));
result = true;
goto end;
}
/* find the first matching record by host/user key prefix */
error = table->file->ha_index_read_map(table->record[0], user_key,
(key_part_map)((1L << 0) | (1L << 1)),
HA_READ_KEY_EXACT);
/* iterate over the password history rows for the user */
while (!error) {
/* found at least 1 row */
if (!*row_existed) {
*row_existed = true;
/* no need to look for more rows if not updating */
if (!drop && !user_to) {
/* mark the cursor as being at end */
error = HA_ERR_KEY_NOT_FOUND;
break;
}
}
if (drop) {
/* if we're dropping, delete the row */
if (0 != (error = table->file->ha_delete_row(table->record[0]))) break;
} else if (user_to) {
/* we're renaming, set the new user/host values */
store_record(table, record[1]);
table->field[MYSQL_PASSWORD_HISTORY_FIELD_USER]->store(
user_to->user.str, user_to->user.length, system_charset_info);
table->field[MYSQL_PASSWORD_HISTORY_FIELD_HOST]->store(
user_to->host.str, user_to->host.length, system_charset_info);
error = table->file->ha_update_row(table->record[1], table->record[0]);
if (error) break;
}
error = table->file->ha_index_next_same(table->record[0], user_key,
key_prefix_length);
}
/* something went wrong reading */
if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE) {
table->file->print_error(error, MYF(0));
result = true;
}
end:
if (table->file->inited != handler::NONE) {
int rc_end = table->file->ha_index_end();
if (rc_end) {
/* purecov: begin inspected */
table->file->print_error(rc_end, MYF(ME_ERRORLOG));
assert(false);
/* purecov: end */
}
}
return result;
}
/**
Checks, if the REPLACE clause is required, optional or not required.
It throws error:
If REPLACE clause is required but not specified.
If REPLACE clause is not required but specified.
If current password specified in the REPLACE clause does not match with
authentication string of the user.
The plaintext current password is erased from LEX_USER, iff its length > 0 .
@param thd The execution context
@param Str LEX user
@param acl_user The associated user which carries the ACL
@param auth Auth plugin to use for verification
@param new_password New password buffer
@param new_password_length Length of new password
@param is_privileged_user Whether caller has CREATE_USER_ACL
or UPDATE_ACL over mysql.*
@param user_exists Whether user already exists
@retval true operation failed
@retval false success
*/
static bool validate_password_require_current(
THD *thd, LEX_USER *Str, ACL_USER *acl_user, st_mysql_auth *auth,
const char *new_password, unsigned int new_password_length,
bool is_privileged_user, bool user_exists) {
if (user_exists) {
auto password_cleanup = create_scope_guard([&] {
my_cleanse(const_cast<char *>(Str->current_auth.str),
Str->current_auth.length);
my_cleanse(const_cast<char *>(new_password), new_password_length);
});
if (Str->uses_replace_clause) {
int is_error = 0;
Security_context *sctx = thd->security_context();
assert(sctx);
// If trying to set password for other user
if (strcmp(sctx->user().str, Str->user.str) ||
my_strcasecmp(system_charset_info, sctx->priv_host().str,
Str->host.str)) {
my_error(ER_CURRENT_PASSWORD_NOT_REQUIRED, MYF(0));
return (true);
}
/*
Handle the validation of empty current password first as some of
authentication plugins do not like to check the empty passwords.
*/
if (acl_user->credentials[PRIMARY_CRED].m_auth_string.length == 0) {
if (Str->current_auth.length > 0) {
my_error(ER_INCORRECT_CURRENT_PASSWORD, MYF(0));
return (true);
}
return (false);
}
/*
Compare the specified plain text current password with the
current auth string.
*/
if ((auth->authentication_flags & AUTH_FLAG_USES_INTERNAL_STORAGE) &&
auth->compare_password_with_hash &&
auth->compare_password_with_hash(
acl_user->credentials[PRIMARY_CRED].m_auth_string.str,
(unsigned long)acl_user->credentials[PRIMARY_CRED]
.m_auth_string.length,
Str->current_auth.str, (unsigned long)Str->current_auth.length,
&is_error) &&
!is_error) {
my_error(ER_INCORRECT_CURRENT_PASSWORD, MYF(0));
return (true);
}
{
/* Validate password policy requirements if any */
my_service<SERVICE_TYPE(validate_password_changed_characters)> service(
"validate_password_changed_characters", srv_registry);
if (service.is_valid()) {
unsigned int minimum_required = 0, changed = 0;
String current_str(Str->current_auth.str, Str->current_auth.length,
&my_charset_utf8mb3_bin);
String new_str(new_password, new_password_length,
&my_charset_utf8mb3_bin);
if (service->validate(reinterpret_cast<my_h_string>(¤t_str),
reinterpret_cast<my_h_string>(&new_str),
&minimum_required, &changed)) {
my_error(ER_VALIDATE_PASSWORD_INSUFFICIENT_CHANGED_CHARACTERS,
MYF(0), minimum_required, changed);
return (true);
}
}
}
} else if (!is_privileged_user) {
/*
If the field value is set or field value is NULL and global sys
variable flag is ON then REPLACE clause must be specified.
*/
if ((acl_user->password_require_current == Lex_acl_attrib_udyn::YES) ||
(acl_user->password_require_current == Lex_acl_attrib_udyn::DEFAULT &&
password_require_current)) {
my_error(ER_MISSING_CURRENT_PASSWORD, MYF(0));
return (true);
}
}
}
return false;
}
char translate_byte_to_password_char(unsigned char c) {
static const std::string translation = std::string(
"1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXY"
"Z,.-;:_+*!%&/(){}[]<>@");
int index = round(((float)c * ((float)(translation.length() - 1) / 255.0)));
return translation[index];
}
/**
Generates a random password of the length decided by the system variable
generated_random_password_length.
@param[out] password The generated password.
@param length The length of the generated password.
*/
void generate_random_password(std::string *password, uint32_t length) {
unsigned char buffer[256];
if (length > 255) length = 255;
RAND_bytes((unsigned char *)&buffer[0], length);
password->reserve(length + 1);
for (uint32_t i = 0; i < length; ++i) {
password->append(1, translate_byte_to_password_char(buffer[i]));
}
}
/**
Sends the result set of generated passwords to the client.
@param thd The thread handler
@param generated_passwords A list of 3-tuple strings containing user, host
and plaintext password.
@return success state
@retval true An error occurred (DA is set)
@retval false Success (my_eof)
*/
bool send_password_result_set(
THD *thd, const Userhostpassword_list &generated_passwords) {
mem_root_deque<Item *> meta_data(thd->mem_root);
meta_data.push_back(new Item_string("user", 4, system_charset_info));
meta_data.push_back(new Item_string("host", 4, system_charset_info));
meta_data.push_back(
new Item_string("generated password", 18, system_charset_info));
meta_data.push_back(new Item_uint(NAME_STRING("auth_factor"), 1, 12));
mem_root_deque<Item *> item_list(thd->mem_root);
Query_result_send output;
if (output.send_result_set_metadata(
thd, meta_data, Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF))
return true;
for (auto password : generated_passwords) {
Item *item = new Item_string(password.user.c_str(), password.user.length(),
system_charset_info);
item_list.push_back(item);
item = new Item_string(password.host.c_str(), password.host.length(),
system_charset_info);
item_list.push_back(item);
item = new Item_string(password.password.c_str(),
password.password.length(), system_charset_info);
item_list.push_back(item);
item = new Item_uint(password.authentication_factor);
item_list.push_back(item);
if (output.send_data(thd, item_list)) {
return true;