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
|
/**
* Copyright (C) 2018-present MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* 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
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the Server Side Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#pragma once
#include <string>
#include <vector>
#include "mongo/crypto/sha1_block.h"
#include "mongo/crypto/sha256_block.h"
#include "mongo/db/auth/privilege.h"
#include "mongo/db/auth/resource_pattern.h"
#include "mongo/db/auth/restriction_set.h"
#include "mongo/db/auth/role_name.h"
#include "mongo/db/auth/user_name.h"
#include "mongo/platform/atomic_word.h"
#include "mongo/stdx/unordered_map.h"
#include "mongo/stdx/unordered_set.h"
#include "mongo/util/read_through_cache.h"
namespace mongo {
/**
* Represents a MongoDB user. Stores information about the user necessary for access control
* checks and authentications, such as what privileges this user has, as well as what roles
* the user belongs to.
*
* Every User object is owned by an AuthorizationManager. The AuthorizationManager is the only
* one that should construct, modify, or delete a User object. All other consumers of User must
* use only the const methods. The AuthorizationManager is responsible for maintaining the
* reference count on all User objects it gives out and must not mutate any User objects with
* a non-zero reference count (except to call invalidate()). Any consumer of a User object
* should check isInvalidated() before using it, and if it has been invalidated, it should
* return the object to the AuthorizationManager and fetch a new User object instance for this
* user from the AuthorizationManager.
*/
class User {
User(const User&) = delete;
User& operator=(const User&) = delete;
public:
using UserId = std::vector<std::uint8_t>;
constexpr static auto kSHA1FieldName = "SCRAM-SHA-1"_sd;
constexpr static auto kSHA256FieldName = "SCRAM-SHA-256"_sd;
constexpr static auto kExternalFieldName = "external"_sd;
constexpr static auto kIterationCountFieldName = "iterationCount"_sd;
constexpr static auto kSaltFieldName = "salt"_sd;
constexpr static auto kServerKeyFieldName = "serverKey"_sd;
constexpr static auto kStoredKeyFieldName = "storedKey"_sd;
template <typename HashBlock>
struct SCRAMCredentials {
SCRAMCredentials() : iterationCount(0), salt(""), serverKey(""), storedKey("") {}
int iterationCount;
std::string salt;
std::string serverKey;
std::string storedKey;
bool isValid() const {
constexpr auto kEncodedHashLength = base64::encodedLength(HashBlock::kHashLength);
constexpr auto kEncodedSaltLength = base64::encodedLength(HashBlock::kHashLength - 4);
return (iterationCount > 0) && (salt.size() == kEncodedSaltLength) &&
base64::validate(salt) && (serverKey.size() == kEncodedHashLength) &&
base64::validate(serverKey) && (storedKey.size() == kEncodedHashLength) &&
base64::validate(storedKey);
}
bool empty() const {
return !iterationCount && salt.empty() && serverKey.empty() && storedKey.empty();
}
void toBSON(BSONObjBuilder* builder) const {
builder->append(kIterationCountFieldName, iterationCount);
builder->append(kSaltFieldName, salt);
builder->append(kStoredKeyFieldName, storedKey);
builder->append(kServerKeyFieldName, serverKey);
}
};
struct CredentialData {
CredentialData() : scram_sha1(), scram_sha256(), isExternal(false) {}
SCRAMCredentials<SHA1Block> scram_sha1;
SCRAMCredentials<SHA256Block> scram_sha256;
bool isExternal;
// Select the template determined version of SCRAMCredentials.
// For example: creds.scram<SHA1Block>().isValid()
// is equivalent to creds.scram_sha1.isValid()
template <typename HashBlock>
SCRAMCredentials<HashBlock>& scram();
template <typename HashBlock>
const SCRAMCredentials<HashBlock>& scram() const;
void toBSON(BSONObjBuilder* builder) const {
if (scram_sha1.isValid()) {
BSONObjBuilder sha1ObjBuilder(builder->subobjStart(kSHA1FieldName));
scram_sha1.toBSON(&sha1ObjBuilder);
sha1ObjBuilder.doneFast();
}
if (scram_sha256.isValid()) {
BSONObjBuilder sha256ObjBuilder(builder->subobjStart(kSHA256FieldName));
scram_sha256.toBSON(&sha256ObjBuilder);
sha256ObjBuilder.doneFast();
}
if (isExternal) {
builder->append(kExternalFieldName, true);
}
}
std::vector<StringData> toMechanismsVector() const {
std::vector<StringData> mechanismsVec;
if (scram_sha1.isValid()) {
mechanismsVec.push_back(kSHA1FieldName);
}
if (scram_sha256.isValid()) {
mechanismsVec.push_back(kSHA256FieldName);
}
if (isExternal) {
mechanismsVec.push_back(kExternalFieldName);
}
// Valid CredentialData objects must have at least one mechanism.
invariant(mechanismsVec.size() > 0);
return mechanismsVec;
}
};
using ResourcePrivilegeMap = stdx::unordered_map<ResourcePattern, Privilege>;
explicit User(const UserName& name);
User(User&&) = default;
User& operator=(User&&) = default;
const UserId& getID() const {
return _id;
}
void setID(UserId id) {
_id = std::move(id);
}
/**
* Returns the user name for this user.
*/
const UserName& getName() const {
return _name;
}
/**
* Checks if the user has been invalidated.
*/
bool isInvalidated() const {
return _isInvalidated;
}
/**
* Invalidates the user.
*/
void invalidate() {
_isInvalidated = true;
}
/**
* Returns a digest of the user's identity
*/
const SHA256Block& getDigest() const {
return _digest;
}
/**
* Returns an iterator over the names of the user's direct roles
*/
RoleNameIterator getRoles() const;
/**
* Returns an iterator over the names of the user's indirect roles
*/
RoleNameIterator getIndirectRoles() const;
/**
* Returns true if this user is a member of the given role.
*/
bool hasRole(const RoleName& roleName) const;
/**
* Returns a reference to the information about the user's privileges.
*/
const ResourcePrivilegeMap& getPrivileges() const {
return _privileges;
}
/**
* Returns the CredentialData for this user.
*/
const CredentialData& getCredentials() const;
/**
* Gets the set of actions this user is allowed to perform on the given resource.
*/
const ActionSet getActionsForResource(const ResourcePattern& resource) const;
/**
* Returns true if the user has is allowed to perform an action on the given resource.
*/
bool hasActionsForResource(const ResourcePattern& resource) const;
// Mutators below. Mutation functions should *only* be called by the AuthorizationManager
/**
* Sets this user's authentication credentials.
*/
void setCredentials(const CredentialData& credentials);
/**
* Replaces any existing user role membership information with the roles from "roles".
*/
void setRoles(RoleNameIterator roles);
/**
* Replaces any existing indirect user role membership information with the roles from
* "indirectRoles".
*/
void setIndirectRoles(RoleNameIterator indirectRoles);
/**
* Replaces any existing user privilege information with "privileges".
*/
void setPrivileges(const PrivilegeVector& privileges);
/**
* Adds the given role name to the list of roles of which this user is a member.
*/
void addRole(const RoleName& role);
/**
* Adds the given role names to the list of roles that this user belongs to.
*/
void addRoles(const std::vector<RoleName>& roles);
/**
* Adds the given privilege to the list of privileges this user is authorized for.
*/
void addPrivilege(const Privilege& privilege);
/**
* Adds the given privileges to the list of privileges this user is authorized for.
*/
void addPrivileges(const PrivilegeVector& privileges);
/**
* Replaces any existing authentication restrictions with "restrictions".
*/
void setRestrictions(RestrictionDocuments restrictions) &;
/**
* Gets any set authentication restrictions.
*/
const RestrictionDocuments& getRestrictions() const& noexcept {
return _restrictions;
}
/**
* Replaces any existing authentication restrictions with "restrictions".
*/
void setIndirectRestrictions(RestrictionDocuments restrictions) &;
/**
* Gets any set authentication restrictions.
*/
const RestrictionDocuments& getIndirectRestrictions() const& noexcept {
return _indirectRestrictions;
}
/**
* Process both direct and indirect authentication restrictions.
*/
Status validateRestrictions(OperationContext* opCtx) const;
/**
* Generates a BSON representation of the User object with all the information needed for
* usersInfo.
*/
void reportForUsersInfo(BSONObjBuilder* builder,
bool showCredentials,
bool showPrivileges,
bool showAuthenticationRestrictions) const;
/**
* Returns true if the User object has at least one different direct or indirect role from the
* otherUser.
*/
bool hasDifferentRoles(const User& otherUser) const;
private:
// Unique ID (often UUID) for this user. May be empty for legacy users.
UserId _id;
// The full user name (as specified by the administrator)
UserName _name;
// User was explicitly invalidated
bool _isInvalidated;
// Digest of the full username
SHA256Block _digest;
// Maps resource name to privilege on that resource
ResourcePrivilegeMap _privileges;
// Roles the user has privileges from
stdx::unordered_set<RoleName> _roles;
// Roles that the user indirectly has privileges from, due to role inheritance.
std::vector<RoleName> _indirectRoles;
// Credential information.
CredentialData _credentials;
// Restrictions which must be met by a Client in order to authenticate as this user.
RestrictionDocuments _restrictions;
// Indirect restrictions inherited via roles.
RestrictionDocuments _indirectRestrictions;
};
/**
* Represents the properties required to request a UserHandle.
* This type is hashable and may be used as a key describing requests
*/
struct UserRequest {
UserRequest(const UserName& name, boost::optional<std::set<RoleName>> roles)
: name(name), roles(std::move(roles)) {}
template <typename H>
friend H AbslHashValue(H h, const UserRequest& key) {
auto state = H::combine(std::move(h), key.name);
if (key.roles) {
for (const auto& role : *key.roles) {
state = H::combine(std::move(state), role);
}
}
return state;
}
bool operator==(const UserRequest& key) const {
return name == key.name && roles == key.roles;
}
// The name of the requested user
UserName name;
// Any authorization grants which should override and be used in favor of roles acquisition.
boost::optional<std::set<RoleName>> roles;
};
using UserCache = ReadThroughCache<UserRequest, User>;
using UserHandle = UserCache::ValueHandle;
} // namespace mongo
|