/
authorization_manager.cpp
773 lines (687 loc) · 35.2 KB
/
authorization_manager.cpp
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
/**
* Copyright (C) 2012 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "mongo/db/auth/authorization_manager.h"
#include <string>
#include <vector>
#include "mongo/base/init.h"
#include "mongo/base/status.h"
#include "mongo/db/auth/action_set.h"
#include "mongo/db/auth/action_type.h"
#include "mongo/db/auth/auth_external_state.h"
#include "mongo/db/auth/principal.h"
#include "mongo/db/auth/principal_set.h"
#include "mongo/db/auth/privilege.h"
#include "mongo/db/auth/privilege_set.h"
#include "mongo/db/client.h"
#include "mongo/db/jsobj.h"
#include "mongo/db/namespacestring.h"
#include "mongo/db/security_common.h"
#include "mongo/util/mongoutils/str.h"
namespace mongo {
// this is a config setting, set at startup and not changing after initialization.
bool noauth = true;
AuthInfo::AuthInfo() {
user = "__system";
}
AuthInfo internalSecurity;
const std::string AuthorizationManager::SERVER_RESOURCE_NAME = "$SERVER";
const std::string AuthorizationManager::CLUSTER_RESOURCE_NAME = "$CLUSTER";
namespace {
const std::string ADMIN_DBNAME = "admin";
const std::string LOCAL_DBNAME = "local";
const std::string ROLES_FIELD_NAME = "roles";
const std::string OTHER_DB_ROLES_FIELD_NAME = "otherDBRoles";
const std::string READONLY_FIELD_NAME = "readOnly";
const std::string USERNAME_FIELD_NAME = "user";
const std::string USERSOURCE_FIELD_NAME = "userSource";
const std::string PASSWORD_FIELD_NAME = "pwd";
const std::string SYSTEM_ROLE_READ = "read";
const std::string SYSTEM_ROLE_READ_WRITE = "readWrite";
const std::string SYSTEM_ROLE_USER_ADMIN = "userAdmin";
const std::string SYSTEM_ROLE_DB_ADMIN = "dbAdmin";
const std::string SYSTEM_ROLE_SERVER_ADMIN = "serverAdmin";
const std::string SYSTEM_ROLE_CLUSTER_ADMIN = "clusterAdmin";
const std::string SYSTEM_ROLE_READ_ANY_DB = "readAnyDB";
const std::string SYSTEM_ROLE_READ_WRITE_ANY_DB = "readWriteAnyDatabase";
const std::string SYSTEM_ROLE_USER_ADMIN_ANY_DB = "userAdminAnyDatabase";
const std::string SYSTEM_ROLE_DB_ADMIN_ANY_DB = "dbAdminAnyDatabase";
} // namespace
// ActionSets for the various system roles. These ActionSets contain all the actions that
// a user of each system role is granted.
ActionSet readRoleActions;
ActionSet readWriteRoleActions;
ActionSet userAdminRoleActions;
ActionSet dbAdminRoleActions;
// Separate serverAdmin and clusterAdmin read-only and read-write action for backwards
// compatibility with old-style read-only admin users.
ActionSet serverAdminRoleReadActions;
ActionSet serverAdminRoleWriteActions;
ActionSet serverAdminRoleActions;
ActionSet clusterAdminRoleReadActions;
ActionSet clusterAdminRoleWriteActions;
ActionSet clusterAdminRoleActions;
// Can only be performed by internal connections. Nothing ever explicitly grants these actions,
// but they're included when calling addAllActions on an ActionSet, which is how internal
// connections are granted their privileges.
ActionSet internalActions;
// This sets up the system role ActionSets. This is what determines what actions each role
// is authorized to perform
MONGO_INITIALIZER(AuthorizationSystemRoles)(InitializerContext* context) {
// Read role
// TODO: Remove OLD_READ once commands require the proper actions
readRoleActions.addAction(ActionType::oldRead);
readWriteRoleActions.addAction(ActionType::cloneCollectionLocalSource);
readRoleActions.addAction(ActionType::collStats);
readRoleActions.addAction(ActionType::dbHash);
readRoleActions.addAction(ActionType::dbStats);
readRoleActions.addAction(ActionType::find);
// Read-write role
readWriteRoleActions.addAllActionsFromSet(readRoleActions);
// TODO: Remove OLD_WRITE once commands require the proper actions
readWriteRoleActions.addAction(ActionType::oldWrite);
readWriteRoleActions.addAction(ActionType::cloneCollectionTarget);
readWriteRoleActions.addAction(ActionType::convertToCapped);
readWriteRoleActions.addAction(ActionType::createCollection); // db admin gets this also
readWriteRoleActions.addAction(ActionType::dropCollection);
readWriteRoleActions.addAction(ActionType::dropIndexes);
readWriteRoleActions.addAction(ActionType::emptycapped);
readWriteRoleActions.addAction(ActionType::ensureIndex);
readWriteRoleActions.addAction(ActionType::insert);
readWriteRoleActions.addAction(ActionType::remove);
readWriteRoleActions.addAction(ActionType::renameCollectionSameDB); // db admin gets this also
readWriteRoleActions.addAction(ActionType::update);
// User admin role
userAdminRoleActions.addAction(ActionType::userAdmin);
// DB admin role
dbAdminRoleActions.addAction(ActionType::clean);
dbAdminRoleActions.addAction(ActionType::collMod);
dbAdminRoleActions.addAction(ActionType::collStats);
dbAdminRoleActions.addAction(ActionType::compact);
dbAdminRoleActions.addAction(ActionType::convertToCapped);
dbAdminRoleActions.addAction(ActionType::createCollection); // read_write gets this also
dbAdminRoleActions.addAction(ActionType::dbStats);
dbAdminRoleActions.addAction(ActionType::dropCollection);
dbAdminRoleActions.addAction(ActionType::profileEnable);
dbAdminRoleActions.addAction(ActionType::profileRead);
dbAdminRoleActions.addAction(ActionType::reIndex); // TODO: Should readWrite have this also? This isn't consistent with ENSURE_INDEX and DROP_INDEXES
dbAdminRoleActions.addAction(ActionType::renameCollectionSameDB); // read_write gets this also
dbAdminRoleActions.addAction(ActionType::validate);
// Server admin role
serverAdminRoleReadActions.addAction(ActionType::connPoolStats);
serverAdminRoleReadActions.addAction(ActionType::connPoolSync);
serverAdminRoleReadActions.addAction(ActionType::getCmdLineOpts);
serverAdminRoleReadActions.addAction(ActionType::getLog);
serverAdminRoleReadActions.addAction(ActionType::getParameter);
serverAdminRoleReadActions.addAction(ActionType::getShardMap);
serverAdminRoleReadActions.addAction(ActionType::hostInfo);
serverAdminRoleReadActions.addAction(ActionType::listDatabases);
serverAdminRoleReadActions.addAction(ActionType::logRotate);
serverAdminRoleReadActions.addAction(ActionType::replSetFreeze);
serverAdminRoleReadActions.addAction(ActionType::replSetGetStatus);
serverAdminRoleReadActions.addAction(ActionType::replSetMaintenance);
serverAdminRoleReadActions.addAction(ActionType::replSetStepDown);
serverAdminRoleReadActions.addAction(ActionType::replSetSyncFrom);
serverAdminRoleReadActions.addAction(ActionType::setParameter);
serverAdminRoleReadActions.addAction(ActionType::serverStatus);
serverAdminRoleReadActions.addAction(ActionType::shutdown);
serverAdminRoleReadActions.addAction(ActionType::top);
serverAdminRoleReadActions.addAction(ActionType::touch);
serverAdminRoleReadActions.addAction(ActionType::unlock);
serverAdminRoleWriteActions.addAction(ActionType::applyOps);
serverAdminRoleWriteActions.addAction(ActionType::closeAllDatabases);
serverAdminRoleWriteActions.addAction(ActionType::cpuProfiler);
serverAdminRoleWriteActions.addAction(ActionType::cursorInfo);
serverAdminRoleWriteActions.addAction(ActionType::diagLogging);
serverAdminRoleWriteActions.addAction(ActionType::fsync);
serverAdminRoleWriteActions.addAction(ActionType::inprog);
serverAdminRoleWriteActions.addAction(ActionType::killop);
serverAdminRoleWriteActions.addAction(ActionType::repairDatabase);
serverAdminRoleWriteActions.addAction(ActionType::replSetInitiate);
serverAdminRoleWriteActions.addAction(ActionType::replSetReconfig);
serverAdminRoleWriteActions.addAction(ActionType::resync);
serverAdminRoleActions.addAllActionsFromSet(serverAdminRoleReadActions);
serverAdminRoleActions.addAllActionsFromSet(serverAdminRoleWriteActions);
// Cluster admin role
clusterAdminRoleReadActions.addAction(ActionType::getShardVersion);
clusterAdminRoleReadActions.addAction(ActionType::listShards);
clusterAdminRoleReadActions.addAction(ActionType::netstat);
clusterAdminRoleReadActions.addAction(ActionType::setShardVersion); // TODO: should this be internal?
clusterAdminRoleReadActions.addAction(ActionType::splitVector);
clusterAdminRoleReadActions.addAction(ActionType::unsetSharding);
clusterAdminRoleWriteActions.addAction(ActionType::addShard);
clusterAdminRoleWriteActions.addAction(ActionType::dropDatabase); // TODO: Should there be a CREATE_DATABASE also?
clusterAdminRoleWriteActions.addAction(ActionType::enableSharding);
clusterAdminRoleWriteActions.addAction(ActionType::flushRouterConfig);
clusterAdminRoleWriteActions.addAction(ActionType::moveChunk);
clusterAdminRoleWriteActions.addAction(ActionType::movePrimary);
clusterAdminRoleWriteActions.addAction(ActionType::removeShard);
clusterAdminRoleWriteActions.addAction(ActionType::shardCollection);
clusterAdminRoleWriteActions.addAction(ActionType::shardingState);
clusterAdminRoleWriteActions.addAction(ActionType::split);
clusterAdminRoleWriteActions.addAction(ActionType::splitChunk);
clusterAdminRoleActions.addAllActionsFromSet(clusterAdminRoleReadActions);
clusterAdminRoleActions.addAllActionsFromSet(clusterAdminRoleWriteActions);
// Internal commands
internalActions.addAction(ActionType::clone);
internalActions.addAction(ActionType::handshake);
internalActions.addAction(ActionType::mapReduceShardedFinish);
internalActions.addAction(ActionType::replSetElect);
internalActions.addAction(ActionType::replSetFresh);
internalActions.addAction(ActionType::replSetGetRBID);
internalActions.addAction(ActionType::replSetHeartbeat);
internalActions.addAction(ActionType::writebacklisten);
internalActions.addAction(ActionType::writeBacksQueued);
internalActions.addAction(ActionType::_migrateClone);
internalActions.addAction(ActionType::_recvChunkAbort);
internalActions.addAction(ActionType::_recvChunkCommit);
internalActions.addAction(ActionType::_recvChunkStart);
internalActions.addAction(ActionType::_recvChunkStatus);
internalActions.addAction(ActionType::_transferMods);
return Status::OK();
}
static inline Status _badValue(const char* reason, int location) {
return Status(ErrorCodes::BadValue, reason, location);
}
static inline Status _badValue(const std::string& reason, int location) {
return Status(ErrorCodes::BadValue, reason, location);
}
static inline StringData makeStringDataFromBSONElement(const BSONElement& element) {
return StringData(element.valuestr(), element.valuestrsize() - 1);
}
static Status _checkRolesArray(const BSONElement& rolesElement) {
if (rolesElement.type() != Array) {
return _badValue("Role fields must be an array when present in system.users entries",
0);
}
for (BSONObjIterator iter(rolesElement.embeddedObject()); iter.more(); iter.next()) {
BSONElement element = *iter;
if (element.type() != String || makeStringDataFromBSONElement(element).empty()) {
return _badValue("Roles must be non-empty strings.", 0);
}
}
return Status::OK();
}
Status AuthorizationManager::checkValidPrivilegeDocument(const StringData& dbname,
const BSONObj& doc) {
BSONElement userElement = doc[USERNAME_FIELD_NAME];
BSONElement userSourceElement = doc[USERSOURCE_FIELD_NAME];
BSONElement passwordElement = doc[PASSWORD_FIELD_NAME];
BSONElement rolesElement = doc[ROLES_FIELD_NAME];
BSONElement otherDBRolesElement = doc[OTHER_DB_ROLES_FIELD_NAME];
BSONElement readOnlyElement = doc[READONLY_FIELD_NAME];
// Validate the "user" element.
if (userElement.type() != String)
return _badValue("system.users entry needs 'user' field to be a string", 14051);
if (makeStringDataFromBSONElement(userElement).empty())
return _badValue("system.users entry needs 'user' field to be non-empty", 14053);
// Must set exactly one of "userSource" and "pwd" fields.
if (userSourceElement.eoo() == passwordElement.eoo()) {
return _badValue("system.users entry must have either a 'pwd' field or a 'userSource' "
"field, but not both", 0);
}
// Cannot have both "roles" and "readOnly" elements.
if (!rolesElement.eoo() && !readOnlyElement.eoo()) {
return _badValue("system.users entry must not have both 'roles' and 'readOnly' fields",
0);
}
// Validate the "pwd" element, if present.
if (!passwordElement.eoo()) {
if (passwordElement.type() != String)
return _badValue("system.users entry needs 'pwd' field to be a string", 14052);
if (makeStringDataFromBSONElement(passwordElement).empty())
return _badValue("system.users entry needs 'pwd' field to be non-empty", 14054);
}
// Validate the "userSource" element, if present.
if (!userSourceElement.eoo()) {
if (userSourceElement.type() != String ||
makeStringDataFromBSONElement(userSourceElement).empty()) {
return _badValue("system.users entry needs 'userSource' field to be a non-empty "
"string, if present", 0);
}
if (userSourceElement.str() == dbname) {
return _badValue(mongoutils::str::stream() << "'" << dbname <<
"' is not a valid value for the userSource field in " <<
dbname << ".system.users entries",
0);
}
if (rolesElement.eoo()) {
return _badValue("system.users entry needs 'roles' field if 'userSource' field "
"is present.", 0);
}
}
// Validate the "roles" element.
if (!rolesElement.eoo()) {
Status status = _checkRolesArray(rolesElement);
if (!status.isOK())
return status;
}
if (!otherDBRolesElement.eoo()) {
if (dbname != ADMIN_DBNAME) {
return _badValue("Only admin.system.users entries may contain 'otherDBRoles' "
"fields", 0);
}
if (rolesElement.eoo()) {
return _badValue("system.users entries with 'otherDBRoles' fields must contain "
"'roles' fields", 0);
}
if (otherDBRolesElement.type() != Object) {
return _badValue("'otherDBRoles' field must be an object when present in "
"system.users entries", 0);
}
for (BSONObjIterator iter(otherDBRolesElement.embeddedObject());
iter.more(); iter.next()) {
Status status = _checkRolesArray(*iter);
if (!status.isOK())
return status;
}
}
return Status::OK();
}
AuthorizationManager::AuthorizationManager(AuthExternalState* externalState) {
_externalState.reset(externalState);
}
AuthorizationManager::~AuthorizationManager(){}
ActionSet AuthorizationManager::getAllUserActions() {
ActionSet allActions;
allActions.addAllActionsFromSet(readRoleActions);
allActions.addAllActionsFromSet(readWriteRoleActions);
allActions.addAllActionsFromSet(userAdminRoleActions);
allActions.addAllActionsFromSet(dbAdminRoleActions);
allActions.addAllActionsFromSet(serverAdminRoleActions);
allActions.addAllActionsFromSet(clusterAdminRoleActions);
return allActions;
}
void AuthorizationManager::startRequest() {
_externalState->startRequest();
}
void AuthorizationManager::addAuthorizedPrincipal(Principal* principal) {
_authenticatedPrincipals.add(principal);
}
Principal* AuthorizationManager::lookupPrincipal(const PrincipalName& name) {
return _authenticatedPrincipals.lookup(name);
}
void AuthorizationManager::logoutDatabase(const std::string& dbname) {
Principal* principal = _authenticatedPrincipals.lookupByDBName(dbname);
if (!principal)
return;
_acquiredPrivileges.revokePrivilegesFromPrincipal(principal->getName());
_authenticatedPrincipals.removeByDBName(dbname);
}
PrincipalSet::NameIterator AuthorizationManager::getAuthenticatedPrincipalNames() {
return _authenticatedPrincipals.getNames();
}
Status AuthorizationManager::acquirePrivilege(const Privilege& privilege,
const PrincipalName& authorizingPrincipal) {
if (!_authenticatedPrincipals.lookup(authorizingPrincipal)) {
return Status(ErrorCodes::UserNotFound,
mongoutils::str::stream()
<< "No authenticated principle found with name: "
<< authorizingPrincipal.getUser()
<< " from database "
<< authorizingPrincipal.getDB(),
0);
}
_acquiredPrivileges.grantPrivilege(privilege, authorizingPrincipal);
return Status::OK();
}
void AuthorizationManager::grantInternalAuthorization(const std::string& principalName) {
Principal* principal = new Principal(PrincipalName(principalName, "local"));
ActionSet actions;
actions.addAllActions();
addAuthorizedPrincipal(principal);
fassert(16581, acquirePrivilege(Privilege(PrivilegeSet::WILDCARD_RESOURCE, actions),
principal->getName()).isOK());
}
bool AuthorizationManager::hasInternalAuthorization() {
ActionSet allActions;
allActions.addAllActions();
return _acquiredPrivileges.hasPrivilege(Privilege(PrivilegeSet::WILDCARD_RESOURCE,
allActions));
}
ActionSet AuthorizationManager::getActionsForOldStyleUser(const std::string& dbname,
bool readOnly) {
ActionSet actions;
// Basic actions
if (readOnly) {
actions.addAllActionsFromSet(readRoleActions);
}
else {
actions.addAllActionsFromSet(readWriteRoleActions);
actions.addAllActionsFromSet(dbAdminRoleActions);
actions.addAllActionsFromSet(userAdminRoleActions);
actions.addAction(ActionType::dropDatabase);
actions.addAction(ActionType::repairDatabase);
}
// Admin actions
if (dbname == ADMIN_DBNAME || dbname == LOCAL_DBNAME) {
actions.addAllActionsFromSet(serverAdminRoleReadActions);
actions.addAllActionsFromSet(clusterAdminRoleReadActions);
if (!readOnly) {
actions.addAllActionsFromSet(serverAdminRoleWriteActions);
actions.addAllActionsFromSet(clusterAdminRoleWriteActions);
}
}
return actions;
}
Status AuthorizationManager::acquirePrivilegesFromPrivilegeDocument(
const std::string& dbname, const PrincipalName& principal, const BSONObj& privilegeDocument) {
if (!_authenticatedPrincipals.lookup(principal)) {
return Status(ErrorCodes::UserNotFound,
mongoutils::str::stream()
<< "No authenticated principle found with name: "
<< principal.getUser()
<< " from database "
<< principal.getDB(),
0);
}
if (principal.getUser() == internalSecurity.user) {
// Grant full access to internal user
ActionSet allActions;
allActions.addAllActions();
return acquirePrivilege(Privilege(PrivilegeSet::WILDCARD_RESOURCE, allActions),
principal);
}
return buildPrivilegeSet(dbname, principal, privilegeDocument, &_acquiredPrivileges);
}
Status AuthorizationManager::buildPrivilegeSet(const std::string& dbname,
const PrincipalName& principal,
const BSONObj& privilegeDocument,
PrivilegeSet* result) {
if (!privilegeDocument.hasField(ROLES_FIELD_NAME)) {
// Old-style (v2.2 and prior) privilege document
return _buildPrivilegeSetFromOldStylePrivilegeDocument(dbname,
principal,
privilegeDocument,
result);
}
else {
return _buildPrivilegeSetFromExtendedPrivilegeDocument(
dbname, principal, privilegeDocument, result);
}
}
Status AuthorizationManager::_buildPrivilegeSetFromOldStylePrivilegeDocument(
const std::string& dbname,
const PrincipalName& principal,
const BSONObj& privilegeDocument,
PrivilegeSet* result) {
if (!(privilegeDocument.hasField(USERNAME_FIELD_NAME) &&
privilegeDocument.hasField(PASSWORD_FIELD_NAME))) {
return Status(ErrorCodes::UnsupportedFormat,
mongoutils::str::stream() << "Invalid old-style privilege document "
"received when trying to extract privileges: "
<< privilegeDocument,
0);
}
if (privilegeDocument[USERNAME_FIELD_NAME].str() != principal.getUser()) {
return Status(ErrorCodes::BadValue,
mongoutils::str::stream() << "Principal name from privilege document \""
<< privilegeDocument[USERNAME_FIELD_NAME].str()
<< "\" doesn't match name of provided Principal \""
<< principal.getUser()
<< "\"",
0);
}
bool readOnly = privilegeDocument[READONLY_FIELD_NAME].trueValue();
ActionSet actions = getActionsForOldStyleUser(dbname, readOnly);
std::string resourceName = (dbname == ADMIN_DBNAME || dbname == LOCAL_DBNAME) ?
PrivilegeSet::WILDCARD_RESOURCE : dbname;
result->grantPrivilege(Privilege(resourceName, actions), principal);
return Status::OK();
}
/**
* Adds to "outPrivileges" the privileges associated with having the named "role" on "dbname".
*
* Returns non-OK status if "role" is not a defined role in "dbname".
*/
static Status _addPrivilegesForSystemRole(const std::string& dbname,
const std::string& role,
std::vector<Privilege>* outPrivileges) {
const bool isAdminDB = (dbname == ADMIN_DBNAME);
if (role == SYSTEM_ROLE_READ) {
outPrivileges->push_back(Privilege(dbname, readRoleActions));
}
else if (role == SYSTEM_ROLE_READ_WRITE) {
outPrivileges->push_back(Privilege(dbname, readWriteRoleActions));
}
else if (role == SYSTEM_ROLE_USER_ADMIN) {
outPrivileges->push_back(Privilege(dbname, userAdminRoleActions));
}
else if (role == SYSTEM_ROLE_DB_ADMIN) {
outPrivileges->push_back(Privilege(dbname, dbAdminRoleActions));
}
else if (isAdminDB && role == SYSTEM_ROLE_READ_ANY_DB) {
outPrivileges->push_back(Privilege(PrivilegeSet::WILDCARD_RESOURCE, readRoleActions));
}
else if (isAdminDB && role == SYSTEM_ROLE_READ_WRITE_ANY_DB) {
outPrivileges->push_back(
Privilege(PrivilegeSet::WILDCARD_RESOURCE, readWriteRoleActions));
}
else if (isAdminDB && role == SYSTEM_ROLE_USER_ADMIN_ANY_DB) {
outPrivileges->push_back(
Privilege(PrivilegeSet::WILDCARD_RESOURCE, userAdminRoleActions));
}
else if (isAdminDB && role == SYSTEM_ROLE_DB_ADMIN_ANY_DB) {
outPrivileges->push_back(
Privilege(PrivilegeSet::WILDCARD_RESOURCE, dbAdminRoleActions));
}
else if (isAdminDB && role == SYSTEM_ROLE_SERVER_ADMIN) {
outPrivileges->push_back(
Privilege(PrivilegeSet::WILDCARD_RESOURCE, serverAdminRoleActions));
}
else if (isAdminDB && role == SYSTEM_ROLE_CLUSTER_ADMIN) {
outPrivileges->push_back(
Privilege(PrivilegeSet::WILDCARD_RESOURCE, clusterAdminRoleActions));
}
else {
return Status(ErrorCodes::BadValue,
mongoutils::str::stream() <<"No such role, " << role <<
", in database " << dbname);
}
return Status::OK();
}
/**
* Given a database name and a BSONElement representing an array of roles, populates
* "outPrivileges" with the privileges associated with the given roles on the named database.
*
* Returns Status::OK() on success.
*/
static Status _getPrivilegesFromRoles(const std::string& dbname,
const BSONElement& rolesElement,
std::vector<Privilege>* outPrivileges) {
static const char privilegesTypeMismatchMessage[] =
"Roles must be enumerated in an array of strings.";
if (dbname == PrivilegeSet::WILDCARD_RESOURCE) {
return Status(ErrorCodes::BadValue,
PrivilegeSet::WILDCARD_RESOURCE + " is an invalid database name.");
}
if (rolesElement.type() != Array)
return Status(ErrorCodes::TypeMismatch, privilegesTypeMismatchMessage);
for (BSONObjIterator iter(rolesElement.embeddedObject()); iter.more(); iter.next()) {
BSONElement roleElement = *iter;
if (roleElement.type() != String)
return Status(ErrorCodes::TypeMismatch, privilegesTypeMismatchMessage);
Status status = _addPrivilegesForSystemRole(dbname, roleElement.str(), outPrivileges);
if (!status.isOK())
return status;
}
return Status::OK();
}
Status AuthorizationManager::_buildPrivilegeSetFromExtendedPrivilegeDocument(
const std::string& dbname,
const PrincipalName& principal,
const BSONObj& privilegeDocument,
PrivilegeSet* result) {
if (!privilegeDocument[READONLY_FIELD_NAME].eoo()) {
return Status(ErrorCodes::UnsupportedFormat,
"Privilege documents may not contain both \"readonly\" and "
"\"roles\" fields");
}
std::vector<Privilege> acquiredPrivileges;
// Acquire privileges on "dbname".
Status status = _getPrivilegesFromRoles(
dbname, privilegeDocument[ROLES_FIELD_NAME], &acquiredPrivileges);
if (!status.isOK())
return status;
// If "dbname" is the admin database, handle the otherDBPrivileges field, which
// grants privileges on databases other than "dbname".
BSONElement otherDbPrivileges = privilegeDocument[OTHER_DB_ROLES_FIELD_NAME];
if (dbname == ADMIN_DBNAME) {
switch (otherDbPrivileges.type()) {
case EOO:
break;
case Object: {
for (BSONObjIterator iter(otherDbPrivileges.embeddedObject());
iter.more(); iter.next()) {
BSONElement rolesElement = *iter;
status = _getPrivilegesFromRoles(
rolesElement.fieldName(), rolesElement, &acquiredPrivileges);
if (!status.isOK())
return status;
}
break;
}
default:
return Status(ErrorCodes::TypeMismatch,
"Field \"otherDBRoles\" must be an object, if present.");
}
}
else if (!otherDbPrivileges.eoo()) {
return Status(ErrorCodes::BadValue, "Only the admin database may contain a field "
"called \"otherDBRoles\"");
}
result->grantPrivileges(acquiredPrivileges, principal);
return Status::OK();
}
bool AuthorizationManager::checkAuthorization(const std::string& resource,
ActionType action) {
return checkAuthForPrivilege(Privilege(resource, action)).isOK();
}
bool AuthorizationManager::checkAuthorization(const std::string& resource,
ActionSet actions) {
return checkAuthForPrivilege(Privilege(resource, actions)).isOK();
}
Status AuthorizationManager::checkAuthForQuery(const std::string& ns) {
NamespaceString namespaceString(ns);
verify(!namespaceString.isCommand());
if (namespaceString.coll == "system.users") {
if (!checkAuthorization(ns, ActionType::userAdmin)) {
return Status(ErrorCodes::Unauthorized,
mongoutils::str::stream() <<
"unauthorized to read user information for database " <<
namespaceString.db,
0);
}
}
else if (namespaceString.coll == "system.profile") {
if (!checkAuthorization(ns, ActionType::profileRead)) {
return Status(ErrorCodes::Unauthorized,
mongoutils::str::stream() << "unauthorized to read " <<
namespaceString.db << ".system.profile",
0);
}
}
else {
if (!checkAuthorization(ns, ActionType::find)) {
return Status(ErrorCodes::Unauthorized,
mongoutils::str::stream() << "unauthorized for query on " << ns,
0);
}
}
return Status::OK();
}
Status AuthorizationManager::checkAuthForInsert(const std::string& ns) {
NamespaceString namespaceString(ns);
if (namespaceString.coll == "system.users") {
if (!checkAuthorization(ns, ActionType::userAdmin)) {
return Status(ErrorCodes::Unauthorized,
mongoutils::str::stream() <<
"unauthorized to create user for database " <<
namespaceString.db,
0);
}
}
else {
if (!checkAuthorization(ns, ActionType::insert)) {
return Status(ErrorCodes::Unauthorized,
mongoutils::str::stream() << "unauthorized for insert on " << ns,
0);
}
}
return Status::OK();
}
Status AuthorizationManager::checkAuthForUpdate(const std::string& ns, bool upsert) {
NamespaceString namespaceString(ns);
if (namespaceString.coll == "system.users") {
if (!checkAuthorization(ns, ActionType::userAdmin)) {
return Status(ErrorCodes::Unauthorized,
mongoutils::str::stream() <<
"not authorized to update user information for database " <<
namespaceString.db,
0);
}
}
else {
if (!checkAuthorization(ns, ActionType::update)) {
return Status(ErrorCodes::Unauthorized,
mongoutils::str::stream() << "not authorized for update on " << ns,
0);
}
if (upsert && !checkAuthorization(ns, ActionType::insert)) {
return Status(ErrorCodes::Unauthorized,
mongoutils::str::stream() << "not authorized for upsert on " << ns,
0);
}
}
return Status::OK();
}
Status AuthorizationManager::checkAuthForDelete(const std::string& ns) {
NamespaceString namespaceString(ns);
if (namespaceString.coll == "system.users") {
if (!checkAuthorization(ns, ActionType::userAdmin)) {
return Status(ErrorCodes::Unauthorized,
mongoutils::str::stream() <<
"not authorized to remove user from database " <<
namespaceString.db,
0);
}
}
else {
if (!checkAuthorization(ns, ActionType::remove)) {
return Status(ErrorCodes::Unauthorized,
mongoutils::str::stream() << "not authorized to remove from " << ns,
0);
}
}
return Status::OK();
}
Status AuthorizationManager::checkAuthForGetMore(const std::string& ns) {
return checkAuthForQuery(ns);
}
Status AuthorizationManager::checkAuthForPrivilege(const Privilege& privilege) {
if (_externalState->shouldIgnoreAuthChecks())
return Status::OK();
if (!_acquiredPrivileges.hasPrivilege(privilege))
return Status(ErrorCodes::Unauthorized, "unauthorized", 0);
return Status::OK();
}
Status AuthorizationManager::checkAuthForPrivileges(const vector<Privilege>& privileges) {
if (_externalState->shouldIgnoreAuthChecks())
return Status::OK();
if (!_acquiredPrivileges.hasPrivileges(privileges))
return Status(ErrorCodes::Unauthorized, "unauthorized", 0);
return Status::OK();
}
} // namespace mongo