-
Notifications
You must be signed in to change notification settings - Fork 889
Expand file tree
/
Copy pathsql_auth_cache.cc
More file actions
4069 lines (3534 loc) · 137 KB
/
sql_auth_cache.cc
File metadata and controls
4069 lines (3534 loc) · 137 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 "sql/auth/sql_auth_cache.h"
#include <stdarg.h>
#include <boost/graph/properties.hpp>
#include <new>
#include "m_ctype.h"
#include "m_string.h" // LEX_CSTRING
#include "mutex_lock.h"
#include "my_base.h"
#include "my_compiler.h"
#include "my_dbug.h"
#include "my_loglevel.h"
#include "my_macros.h"
#include "mysql/components/services/bits/psi_bits.h"
#include "mysql/components/services/bits/psi_mutex_bits.h"
#include "mysql/components/services/log_builtins.h"
#include "mysql/plugin.h"
#include "mysql/plugin_audit.h"
#include "mysql/plugin_auth.h" // st_mysql_auth
#include "mysql/psi/mysql_mutex.h"
#include "mysql/service_mysql_alloc.h"
#include "mysqld_error.h"
#include "prealloced_array.h"
#include "sql/auth/auth_acls.h"
#include "sql/auth/auth_common.h" // ACL_internal_schema_access
#include "sql/auth/auth_internal.h" // auth_plugin_is_built_in
#include "sql/auth/auth_utility.h"
#include "sql/auth/dynamic_privilege_table.h"
#include "sql/auth/sql_authentication.h" // g_cached_authentication_plugins
#include "sql/auth/sql_security_ctx.h"
#include "sql/auth/sql_user_table.h"
#include "sql/auth/user_table.h" // read_user_table
#include "sql/current_thd.h" // current_thd
#include "sql/debug_sync.h"
#include "sql/error_handler.h" // Internal_error_handler
#include "sql/field.h" // Field
#include "sql/handler.h"
#include "sql/iterators/row_iterator.h"
#include "sql/key.h"
#include "sql/mdl.h"
#include "sql/mysqld.h" // my_localhost
#include "sql/psi_memory_key.h" // key_memory_acl_mem
#include "sql/set_var.h"
#include "sql/sql_audit.h"
#include "sql/sql_base.h" // open_and_lock_tables
#include "sql/sql_class.h" // THD
#include "sql/sql_const.h"
#include "sql/sql_error.h"
#include "sql/sql_executor.h" // unique_ptr_destroy_only<RowIterator>
#include "sql/sql_lex.h"
#include "sql/sql_plugin.h" // my_plugin_lock_by_name
#include "sql/sql_plugin_ref.h"
#include "sql/ssl_acceptor_context_operator.h"
#include "sql/system_variables.h"
#include "sql/table.h" // TABLE
#include "sql/thd_raii.h"
#include "sql/thr_malloc.h"
#include "sql/tztime.h" // Time_zone
#include "sql/xa.h"
#include "sql_string.h"
#include "thr_lock.h"
#include "thr_mutex.h"
#define INVALID_DATE "0000-00-00 00:00:00"
#include <algorithm>
#include <functional>
#include <unordered_map>
#include <utility>
#include <vector>
using std::make_unique;
using std::min;
using std::string;
using std::unique_ptr;
PSI_mutex_key key_LOCK_acl_cache_flush;
PSI_mutex_info all_acl_cache_mutexes[] = {
{&key_LOCK_acl_cache_flush, "LOCK_acl_cache_flush", PSI_FLAG_SINGLETON, 0,
PSI_DOCUMENT_ME}};
Acl_cache *g_acl_cache = nullptr;
Acl_cache *get_global_acl_cache() { return g_acl_cache; }
ulong get_global_acl_cache_size() { return g_acl_cache->size(); }
void init_acl_cache();
extern Role_index_map *g_authid_to_vertex;
extern Granted_roles_graph *g_granted_roles;
#include <boost/property_map/property_map.hpp>
struct ACL_internal_schema_registry_entry {
const LEX_CSTRING *m_name;
const ACL_internal_schema_access *m_access;
};
/**
Internal schema registered.
Currently, this is only:
- performance_schema
- information_schema,
This can be reused later for:
- mysql
*/
static ACL_internal_schema_registry_entry registry_array[2];
static uint m_registry_array_size = 0;
MEM_ROOT global_acl_memory;
MEM_ROOT memex;
Prealloced_array<ACL_USER, ACL_PREALLOC_SIZE> *acl_users = nullptr;
Prealloced_array<ACL_PROXY_USER, ACL_PREALLOC_SIZE> *acl_proxy_users = nullptr;
Prealloced_array<ACL_DB, ACL_PREALLOC_SIZE> *acl_dbs = nullptr;
Prealloced_array<ACL_HOST_AND_IP, ACL_PREALLOC_SIZE> *acl_wild_hosts = nullptr;
Db_access_map acl_db_map;
Default_roles *g_default_roles = nullptr;
std::vector<Role_id> *g_mandatory_roles = nullptr;
unique_ptr<
malloc_unordered_multimap<string, unique_ptr_destroy_only<GRANT_TABLE>>>
column_priv_hash;
unique_ptr<
malloc_unordered_multimap<string, unique_ptr_destroy_only<GRANT_NAME>>>
proc_priv_hash, func_priv_hash;
malloc_unordered_map<std::string, unique_ptr_my_free<acl_entry>> db_cache{
key_memory_acl_cache};
collation_unordered_map<std::string, ACL_USER *> *acl_check_hosts = nullptr;
unique_ptr<Acl_restrictions> acl_restrictions = nullptr;
/**
A hashmap on user part of account name for quick lookup.
*/
typedef std::unordered_map<
std::string, Acl_user_ptr_list, std::hash<std::string>,
std::equal_to<std::string>,
Acl_cache_allocator<std::pair<const std::string, Acl_user_ptr_list>>>
Name_to_userlist;
Name_to_userlist *name_to_userlist = nullptr;
bool initialized = false;
bool skip_grant_tables(void) { return !initialized; }
bool acl_cache_initialized = false;
bool allow_all_hosts = true;
uint grant_version = 0; /* Version of priv tables */
bool validate_user_plugins = true;
#define IP_ADDR_STRLEN (3 + 1 + 3 + 1 + 3 + 1 + 3)
#define ACL_KEY_LENGTH (IP_ADDR_STRLEN + 1 + NAME_LEN + 1 + USERNAME_LENGTH + 1)
/** Helper: Set user name */
static void set_username(char **user, const char *user_arg, MEM_ROOT *mem) {
assert(user != nullptr);
*user = (user_arg && *user_arg) ? strdup_root(mem, user_arg) : nullptr;
}
/** Helper: Set host name */
static void set_hostname(ACL_HOST_AND_IP *host, const char *host_arg,
MEM_ROOT *mem) {
assert(host != nullptr);
host->update_hostname((host_arg && *host_arg) ? strdup_root(mem, host_arg)
: nullptr);
}
/**
Allocates the memory in the the global_acl_memory MEM_ROOT.
*/
void init_acl_memory() {
init_sql_alloc(key_memory_acl_mem, &global_acl_memory, ACL_ALLOC_BLOCK_SIZE);
}
/**
Add an internal schema to the registry.
@param name the schema name
@param access the schema ACL specific rules
*/
void ACL_internal_schema_registry::register_schema(
const LEX_CSTRING &name, const ACL_internal_schema_access *access) {
assert(m_registry_array_size < array_elements(registry_array));
/* Not thread safe, and does not need to be. */
registry_array[m_registry_array_size].m_name = &name;
registry_array[m_registry_array_size].m_access = access;
m_registry_array_size++;
}
/**
Search per internal schema ACL by name.
@param name a schema name
@return per schema rules, or NULL
*/
const ACL_internal_schema_access *ACL_internal_schema_registry::lookup(
const char *name) {
assert(name != nullptr);
uint i;
for (i = 0; i < m_registry_array_size; i++) {
if (my_strcasecmp(system_charset_info, registry_array[i].m_name->str,
name) == 0)
return registry_array[i].m_access;
}
return nullptr;
}
bool ACL_HOST_AND_IP::calc_cidr_mask(const char *ip_arg, long *val) {
long tmp;
if (!(ip_arg = str2int(ip_arg, 10, 0, 32, &tmp)) || *ip_arg != '\0')
return true;
/* Create IP mask. */
*val = UINT_MAX32 << (32 - tmp);
return false;
}
bool ACL_HOST_AND_IP::calc_ip_mask(const char *ip_arg, long *val) {
long tmp = 0;
if (!(ip_arg = calc_ip(ip_arg, &tmp)) || *ip_arg != '\0') return true;
/* Valid IP mask must be continuous bit flags. */
if (((~tmp & UINT_MAX32) + 1) & ~tmp) return true;
*val = tmp;
return false;
}
const char *ACL_HOST_AND_IP::calc_ip(const char *ip_arg, long *val) {
long ip_val, tmp;
if (!(ip_arg = str2int(ip_arg, 10, 0, 255, &ip_val)) || *ip_arg != '.')
return nullptr;
ip_val <<= 24;
if (!(ip_arg = str2int(ip_arg + 1, 10, 0, 255, &tmp)) || *ip_arg != '.')
return nullptr;
ip_val += tmp << 16;
if (!(ip_arg = str2int(ip_arg + 1, 10, 0, 255, &tmp)) || *ip_arg != '.')
return nullptr;
ip_val += tmp << 8;
if (!(ip_arg = str2int(ip_arg + 1, 10, 0, 255, &tmp))) return nullptr;
*val = ip_val + tmp;
return ip_arg;
}
/**
@brief Update the hostname. Updates ip and ip_mask accordingly.
@param host_arg Value to be stored
*/
void ACL_HOST_AND_IP::update_hostname(const char *host_arg) {
hostname = host_arg; // This will not be modified!
ip = ip_mask = 0;
if (!host_arg) {
hostname_length = 0;
return;
}
hostname_length = strlen(hostname);
if ((host_arg = calc_ip(host_arg, &ip))) {
if (*host_arg == '\0') {
/* There is only IP part specified. */
ip_mask_type = ip_mask_type_implicit;
ip_mask = UINT_MAX32;
} else if (*host_arg == '/') {
if (!calc_ip_mask(host_arg + 1, &ip_mask)) {
ip_mask_type = ip_mask_type_subnet;
} else if (!calc_cidr_mask(host_arg + 1, &ip_mask)) {
ip_mask_type = ip_mask_type_cidr;
} else
/* Invalid or unsupported IP mask.*/
ip = 0;
}
}
}
/*
@brief Comparing of hostnames.
@TODO This function should ideally only
be called during authentication and not from authorization code. You may
authenticate with a hostmask, but all authentication should be against a
specific security context with a specific authentication ID.
@param host_arg Hostname to be compared with
@param ip_arg IP address to be compared with
@notes
A hostname may be of type:
1) hostname (May include wildcards); monty.pp.sci.fi
2) ip (May include wildcards); 192.168.0.0
3) ip/netmask 192.168.0.0/255.255.255.0
A net mask of 0.0.0.0 is not allowed.
@return
true if matched
false if not matched
*/
bool ACL_HOST_AND_IP::compare_hostname(const char *host_arg,
const char *ip_arg) {
long tmp;
const char *p;
if (ip_mask && ip_arg && (p = calc_ip(ip_arg, &tmp)) && *p == '\0') {
return (tmp & ip_mask) == ip;
}
return (!hostname ||
(host_arg &&
!wild_case_compare(system_charset_info, host_arg, hostname)) ||
(ip_arg && !wild_compare(ip_arg, strlen(ip_arg), hostname,
strlen(hostname), false)));
}
ACL_USER::ACL_USER() {
/* ACL_ACCESS is initialized by its constructor */
{
/* USER_RESOURCES */
user_resource.questions = 0;
user_resource.updates = 0;
user_resource.conn_per_hour = 0;
user_resource.user_conn = 0;
user_resource.specified_limits = 0;
}
user = nullptr;
{
/* TLS restrictions */
ssl_type = SSL_TYPE_NONE;
ssl_cipher = nullptr;
x509_issuer = nullptr;
x509_subject = nullptr;
}
plugin = EMPTY_CSTR;
password_expired = false;
can_authenticate = false;
password_last_changed.time_type = MYSQL_TIMESTAMP_ERROR;
password_lifetime = 0;
use_default_password_lifetime = false;
account_locked = false;
is_role = false;
password_history_length = 0;
use_default_password_history = false;
password_reuse_interval = 0;
use_default_password_reuse_interval = false;
password_require_current = Lex_acl_attrib_udyn::DEFAULT;
m_mfa = nullptr;
/* Acl_credentials is initialized by its constructor */
}
void ACL_USER::Password_locked_state::set_temporary_lock_state_parameters(
uint remaining_login_attempts, long daynr_locked) {
m_remaining_login_attempts = remaining_login_attempts;
m_daynr_locked = daynr_locked;
}
void ACL_USER::Password_locked_state::set_parameters(
int password_lock_time_days, uint failed_login_attempts) {
m_password_lock_time_days = password_lock_time_days;
m_failed_login_attempts = failed_login_attempts;
set_temporary_lock_state_parameters(failed_login_attempts, 0);
assert(is_default() == true);
}
/**
Updates the password locked state based on the time of day fetched from the
THD
@param thd the session to use to calculate time
@param successful_login true if the login succeeded
@param[out] ret_days_remaining remaining number of days. Filled only if
update returns locked account
@retval false account not locked
@retval true account locked
*/
bool ACL_USER::Password_locked_state::update(THD *thd, bool successful_login,
long *ret_days_remaining) {
/* stop if the user is not tracking failed logins */
if (!is_active()) return false;
/* reset on a successful login if the account is not locked */
if (successful_login && m_daynr_locked == 0) {
m_remaining_login_attempts = m_failed_login_attempts;
return false;
}
/* decreases the remaining login attempts if any */
if (!successful_login && m_remaining_login_attempts > 0) {
m_remaining_login_attempts--;
assert(m_daynr_locked == 0);
}
if (m_remaining_login_attempts) return false;
long now_day;
/* fetch the current day */
MYSQL_TIME tm_now;
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);
DBUG_EXECUTE_IF("account_lock_daynr_add_one", { now_day += 1; });
DBUG_EXECUTE_IF("account_lock_daynr_add_ten", { now_day += 10; });
/* last unsuccessful login. lock the account */
if (m_daynr_locked == 0) {
assert(!successful_login);
m_daynr_locked = now_day;
*ret_days_remaining = m_password_lock_time_days;
return true;
};
/* if the lock should never expire we stop here */
if (m_daynr_locked > 0 && m_password_lock_time_days < 0) return true;
/* check if the account is still to be locked */
if (now_day - m_daynr_locked < (long)m_password_lock_time_days) {
*ret_days_remaining =
((long)m_password_lock_time_days) - (now_day - m_daynr_locked);
return true;
}
/* reset the account lock if the time has expired */
if (now_day - m_daynr_locked >= (long)m_password_lock_time_days) {
m_daynr_locked = 0;
m_remaining_login_attempts = m_failed_login_attempts;
return false;
}
/* it should never get to here */
assert(false);
return false;
}
ACL_USER *ACL_USER::copy(MEM_ROOT *root) {
ACL_USER *dst = (ACL_USER *)root->Alloc(sizeof(ACL_USER));
if (!dst) return nullptr;
*dst = *this;
dst->user = safe_strdup_root(root, user);
dst->ssl_cipher = safe_strdup_root(root, ssl_cipher);
dst->x509_issuer = safe_strdup_root(root, x509_issuer);
dst->x509_subject = safe_strdup_root(root, x509_subject);
/*
If the plugin is built in we don't need to reallocate the name of the
plugin.
*/
if (auth_plugin_is_built_in(dst->plugin.str))
dst->plugin = plugin;
else {
dst->plugin.str = strmake_root(root, plugin.str, plugin.length);
dst->plugin.length = plugin.length;
}
for (int i = 0; i < NUM_CREDENTIALS; ++i) {
dst->credentials[i].m_auth_string.str =
safe_strdup_root(root, credentials[i].m_auth_string.str);
dst->credentials[i].m_auth_string.length =
credentials[i].m_auth_string.length;
dst->credentials[i].m_salt_len = credentials[i].m_salt_len;
memcpy(dst->credentials[i].m_salt, credentials[i].m_salt,
credentials[i].m_salt_len);
}
dst->host.update_hostname(safe_strdup_root(root, host.get_host()));
dst->password_require_current = password_require_current;
dst->password_locked_state = password_locked_state;
dst->set_mfa(root, m_mfa);
return dst;
}
void ACL_USER::set_user(MEM_ROOT *mem, const char *user_arg) {
set_username(&user, user_arg, mem);
}
void ACL_USER::set_host(MEM_ROOT *mem, const char *host_arg) {
set_hostname(&host, host_arg, mem);
}
void ACL_USER::set_mfa(MEM_ROOT *mem, I_multi_factor_auth *m) {
if (mem && m) {
m_mfa = new (mem) Multi_factor_auth_list(mem);
Multi_factor_auth_list *auth_list = m->get_multi_factor_auth_list();
/*
iterate over list of auth factors and make a new copy of each
individual auth factors
*/
for (auto m_it : auth_list->get_mfa_list()) {
Multi_factor_auth_info *af = m_it->get_multi_factor_auth_info();
m_mfa->add_factor(new (mem)
Multi_factor_auth_info(mem, af->get_lex_mfa()));
}
} else {
m_mfa = m;
}
}
void ACL_PROXY_USER::init(const char *host_arg, const char *user_arg,
const char *proxied_host_arg,
const char *proxied_user_arg, bool with_grant_arg) {
user = (user_arg && *user_arg) ? user_arg : nullptr;
host.update_hostname((host_arg && *host_arg) ? host_arg : nullptr);
proxied_user =
(proxied_user_arg && *proxied_user_arg) ? proxied_user_arg : nullptr;
proxied_host.update_hostname(
(proxied_host_arg && *proxied_host_arg) ? proxied_host_arg : nullptr);
with_grant = with_grant_arg;
sort =
get_sort(4, host.get_host(), user, proxied_host.get_host(), proxied_user);
}
void ACL_PROXY_USER::init(MEM_ROOT *mem, const char *host_arg,
const char *user_arg, const char *proxied_host_arg,
const char *proxied_user_arg, bool with_grant_arg) {
init((host_arg && *host_arg) ? strdup_root(mem, host_arg) : nullptr,
(user_arg && *user_arg) ? strdup_root(mem, user_arg) : nullptr,
(proxied_host_arg && *proxied_host_arg)
? strdup_root(mem, proxied_host_arg)
: nullptr,
(proxied_user_arg && *proxied_user_arg)
? strdup_root(mem, proxied_user_arg)
: nullptr,
with_grant_arg);
}
void ACL_PROXY_USER::init(TABLE *table, MEM_ROOT *mem) {
init(get_field(mem, table->field[MYSQL_PROXIES_PRIV_HOST]),
get_field(mem, table->field[MYSQL_PROXIES_PRIV_USER]),
get_field(mem, table->field[MYSQL_PROXIES_PRIV_PROXIED_HOST]),
get_field(mem, table->field[MYSQL_PROXIES_PRIV_PROXIED_USER]),
table->field[MYSQL_PROXIES_PRIV_WITH_GRANT]->val_int() != 0);
}
bool ACL_PROXY_USER::check_validity(bool check_no_resolve) {
if (check_no_resolve &&
(hostname_requires_resolving(host.get_host()) ||
hostname_requires_resolving(proxied_host.get_host())) &&
strcmp(host.get_host(), "localhost") != 0) {
LogErr(WARNING_LEVEL, ER_AUTHCACHE_PROXIES_PRIV_SKIPPED_NEEDS_RESOLVE,
proxied_user ? proxied_user : "",
proxied_host.get_host() ? proxied_host.get_host() : "",
user ? user : "", host.get_host() ? host.get_host() : "");
}
return false;
}
bool ACL_PROXY_USER::matches(const char *host_arg, const char *user_arg,
const char *ip_arg, const char *proxied_user_arg,
bool any_proxy_user) {
DBUG_TRACE;
DBUG_PRINT("info",
("compare_hostname(%s,%s,%s) &&"
"compare_hostname(%s,%s,%s) &&"
"wild_compare (%s,%s) &&"
"wild_compare (%s,%s)",
host.get_host() ? host.get_host() : "<NULL>",
host_arg ? host_arg : "<NULL>", ip_arg ? ip_arg : "<NULL>",
proxied_host.get_host() ? proxied_host.get_host() : "<NULL>",
host_arg ? host_arg : "<NULL>", ip_arg ? ip_arg : "<NULL>",
user_arg ? user_arg : "<NULL>", user ? user : "<NULL>",
proxied_user_arg ? proxied_user_arg : "<NULL>",
proxied_user ? proxied_user : "<NULL>"));
return host.compare_hostname(host_arg, ip_arg) &&
proxied_host.compare_hostname(host_arg, ip_arg) &&
(!user || (user_arg && !wild_compare(user_arg, strlen(user_arg), user,
strlen(user), true))) &&
(any_proxy_user || !proxied_user ||
(proxied_user &&
!wild_compare(proxied_user_arg, strlen(proxied_user_arg),
proxied_user, strlen(proxied_user), true)));
}
bool ACL_PROXY_USER::pk_equals(ACL_PROXY_USER *grant) {
DBUG_TRACE;
DBUG_PRINT("info",
("strcmp(%s,%s) &&"
"strcmp(%s,%s) &&"
"wild_compare (%s,%s) &&"
"wild_compare (%s,%s)",
user ? user : "<NULL>", grant->user ? grant->user : "<NULL>",
proxied_user ? proxied_user : "<NULL>",
grant->proxied_user ? grant->proxied_user : "<NULL>",
host.get_host() ? host.get_host() : "<NULL>",
grant->host.get_host() ? grant->host.get_host() : "<NULL>",
proxied_host.get_host() ? proxied_host.get_host() : "<NULL>",
grant->proxied_host.get_host() ? grant->proxied_host.get_host()
: "<NULL>"));
return auth_element_equals(user, grant->user) &&
auth_element_equals(proxied_user, grant->proxied_user) &&
auth_element_equals(host.get_host(), grant->host.get_host()) &&
auth_element_equals(proxied_host.get_host(),
grant->proxied_host.get_host());
}
void ACL_PROXY_USER::print_grant(THD *thd, String *str) {
str->append(STRING_WITH_LEN("GRANT PROXY ON "));
append_auth_id_string(thd, proxied_user, get_proxied_user_length(),
proxied_host.get_host(), proxied_host.get_host_len(),
str);
str->append(STRING_WITH_LEN(" TO "));
append_auth_id_string(thd, user, get_user_length(), host.get_host(),
host.get_host_len(), str);
if (with_grant) str->append(STRING_WITH_LEN(" WITH GRANT OPTION"));
}
int ACL_PROXY_USER::store_pk(TABLE *table, const LEX_CSTRING &hostname,
const LEX_CSTRING &user,
const LEX_CSTRING &proxied_host,
const LEX_CSTRING &proxied_user) {
DBUG_TRACE;
DBUG_PRINT("info", ("host=%s, user=%s, proxied_host=%s, proxied_user=%s",
hostname.str ? hostname.str : "<NULL>",
user.str ? user.str : "<NULL>",
proxied_host.str ? proxied_host.str : "<NULL>",
proxied_user.str ? proxied_user.str : "<NULL>"));
if (table->field[MYSQL_PROXIES_PRIV_HOST]->store(
hostname.str, hostname.length, system_charset_info))
return true;
if (table->field[MYSQL_PROXIES_PRIV_USER]->store(user.str, user.length,
system_charset_info))
return true;
if (table->field[MYSQL_PROXIES_PRIV_PROXIED_HOST]->store(
proxied_host.str, proxied_host.length, system_charset_info))
return true;
if (table->field[MYSQL_PROXIES_PRIV_PROXIED_USER]->store(
proxied_user.str, proxied_user.length, system_charset_info))
return true;
return false;
}
int ACL_PROXY_USER::store_with_grant(TABLE *table, bool with_grant) {
DBUG_TRACE;
DBUG_PRINT("info", ("with_grant=%s", with_grant ? "TRUE" : "FALSE"));
if (table->field[MYSQL_PROXIES_PRIV_WITH_GRANT]->store(with_grant ? 1 : 0,
true))
return true;
return false;
}
int ACL_PROXY_USER::store_data_record(TABLE *table, const LEX_CSTRING &hostname,
const LEX_CSTRING &user,
const LEX_CSTRING &proxied_host,
const LEX_CSTRING &proxied_user,
bool with_grant, const char *grantor) {
DBUG_TRACE;
if (store_pk(table, hostname, user, proxied_host, proxied_user)) return true;
if (store_with_grant(table, with_grant)) return true;
if (table->field[MYSQL_PROXIES_PRIV_GRANTOR]->store(grantor, strlen(grantor),
system_charset_info))
return true;
my_timeval tm = table->in_use->query_start_timeval_trunc(0);
table->field[MYSQL_PROXIES_PRIV_TIMESTAMP]->store_timestamp(&tm);
return false;
}
void ACL_PROXY_USER::set_user(MEM_ROOT *mem, const char *user_arg) {
set_username(const_cast<char **>(&user), user_arg, mem);
}
void ACL_PROXY_USER::set_host(MEM_ROOT *mem, const char *host_arg) {
set_hostname(&host, host_arg, mem);
}
void ACL_DB::set_user(MEM_ROOT *mem, const char *user_arg) {
set_username(&user, user_arg, mem);
}
void ACL_DB::set_host(MEM_ROOT *mem, const char *host_arg) {
set_hostname(&host, host_arg, mem);
}
/**
Append the authorization id for the user
@param [in] thd The THD to find the SQL mode
@param [in] acl_user ACL User to retrieve the user information
@param [in, out] str The string in which authID is suffixed
*/
void append_auth_id(const THD *thd, ACL_USER *acl_user, String *str) {
assert(thd);
append_auth_id_string(thd, acl_user->user, acl_user->get_username_length(),
acl_user->host.get_host(),
acl_user->host.get_host_len(), str);
}
/**
Append the user\@host to the str.
@param [in] thd The THD to find the SQL mode
@param [in] user Username to append to authID
@param [in] user_len Length of Username
@param [in] host hostname to append to authID
@param [in] host_len Length of hostname
@param [in, out] str The string in which authID is suffixed
*/
void append_auth_id_string(const THD *thd, const char *user, size_t user_len,
const char *host, size_t host_len, String *str) {
assert(thd);
append_identifier(thd, str, user, user_len);
str->append(STRING_WITH_LEN("@"));
append_identifier(thd, str, host, host_len);
}
/**
Performs wildcard matching, aka globbing, on the input string with
the given wildcard pattern, and the specified wildcard characters.
This method does case insensitive comparisons.
@param[in] cs character set of the input string and wildcard pattern
@param[in] str input which should be matched against pattern
@param[in] str_len length of the input string
@param[in] wildstr pattern with wildcards
@param[in] wildstr_len length of the wildcards pattern
@return 0 if input string match with the pattern
@return 1 otherwise
*/
int wild_case_compare(CHARSET_INFO *cs, const char *str, size_t str_len,
const char *wildstr, size_t wildstr_len) {
int flag;
DBUG_TRACE;
DBUG_PRINT("enter", ("str: '%s' wildstr: '%s'", str, wildstr));
const char *wildstr_end = wildstr + wildstr_len;
const char *str_end = str + str_len;
/*
Empty string matches only if there is only a wild_many(%) char
in the string to be matched with.
*/
if (str_len == 0) {
bool ret_value = true;
if (wildstr_len == 1) {
ret_value = !(*wildstr == wild_many);
}
return ret_value;
}
while (wildstr != wildstr_end && str != str_end) {
while (wildstr != wildstr_end && *wildstr != wild_many &&
*wildstr != wild_one && str != str_end) {
if (*wildstr == wild_prefix && wildstr[1]) wildstr++;
if (my_toupper(cs, *wildstr++) != my_toupper(cs, *str++)) return 1;
}
if (wildstr == wildstr_end) {
return str != str_end;
}
if (str == str_end) {
if (*wildstr == '%' && wildstr + 1 == wildstr_end)
return 0; /* % match empty string */
return (wildstr != wildstr_end);
}
if (*wildstr++ == wild_one) {
++str;
if (str == str_end) /* One char; skip */
{
return wildstr != wildstr_end;
}
} else { /* Found wild_many */
if (wildstr == wildstr_end) return 0; // empty matches wild_many
flag = (*wildstr != wild_many && *wildstr != wild_one);
do {
if (flag) {
char cmp;
if ((cmp = *wildstr) == wild_prefix && wildstr[1]) cmp = wildstr[1];
cmp = my_toupper(cs, cmp);
while (str != str_end && my_toupper(cs, *str) != cmp) str++;
if (str == str_end) return 1;
}
if (wild_case_compare(cs, str, str_end - str, wildstr,
wildstr_end - wildstr) == 0) {
return 0;
}
++str;
} while (str != str_end);
return 1;
}
}
return str != str_end;
}
int wild_case_compare(CHARSET_INFO *cs, const char *str, const char *wildstr) {
return wild_case_compare(cs, str, strlen(str), wildstr, strlen(wildstr));
}
/*
Return a number which, if sorted 'desc', puts strings in this order:
no wildcards
strings containing wildcards and non-wildcard characters
single muilt-wildcard character('%')
empty string
*/
ulong get_sort(uint count, ...) {
va_list args;
va_start(args, count);
ulong sort = 0;
/* Should not use this function with more than 4 arguments for compare. */
assert(count <= 4);
while (count--) {
char *start, *str = va_arg(args, char *);
uint chars = 0;
uint wild_pos = 0;
/*
wild_pos
0 if string is empty
1 if string is a single muilt-wildcard
character('%')
first wildcard position + 1 if string containing wildcards and
non-wildcard characters
*/
if ((start = str)) {
for (; *str; str++) {
if (*str == wild_prefix && str[1])
str++;
else if (*str == wild_many || *str == wild_one) {
wild_pos = (uint)(str - start) + 1;
if (!(wild_pos == 1 && *str == wild_many && *(++str) == '\0'))
wild_pos++;
break;
}
chars = 128; // Marker that chars existed
}
}
sort = (sort << 8) + (wild_pos ? min(wild_pos, 127U) : chars);
}
va_end(args);
return sort;
}
/**
Check if the given host name needs to be resolved or not.
Host name has to be resolved if it actually contains *name*.
For example:
192.168.1.1 --> false
192.168.1.0/255.255.255.0 --> false
% --> false
192.168.1.% --> false
AB% --> false
AAAAFFFF --> true (Hostname)
AAAA:FFFF:1234:5678 --> false
::1 --> false
This function does not check if the given string is a valid host name or
not. It assumes that the argument is a valid host name.
@param hostname the string to check.
@return a flag telling if the argument needs to be resolved or not.
@retval true the argument is a host name and needs to be resolved.
@retval false the argument is either an IP address, or a patter and
should not be resolved.
*/
bool hostname_requires_resolving(const char *hostname) {
/* called only for --skip-name-resolve */
assert(specialflag & SPECIAL_NO_RESOLVE);
if (!hostname) return false;
/*
If the string contains any of {':', '%', '_', '/'}, it is definitely
not a host name:
- ':' means that the string is an IPv6 address;
- '%' or '_' means that the string is a pattern;
- '/' means that the string is an IPv4 network address;
*/
for (const char *p = hostname; *p; ++p) {
switch (*p) {
case ':':
case '%':
case '_':
case '/':
return false;
}
}
/*
Now we have to tell a host name (ab.cd, 12.ab) from an IPv4 address
(12.34.56.78). The assumption is that if the string contains only
digits and dots, it is an IPv4 address. Otherwise -- a host name.
*/
for (const char *p = hostname; *p; ++p) {
if (*p != '.' && !my_isdigit(&my_charset_latin1, *p))
return true; /* a "letter" has been found. */
}
return false; /* all characters are either dots or digits. */
}
GRANT_COLUMN::GRANT_COLUMN(String &c, Access_bitmask y)
: rights(y), column(c.ptr(), c.length()) {}
void GRANT_NAME::set_user_details(const char *h, const char *d, const char *u,
const char *t, bool is_routine) {
/* Host given by user */
set_hostname(&host, h, &memex);
if (db != d) {
db = strdup_root(&memex, d);
if (lower_case_table_names) my_casedn_str(files_charset_info, db);
}
user = strdup_root(&memex, u);
sort = get_sort(3, host.get_host(), db, user);
if (tname != t) {
tname = strdup_root(&memex, t);
if (lower_case_table_names || is_routine)
my_casedn_str(files_charset_info, tname);
}
hash_key = user;
hash_key.push_back('\0');
hash_key.append(db);
hash_key.push_back('\0');
hash_key.append(tname);
hash_key.push_back('\0');
}
GRANT_NAME::GRANT_NAME(const char *h, const char *d, const char *u,
const char *t, Access_bitmask p, bool is_routine)
: db(nullptr), tname(nullptr), privs(p) {
set_user_details(h, d, u, t, is_routine);
}
GRANT_TABLE::GRANT_TABLE(const char *h, const char *d, const char *u,
const char *t, Access_bitmask p, Access_bitmask c)
: GRANT_NAME(h, d, u, t, p, false),
cols(c),
hash_columns(system_charset_info, key_memory_acl_memex) {}
GRANT_NAME::GRANT_NAME(TABLE *form, bool is_routine) {
host.update_hostname(get_field(&memex, form->field[0]));
db = get_field(&memex, form->field[1]);
user = get_field(&memex, form->field[2]);
if (!user) user = "";
sort = get_sort(3, host.get_host(), db, user);
tname = get_field(&memex, form->field[3]);
if (!db || !tname) {
/* Wrong table row; Ignore it */
privs = 0;
return; /* purecov: inspected */
}
if (lower_case_table_names) {
my_casedn_str(files_charset_info, db);
}
if (lower_case_table_names || is_routine) {
my_casedn_str(files_charset_info, tname);
}
hash_key = user;
hash_key.push_back('\0');
hash_key.append(db);
hash_key.push_back('\0');
hash_key.append(tname);
hash_key.push_back('\0');
if (form->field[MYSQL_TABLES_PRIV_FIELD_TABLE_PRIV]) {
privs = (Access_bitmask)form->field[MYSQL_TABLES_PRIV_FIELD_TABLE_PRIV]
->val_int();
privs = fix_rights_for_table(privs);
}
}
GRANT_TABLE::GRANT_TABLE(TABLE *form)
: GRANT_NAME(form, false),
hash_columns(system_charset_info, key_memory_acl_memex) {
if (!db || !tname) {
/* Wrong table row; Ignore it */
cols = 0;
return;
}