forked from alibaba/AliSQL
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsql_authorization.cc
More file actions
7590 lines (6711 loc) · 269 KB
/
sql_authorization.cc
File metadata and controls
7590 lines (6711 loc) · 269 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_authorization.h"
#include <limits.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <algorithm>
#include <boost/concept/usage.hpp>
#include <boost/function.hpp>
#include <boost/graph/adjacency_iterator.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/breadth_first_search.hpp>
#include <boost/graph/filtered_graph.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/graphml.hpp>
#include <boost/graph/named_function_params.hpp>
#include <boost/graph/properties.hpp>
#include <boost/iterator/iterator_facade.hpp>
#include <boost/move/utility_core.hpp>
#include <boost/property_map/dynamic_property_map.hpp>
#include <boost/property_map/property_map.hpp>
#include <boost/range/irange.hpp>
#include <boost/smart_ptr/make_shared_object.hpp>
#include <boost/smart_ptr/shared_ptr.hpp>
#include <boost/tuple/tuple.hpp>
#include <cstdlib>
#include <iterator>
#include <map>
#include <memory>
#include <set>
#include <sstream>
#include <string>
#include <tuple>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#include "lex_string.h"
#include "m_ctype.h"
#include "m_string.h"
#include "map_helpers.h"
#include "mf_wcomp.h"
#include "my_alloc.h"
#include "my_compiler.h"
#include "my_dbug.h"
#include "my_inttypes.h"
#include "my_loglevel.h"
#include "my_macros.h"
#include "my_sqlcommand.h"
#include "my_sys.h"
#include "mysql/components/services/log_builtins.h"
#include "mysql/components/services/log_shared.h"
#include "mysql/mysql_lex_string.h"
#include "mysql/plugin_audit.h"
#include "mysql/psi/mysql_mutex.h"
#include "mysql/service_mysql_alloc.h"
#include "mysql_com.h"
#include "mysqld_error.h"
#include "prealloced_array.h"
#include "sql/auth/auth_acls.h"
#include "sql/auth/auth_common.h"
#include "sql/auth/auth_internal.h"
#include "sql/auth/auth_utility.h"
#include "sql/auth/dynamic_privilege_table.h"
#include "sql/auth/partial_revokes.h"
#include "sql/auth/role_tables.h"
#include "sql/auth/roles.h"
#include "sql/auth/sql_auth_cache.h"
#include "sql/auth/sql_security_ctx.h"
#include "sql/auth/sql_user_table.h"
#include "sql/current_thd.h"
#include "sql/dd/dd_table.h" // dd::table_exists
#include "sql/debug_sync.h"
#include "sql/derror.h" /* ER_THD */
#include "sql/error_handler.h" /* error_handler */
#include "sql/field.h"
#include "sql/handler.h"
#include "sql/item.h"
#include "sql/key_spec.h" /* Key_spec */
#include "sql/mdl.h"
#include "sql/mysqld.h" /* lower_case_table_names */
#include "sql/nested_join.h"
#include "sql/protocol.h"
#include "sql/sp.h" /* sp_exist_routines */
#include "sql/sql_admin.h" // enum role_enum
#include "sql/sql_alter.h"
#include "sql/sql_audit.h"
#include "sql/sql_base.h" /* open_and_lock_tables */
#include "sql/sql_class.h" /* THD */
#include "sql/sql_connect.h"
#include "sql/sql_error.h"
#include "sql/sql_lex.h"
#include "sql/sql_list.h"
#include "sql/sql_parse.h" /* get_current_user */
#include "sql/sql_rewrite.h" /* Grant_params */
#include "sql/sql_show.h" /* append_identifier */
#include "sql/sql_view.h" /* VIEW_ANY_ACL */
#include "sql/strfunc.h"
#include "sql/system_variables.h"
#include "sql/table.h"
#include "sql/thd_raii.h"
#include "sql_string.h"
#include "template_utils.h"
#include "thr_lock.h"
#include "violite.h"
/**
@file sql_authorization.cc
AUTHORIZATION CODE
*/
/**
@page AUTHORIZATION_PAGE Authorization IDs, roles and users
@section AUTHORIZATION_ID Authentication ID
@subsection AUTH_ID_DEFINITION Definition
Each row in the mysql.user table is identified by a user and host tuple. This
tuple is the authorization ID.
A client can authenticate with an authorization ID and a password. The ID is
then referred to as a user or user name.
@section AUTHORIZATION_PRIVILEGES Privileges ID
@subsection AUTH_PRIV_DEFINITION Definition
A privilege ID is a named token which can be granted to an authorization ID.
A privilege can either be effective or not effective. An effective privilege is
a privilege which used in a session to evaluate if a particular operation is
allowed or not. All effective privileges are granted or inherited but not all
privileges are effective.
@section AUTHORIZATION_ROLES Roles
@subsection AUTH_ROLES_DEFINITION Definition
A role is an authorization ID which can be granted to another authorization ID
by forming an directed edge between them in the role graph where every vertex
is a unique authorization ID. When the effective privilege is calculated, all
connected roles are visited according to their edge direction and their
corresponding granted privileges are aggregated.
@subsection ACTIVE_ROLE Active roles
A role can either be active or inactive. Active roles are kept in a thread
local list which exists solely for the lifetime of a client session. Granted
roles can be made active by
1) a SET ROLE statement,
2) after authentication if the role is a default role,
3) after authentication if the global variable
opt_always_activate_roles_on_login is set to true.
Example: To set the grated role ``team``\@``%`` as an active role, after
authentication, execute: SET ROLE team
@subsection DEFAULT_ROLE Default roles
Each authorization ID has a list of default roles. Default roles belonging to
an authorization ID are made into active roles after authentication iff they
are granted to this ID. If the list of default roles is empty then no roles are
made active after authentication unless the client sets a
SET ROLE statement.
@subsection MANDATORY_ROLE Mandatory roles
A mandatory role is an authorization ID which is implicitly granted to every
other authorization ID which has authenticated, regardless if this role has
been previously granted or not. Mandatory roles are specified in a global
variable. It's not required that the specified list maps to any existing
authorization ID but if there's no previous authorization ID then no mandatory
role can be granted. Mandatory roles are processed sequentially as any other
granted role when the effective privilege of an authorization ID needs to be
calculated iff they are active.
@section AUTHORIZATION_CACHE The effective privilege cache
@subsection OVERVIEW Overview
To avoid recalculating the effective privilege at every step the result is
saved into a cache (See Acl_cache ). The key to this cache is
formed by concatenating authorization ID, the active roles and the version ID
of the cache.
The cache is a lockless hash storage and each element is assembled using
read-only operations on the shared role graph.
@see get_privilege_access_maps
@section AUTHORIZATION_SHOW_GRANTS SHOW GRANTS
The statements @code SHOW GRANT @endcode shows all effective privileges using
the currently active roles for the current user.
The statement @code SHOW GRANT FOR x USING y @endcode is used for listing the
effective privilege for x given y as active roles. If If y isn't specified then
no roles are used. If x isn't specified then the current_user() is used.
Mandatory roles are always excluded from the list of granted roles when this
statement is used.
Example: To show the privilege for a role using no roles:
@code SHOW GRANTS FOR x. @endcode
SHOW-statements does not use the privilege cache and the effective privilege is
recalculated on every execution.
@see mysql_show_grants
To show the role graph use @code SELECT roles_graphml() @endcode
To investigate the role graph use the built in XML functions or the
mysql.role_edges table.
*/
/**
Class to handle sanity checks for GRANT ... AS ... statement
*/
class Grant_validator {
public:
explicit Grant_validator(THD *thd, const char *db,
const List<LEX_USER> &user_list,
Access_bitmask rights, bool revoke,
const List<LEX_CSTRING> &dynamic_privilege,
bool grant_all, LEX_GRANT_AS *grant_as,
TABLE *dynamic_priv_table)
: m_thd(thd),
m_db(db),
m_user_list(user_list),
m_rights(rights),
m_revoke(revoke),
m_dynamic_privilege(dynamic_privilege),
m_grant_all(grant_all),
m_grant_as(grant_as),
m_dynamic_priv_table(dynamic_priv_table),
m_restore(false),
m_backup(nullptr) {}
~Grant_validator();
bool validate();
private:
bool mask_and_return_error();
bool validate_system_user_privileges();
bool validate_dynamic_privileges();
bool validate_and_process_grant_as();
private:
THD *m_thd;
const char *m_db;
const List<LEX_USER> &m_user_list;
Access_bitmask m_rights;
bool m_revoke;
const List<LEX_CSTRING> &m_dynamic_privilege;
bool m_grant_all;
LEX_GRANT_AS *m_grant_as;
TABLE *m_dynamic_priv_table;
bool m_restore;
Security_context *m_backup;
Security_context m_security_context;
};
/*
Destructor. Restores original security context.
*/
Grant_validator::~Grant_validator() {
if (m_restore)
m_thd->security_context()->restore_security_context(m_thd, m_backup);
}
/**
Helper function to mask specific error with generic one.
@returns true always.
*/
bool Grant_validator::mask_and_return_error() {
DBUG_TRACE;
/* Restore security context */
if (m_restore)
m_thd->security_context()->restore_security_context(m_thd, m_backup);
m_restore = false;
/*
Any error set before this point may potentially give away
information about user and/or role. So, clear any error
that may have been raised and replace it with a generic error.
*/
m_thd->get_stmt_da()->reset_diagnostics_area();
my_error(ER_UKNOWN_AUTH_ID_OR_ACCESS_DENIED_FOR_GRANT_AS, MYF(0));
return true;
}
/**
Perform sanity checks for GRANT ... AS ...
@returns status of checks
@retval false Success. Security context may have been changed
@retval true Failure. Error has been raised.
*/
bool Grant_validator::validate_and_process_grant_as() {
DBUG_TRACE;
if (m_grant_as == nullptr || !m_grant_as->grant_as_used) return false;
LEX_USER *user = get_current_user(m_thd, m_grant_as->user);
if (user == nullptr) return mask_and_return_error();
/* Change security context */
if (m_security_context.change_security_context(m_thd, user->user, user->host,
nullptr, &m_backup, true))
return mask_and_return_error();
m_restore = true;
Roles::Role_activation role_activation(m_thd, m_thd->security_context(),
m_grant_as->role_type,
m_grant_as->role_list, false);
if (role_activation.activate()) return mask_and_return_error();
/* Compare restrictions */
Restrictions this_restrictions = m_thd->security_context()->restrictions();
Restrictions other_restrictions = m_backup->restrictions();
if (this_restrictions.has_more_db_restrictions(other_restrictions, m_rights))
return mask_and_return_error();
return false;
}
/**
Validate that if grantee has SYSTEM_USER privileges, current user has it too.
@returns status of the check
@retval false Success
@retval true Current user lacks SYSTEM_USER privilege
*/
bool Grant_validator::validate_system_user_privileges() {
DBUG_TRACE;
if (check_system_user_privilege(m_thd, m_user_list)) return true;
return false;
}
/**
Permission and sanity checks for dynamic privileges.
We check:
1. Current user's ability to grant dynamic privilege
2. SYSTEM_USER is not granted to mandatory roles
@returns status of checks
@retval false Success
@retval true Error validating dynamic privileges
*/
bool Grant_validator::validate_dynamic_privileges() {
DBUG_TRACE;
/* Sanity checks for dynamic privileges */
if (!m_db && (m_dynamic_privilege.elements > 0 || m_grant_all)) {
LEX_CSTRING *priv;
Update_dynamic_privilege_table update_table(m_thd, m_dynamic_priv_table);
List<LEX_CSTRING> *privileges_to_check;
if (m_grant_all) {
/*
Copy all currently available dynamic privileges to the list of
dynamic privileges to grant.
*/
privileges_to_check = new (m_thd->mem_root) List<LEX_CSTRING>;
iterate_all_dynamic_privileges(m_thd, [&](const char *str) {
LEX_CSTRING *new_str = (LEX_CSTRING *)m_thd->alloc(sizeof(LEX_CSTRING));
new_str->str = str;
new_str->length = strlen(str);
privileges_to_check->push_back(new_str);
return false;
});
} else
privileges_to_check =
&const_cast<List<LEX_CSTRING> &>(m_dynamic_privilege);
List_iterator<LEX_CSTRING> priv_it(*privileges_to_check);
bool error = false;
Security_context *sctx = m_thd->security_context();
while ((priv = priv_it++) && !error) {
/*
Privilege to grant dynamic privilege to others is granted if the user
either has super user privileges (currently UPDATE_ACL on mysql.*) or
if the user has a GRANT_OPTION on the specific dynamic privilege he
wants to grant.
Note that this is different than the rules which apply for other
privileges since for them the GRANT OPTION applies on a privilege
scope level (ie global, db or table level).
From a user POV it might appear confusing that some privileges are
more strictly associated with GRANT OPTION than others, but this
choice is made to preserve back compatibility while also paving way
for future improvements where all privileges objects have their own
grant option.
*/
if (check_access(m_thd, UPDATE_ACL, consts::mysql.c_str(), nullptr,
nullptr, true, true) &&
!sctx->has_global_grant(priv->str, priv->length).second) {
my_error(ER_SPECIFIC_ACCESS_DENIED_ERROR, MYF(0), "GRANT OPTION");
return true;
}
if (!m_revoke) {
// Do not grant SYSTEM_USER privilege to a mandatory role
if (consts::system_user.compare(priv->str) == 0) {
std::vector<Role_id> mandatory_roles;
get_mandatory_roles(&mandatory_roles);
List_iterator<LEX_USER> str_list(
const_cast<List<LEX_USER> &>(m_user_list));
LEX_USER *user, *target_user;
while ((target_user = str_list++)) {
if (!(user = get_current_user(m_thd, target_user))) {
my_error(ER_OUTOFMEMORY, MYF(0), sizeof(LEX_USER));
return true;
}
Auth_id_ref auth_id = create_authid_from(user);
for (const auto &rid : mandatory_roles) {
if (rid == auth_id) {
my_error(ER_CANNOT_GRANT_SYSTEM_PRIV_TO_MANDATORY_ROLE, MYF(0),
auth_id.first.str, auth_id.second.str, priv->str);
return true;
}
}
}
}
}
}
}
return false;
}
/**
Umbrella method to perform validation
A possible side effect of this method is that active security context of the
session may have been changed. This is true if GRANT ... AS ... is used.
@returns status of checks
@retval false Success
@retval true Error found during validation
*/
bool Grant_validator::validate() {
DBUG_TRACE;
if (validate_system_user_privileges()) return true;
if (validate_dynamic_privileges()) return true;
/*
This must be the last check because it may change
the active security context of a thread.
*/
if (validate_and_process_grant_as()) return true;
return false;
}
/**
The dynamic privilege is probed in the global map that keeps track of
dynamic privileges registered with server. The policy is that
- Plugin/Component may register a privilege ID
- Any privilege ID that exist in mysql.global_grants is a valid privilege ID
This method assumes that caller must have acquired the necessory ACL_LOCK.
@param [in] privilege Privilege to be checked in the dynamic privilege map
@retval true Privilege is registered
@retval false Otherwise
*/
static bool is_dynamic_privilege_registered(const std::string &privilege) {
if (get_dynamic_privilege_register()->find(privilege) !=
get_dynamic_privilege_register()->end()) {
return true;
}
return false;
}
Granted_roles_graph *g_granted_roles = nullptr;
Role_index_map *g_authid_to_vertex = nullptr;
static char g_active_dummy_user[] = "active dummy user";
extern bool initialized;
extern Default_roles *g_default_roles;
typedef boost::graph_traits<Granted_roles_graph>::adjacency_iterator
Role_adjacency_iterator;
User_to_dynamic_privileges_map *g_dynamic_privileges_map = nullptr;
const char *any_db = "*any*"; // Special symbol for check_access
static bool check_routine_level_acl(THD *thd, const char *db, const char *name,
bool is_proc);
void get_granted_roles(Role_vertex_descriptor &v,
List_of_granted_roles *granted_roles);
/**
This utility function is used by revoke_role() and remove_all_granted_roles()
for removing a specific edge from the role graph.
@param thd Thread handler
@param authid_role The role which should be revoked
@param authid_user The user who will get its role revoked
@param [out] user_vert The vertex descriptor of the user
@param [out] role_vert The vertex descriptor of the role
@return Success state
@retval true No such user
@retval false User was removed
*/
bool revoke_role_helper(THD *thd [[maybe_unused]], std::string &authid_role,
std::string &authid_user,
Role_vertex_descriptor *user_vert,
Role_vertex_descriptor *role_vert) {
DBUG_TRACE;
assert(assert_acl_cache_write_lock(thd));
Role_index_map::iterator it = g_authid_to_vertex->find(authid_user);
if (it == g_authid_to_vertex->end()) {
// No such user
return true;
} else
*user_vert = it->second;
it = g_authid_to_vertex->find(authid_role);
if (it == g_authid_to_vertex->end()) {
// No such role
return true;
} else
*role_vert = it->second;
boost::remove_edge(*user_vert, *role_vert, *g_granted_roles);
return false;
}
/**
This utility function checks for the connecting vertices of the role
descriptor(authid node) and updates the role flag of the corresponding
ACL user. If there are no incoming edges to this authid node then this
is not a role id anymore. It assumes that acl user and role descriptor
are, valid and passed correctly.
@param [in] role_vert The role vertex descriptor
@param [in,out] acl_user The acl role
*/
void static update_role_flag_of_acl_user(
const Role_vertex_descriptor &role_vert, ACL_USER *acl_user) {
degree_s_t count = boost::in_degree(role_vert, *g_granted_roles);
acl_user->is_role = (count > 0) ? true : false;
}
/**
Used by mysql_revoke_role() for revoking a specified role from a specified
user.
@param thd Thread handler
@param role The role which will be revoked
@param user The user who will get its role revoked
*/
void revoke_role(THD *thd, ACL_USER *role, ACL_USER *user) {
std::string authid_role = create_authid_str_from(role);
std::string authid_user = create_authid_str_from(user);
Role_vertex_descriptor user_vert;
Role_vertex_descriptor role_vert;
if (!revoke_role_helper(thd, authid_role, authid_user, &user_vert,
&role_vert)) {
update_role_flag_of_acl_user(role_vert, role);
}
}
/**
Since the gap in the vertex vector was removed all the vertex descriptors
has changed. As a consequence we now need to rebuild the authid_to_vertex
index.
*/
void rebuild_vertex_index(THD *thd [[maybe_unused]]) {
assert(assert_acl_cache_write_lock(thd));
for (auto &acl_user : *acl_users) {
create_role_vertex(&acl_user);
}
g_authid_to_vertex->clear();
boost::graph_traits<Granted_roles_graph>::vertex_iterator vert_it, vert_end;
boost::tie(vert_it, vert_end) = boost::vertices(*g_granted_roles);
for (; vert_it != vert_end; ++vert_it) {
ACL_USER acl_user =
boost::get(boost::vertex_acl_user_t(),
*g_granted_roles)[boost::vertex(*vert_it, *g_granted_roles)];
if (acl_user.user == g_active_dummy_user) {
(*g_authid_to_vertex)["root"] = *vert_it;
} else {
std::string authid = create_authid_str_from(&acl_user);
(*g_authid_to_vertex)[authid] = *vert_it;
}
}
}
bool drop_role(THD *thd, TABLE *edge_table, TABLE *defaults_table,
const Auth_id_ref &authid_user) {
DBUG_TRACE;
bool error = false;
std::vector<ACL_USER> users;
assert(assert_acl_cache_write_lock(thd));
std::string authid_user_str = create_authid_str_from(authid_user);
Role_index_map::iterator it;
if ((it = g_authid_to_vertex->find(authid_user_str)) !=
g_authid_to_vertex->end()) {
/* Fetch source vertex details */
ACL_USER source_acl_user = boost::get(
boost::vertex_acl_user_t(),
*g_granted_roles)[boost::vertex(it->second, *g_granted_roles)];
Auth_id_ref source_user = create_authid_from(&source_acl_user);
/*
Lambda function that drops all adjacent edges (if exists) from the
source_user present in the role_edges table and, keep track of
target acl user.
It assumes all the parameters and captures are valid and sane.
*/
auto modify_role_edges = [&thd, &edge_table, &error,
&source_user](const ACL_USER &target_acl_user) {
Auth_id_ref target_user = create_authid_from(&target_acl_user);
error = modify_role_edges_in_table(thd, edge_table, source_user,
target_user, false, true);
error |= modify_role_edges_in_table(thd, edge_table, target_user,
source_user, false, true);
};
/* Fetch the neighboring vertices from the outgoing edges */
out_edge_itr_t oute_itr, oute_end;
boost::tie(oute_itr, oute_end) =
boost::out_edges(it->second, *g_granted_roles);
for (; oute_itr != oute_end; ++oute_itr) {
ACL_USER target_acl_user = boost::get(
boost::vertex_acl_user_t(),
*g_granted_roles)[boost::target(*oute_itr, *g_granted_roles)];
modify_role_edges(target_acl_user);
users.push_back(target_acl_user);
}
/* Fetch the neighboring vertices from the incoming edges */
in_edge_itr_t ine_itr, ine_end;
boost::tie(ine_itr, ine_end) =
boost::in_edges(it->second, *g_granted_roles);
for (; ine_itr != ine_end; ++ine_itr) {
ACL_USER target_acl_user = boost::get(
boost::vertex_acl_user_t(),
*g_granted_roles)[boost::source(*ine_itr, *g_granted_roles)];
modify_role_edges(target_acl_user);
}
/* Remove this vertex from the graph (along with its edges) */
DBUG_PRINT("info", ("Removing %s from graph and rebuild the index.",
authid_user_str.c_str()));
/*
We clear all edges connecting this vertex but we avoid removing it
from the graph at this time as it would invalidate the vertex
descriptors and we would have to rebuild all indexes. For now it is
enough to remove the index entry. As the roles are reloaded from the
tables the dropped roles will disappear.
*/
boost::clear_vertex(it->second, *g_granted_roles);
/*
If the role authid does not have any incoming edges then update
the role flag of corresponding ACL role.
*/
for (auto &&user_itr : users) {
Role_index_map::iterator role_it =
g_authid_to_vertex->find(create_authid_str_from(&user_itr));
if (role_it != g_authid_to_vertex->end()) {
ACL_USER *acl_role =
find_acl_user(user_itr.host.get_host(), user_itr.user, true);
assert(acl_role != nullptr);
update_role_flag_of_acl_user(role_it->second, acl_role);
}
}
}
// Remove all default role policies assigned to this authid.
clear_default_roles(thd, defaults_table, authid_user, nullptr);
// Remove all default role policies in which this authid is a default role.
std::vector<Default_roles::iterator> delete_policies;
for (auto policy = g_default_roles->begin(); policy != g_default_roles->end();
++policy) {
if (policy->second == authid_user) {
delete_policies.push_back(policy);
}
}
for (auto &&policy : delete_policies) {
modify_default_roles_in_table(thd, defaults_table,
create_authid_from(policy->first),
create_authid_from(policy->second), true);
g_default_roles->erase(policy);
}
return error;
}
/**
Used by @ref mysql_drop_user. Will drop all
@param thd THD handle
@param edge_table Handle to table that stores role grants
@param defaults_table Handle to table that stores default role information
@param user_name User being dropped
@retval true An error occurred
@retval false Success
*/
bool revoke_all_roles_from_user(THD *thd, TABLE *edge_table,
TABLE *defaults_table, LEX_USER *user_name) {
List_of_granted_roles granted_roles;
get_granted_roles(user_name, &granted_roles);
Auth_id_ref user_name_authid = create_authid_from(user_name);
bool error = drop_role(thd, edge_table, defaults_table, user_name_authid);
return error;
}
/**
If possible, it will revoke all roles and default roles from user_from and
set them for user_to instead.
@param thd Thread handle
@param table A table handler
@param user_from The name of the ACL_USER which will be renamed.
@param [out] granted_roles A list of roles that were successfully revoked.
@return success state
@retval true En error occurred
@retval false Successful
*/
bool revoke_all_granted_roles(THD *thd, TABLE *table, LEX_USER *user_from,
List_of_granted_roles *granted_roles) {
DBUG_TRACE;
std::string authid_user = create_authid_str_from(user_from);
Role_index_map::iterator it;
if ((it = g_authid_to_vertex->find(authid_user)) ==
g_authid_to_vertex->end()) {
/* The user from wasn't in the role graph index; nothing to do. */
return true;
}
get_granted_roles(it->second, granted_roles);
Role_vertex_descriptor user_vert;
Role_vertex_descriptor role_vert;
bool errors = false;
for (auto &&ref : *granted_roles) {
std::string role_id_str;
ref.first.auth_str(&role_id_str);
std::string user_from_str = create_authid_str_from(user_from);
Auth_id_ref role_id = create_authid_from(ref.first);
errors = modify_role_edges_in_table(thd, table, role_id,
{user_from->user, user_from->host},
ref.second, true);
if (errors) break;
/*
If the role is revoked then update the flag in the
corresponding ACL authid.
*/
if (!revoke_role_helper(thd, role_id_str, user_from_str, &user_vert,
&role_vert)) {
ACL_USER *acl_role = find_acl_user(ref.first.host().c_str(),
ref.first.user().c_str(), ref.second);
assert(acl_role != nullptr);
update_role_flag_of_acl_user(role_vert, acl_role);
}
}
return errors;
}
bool is_role_id(LEX_USER *authid) {
ACL_USER *acl_user = find_acl_user(authid->host.str, authid->user.str, true);
if (acl_user == nullptr) return false;
return acl_user->is_role;
}
/**
Grants a single role to a single user. The change is made to the in-memory
roles graph and not persistent.
@see mysql_grant_role
@param role A pointer to the role to be granted
@param user A pointer to the user which will be granted
@param with_admin_opt True if the user should have the ability to pass on the
granted role to another authorization id.
*/
void grant_role(ACL_USER *role, const ACL_USER *user, bool with_admin_opt) {
DBUG_TRACE;
bool is_added;
std::string authid_role = create_authid_str_from(role);
std::string authid_user = create_authid_str_from(user);
Role_vertex_descriptor user_vert, role_vert;
Role_index_map::iterator it;
if ((it = g_authid_to_vertex->find(authid_user)) ==
g_authid_to_vertex->end()) {
user_vert = boost::add_vertex(*g_granted_roles);
g_authid_to_vertex->insert(make_pair(authid_user, user_vert));
} else
user_vert = it->second;
if ((it = g_authid_to_vertex->find(authid_role)) ==
g_authid_to_vertex->end()) {
role_vert = boost::add_vertex(*g_granted_roles);
g_authid_to_vertex->insert(make_pair(authid_role, role_vert));
} else
role_vert = it->second;
boost::property_map<Granted_roles_graph, boost::vertex_name_t>::type
user_pname,
role_pname;
user_pname = boost::get(boost::vertex_name_t(), *g_granted_roles);
boost::put(user_pname, user_vert, authid_user);
role_pname = boost::get(boost::vertex_name_t(), *g_granted_roles);
boost::put(role_pname, role_vert, authid_role);
boost::property_map<Granted_roles_graph, boost::vertex_acl_user_t>::type
user_pacl_user,
role_pacl_user;
user_pacl_user = boost::get(boost::vertex_acl_user_t(), *g_granted_roles);
boost::put(user_pacl_user, user_vert, *user);
role_pacl_user = boost::get(boost::vertex_acl_user_t(), *g_granted_roles);
boost::put(role_pacl_user, role_vert, *role);
Role_edge_descriptor edge;
tie(edge, is_added) = add_edge(user_vert, role_vert, *g_granted_roles);
boost::property_map<Granted_roles_graph, boost::edge_capacity_t>::type
edge_colors;
edge_colors = boost::get(boost::edge_capacity_t(), *g_granted_roles);
boost::put(edge_colors, edge, (with_admin_opt ? 1 : 0));
role->is_role = true;
}
/**
Helper function for create_roles_vertices. Creates a vertex in the role
graph and associate it with an ACL_USER. If the ACL_USER already exists in
the vertex-to-acl-user index then we ignore this request.
@param role_acl_user The acial user to be mapped to a vertex.
*/
void create_role_vertex(ACL_USER *role_acl_user) {
Role_vertex_descriptor role_vertex;
Role_index_map::iterator it;
std::string key = create_authid_str_from(role_acl_user);
if ((it = g_authid_to_vertex->find(key)) == g_authid_to_vertex->end()) {
role_vertex = boost::add_vertex(*g_granted_roles);
boost::property_map<Granted_roles_graph, boost::vertex_acl_user_t>::type
root_prop;
root_prop = boost::get(boost::vertex_acl_user_t(), *g_granted_roles);
boost::put(root_prop, role_vertex, *role_acl_user);
boost::property_map<Granted_roles_graph, boost::vertex_name_t>::type
role_pname;
role_pname = boost::get(boost::vertex_name_t(), *g_granted_roles);
boost::put(role_pname, role_vertex, key);
g_authid_to_vertex->insert(std::make_pair(key, role_vertex));
}
}
/**
Renames a user in the mysql.role_edge and the mysql.default_roles
tables. user_to must already exist in the acl_user cache, but user_from
may not as long as it exist in the role graph.
@param thd Thread handler
@param edge_table An open table handle for mysql.edge_mysql
@param defaults_table An open table handle for mysql.default_roles
@param user_from The user to rename
@param user_to The target user name
@see mysql_rename_user
@retval true An error occurred
@retval false Success
*/
bool roles_rename_authid(THD *thd, TABLE *edge_table, TABLE *defaults_table,
LEX_USER *user_from, LEX_USER *user_to) {
assert(assert_acl_cache_write_lock(thd));
ACL_USER *acl_user_to =
find_acl_user(user_to->host.str, user_to->user.str, true);
if (acl_user_to == nullptr) {
/* The target user doesn't exist yet? */
return true;
}
/* Update default roles */
std::vector<Role_id> old_roles;
Auth_id_ref authid_user_from = create_authid_from(user_from);
clear_default_roles(thd, defaults_table, authid_user_from, &old_roles);
List_of_auth_id_refs new_default_role_ref;
for (auto &&role : old_roles) {
Auth_id_ref authid = create_authid_from(role);
new_default_role_ref.push_back(authid);
}
bool ret = alter_user_set_default_roles(thd, defaults_table, user_to,
new_default_role_ref);
if (ret) {
String warning;
append_identifier(thd, &warning, user_from->user.str,
user_from->user.length);
append_identifier(thd, &warning, user_from->host.str,
user_from->host.length);
LogErr(WARNING_LEVEL, ER_SQL_AUTHOR_DEFAULT_ROLES_FAIL, warning.c_ptr());
ret = false;
}
List_of_granted_roles granted_roles;
ret = revoke_all_granted_roles(thd, edge_table, user_from, &granted_roles);
if (!ret) {
for (auto &&ref : granted_roles) {
ACL_USER *acl_role = find_acl_user(ref.first.host().c_str(),
ref.first.user().c_str(), ref.second);
if (acl_role == nullptr) {
/* An invalid reference was encountered; just ignore it. */
continue;
}
grant_role(acl_role, acl_user_to, ref.second);
Auth_id_ref authid_role = create_authid_from(acl_role);
Auth_id_ref authid_user = create_authid_from(acl_user_to);
ret = modify_role_edges_in_table(thd, edge_table, authid_role,
authid_user, ref.second, false);
if (ret) break;
}
}
return ret;
}
/**
Maps a global ACL to a string representation.
@param thd Thread handler
@param want_access An ACL
@param acl_user The associated user which carries the ACL
@param [out] global The resulting string
*/
void make_global_privilege_statement(THD *thd, Access_bitmask want_access,
ACL_USER *acl_user, String *global) {
assert(assert_acl_cache_read_lock(thd));
global->length(0);
global->append(STRING_WITH_LEN("GRANT "));
if (!(want_access & ~GRANT_ACL))
global->append(STRING_WITH_LEN("USAGE"));
else {
bool found = false;
const Access_bitmask test_access = want_access & ~GRANT_ACL;
int counter = 0;
Access_bitmask j = SELECT_ACL;
for (; j <= GLOBAL_ACLS; counter++, j <<= 1) {
if (test_access & j) {
if (found) global->append(STRING_WITH_LEN(", "));
found = true;
global->append(global_acls_vector[counter].c_str(),
global_acls_vector[counter].length());
}
}
}
global->append(STRING_WITH_LEN(" ON *.* TO "));
append_auth_id(thd, acl_user, global);
if (want_access & GRANT_ACL)
global->append(STRING_WITH_LEN(" WITH GRANT OPTION"));
}
/**
Maps a set of database level ACLs to string representations and sends them
through the client protocol.
@param thd The thread handler
@param role The authid associated with the ACLs
@param protocol A handler used for sending data to the client
@param db_map A list of database level ACLs
@param db_wild_map A list of database level ACLs which use pattern matching
@param restrictions List of databases on which there exists different
restrictions for the ACL_USER.
*/
void make_database_privilege_statement(THD *thd, ACL_USER *role,
Protocol *protocol,
const Db_access_map &db_map,
const Db_access_map &db_wild_map,
const DB_restrictions &restrictions) {
assert(assert_acl_cache_read_lock(thd));
auto make_grant_stmts = [thd, role, protocol](const Db_access_map &map) {
for (const Db_access_map::value_type &it : map) {
Access_bitmask want_access = it.second;