]> git.saurik.com Git - apple/securityd.git/blob - src/AuthorizationEngine.cpp
securityd-55137.1.tar.gz
[apple/securityd.git] / src / AuthorizationEngine.cpp
1 /*
2 * Copyright (c) 2000-2004,2009 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24 #include "AuthorizationEngine.h"
25 #include <security_cdsa_utilities/AuthorizationWalkers.h>
26 #include <Security/AuthorizationPriv.h>
27 #include <Security/AuthorizationDB.h>
28
29 #include "authority.h"
30
31 #include <Security/AuthorizationTags.h>
32 #include <Security/AuthorizationTagsPriv.h>
33 #include <security_utilities/logging.h>
34 #include <security_utilities/cfutilities.h>
35 #include <security_utilities/debugging.h>
36 #include "server.h"
37
38 #include <CoreFoundation/CFData.h>
39 #include <CoreFoundation/CFNumber.h>
40 #include <CoreFoundation/CFPropertyList.h>
41
42 #include <errno.h>
43 #include <fcntl.h>
44 #include <float.h>
45 #include <sandbox.h>
46
47 #include <bsm/audit_uevents.h> // AUE_ssauth*
48 #include "ccaudit_extensions.h"
49
50 namespace Authorization {
51
52 using namespace CommonCriteria::Securityd;
53
54
55 //
56 // Errors to be thrown
57 //
58 Error::Error(int err) : error(err)
59 {
60 }
61
62 const char *Error::what() const throw()
63 { return "Authorization error"; }
64
65 int Error::unixError() const throw()
66 { return error; } // @@@ eventually...
67
68 OSStatus Error::osStatus() const throw()
69 { return error; }
70
71 void Error::throwMe(int err) { throw Error(err); }
72
73 //
74 // Engine class
75 //
76 Engine::Engine(const char *configFile) : mAuthdb(configFile)
77 {
78 }
79
80 Engine::~Engine()
81 {
82 }
83
84
85 /*!
86 @function AuthorizationEngine::authorize
87
88 @@@.
89
90 @param inRights (input) List of rights being requested for authorization.
91 @param environment (optional/input) Environment containing information to be used during evaluation.
92 @param flags (input) Optional flags @@@ see AuthorizationCreate for a description.
93 @param inCredentials (input) Credentials already held by the caller.
94 @param outCredentials (output/optional) Credentials obtained, used or refreshed during this call to authorize the requested rights.
95 @param outRights (output/optional) Subset of inRights which were actually authorized.
96
97 @results Returns errAuthorizationSuccess if all rights requested are authorized, or if the kAuthorizationFlagPartialRights flag was specified. Might return other status values like errAuthorizationDenied, errAuthorizationCanceled or errAuthorizationInteractionNotAllowed
98 */
99 OSStatus
100 Engine::authorize(const AuthItemSet &inRights, const AuthItemSet &environment,
101 AuthorizationFlags flags, const CredentialSet *inCredentials, CredentialSet *outCredentials,
102 AuthItemSet &outRights, AuthorizationToken &auth)
103 {
104 CredentialSet credentials;
105 OSStatus status = errAuthorizationSuccess;
106 SecurityAgent::Reason reason = SecurityAgent::noReason;
107
108 // Get current time of day.
109 CFAbsoluteTime now = CFAbsoluteTimeGetCurrent();
110
111 // Update rules from database if needed
112 mAuthdb.sync(now);
113
114 // Check if a credential was passed into the environment and we were asked to extend the rights
115 if (flags & kAuthorizationFlagExtendRights)
116 {
117 string username, password;
118 bool shared = false;
119 for (AuthItemSet::iterator item = environment.begin(); item != environment.end(); item ++)
120 {
121 if (!strcmp((*item)->name(), kAuthorizationEnvironmentUsername))
122 username = (*item)->stringValue();
123 else if (!strcmp((*item)->name(), kAuthorizationEnvironmentPassword))
124 password = (*item)->stringValue();
125 else if (!strcmp((*item)->name(), kAuthorizationEnvironmentShared))
126 shared = true;
127 }
128
129 if (username.length())
130 {
131 // Let's create a credential from the passed in username and password.
132 Credential newCredential(username, password, shared);
133 // If it's valid insert it into the credentials list. Normally this is
134 // only done if it actually authorizes a requested right, but for this
135 // special case (environment) we do it even when no rights are being requested.
136 if (newCredential->isValid())
137 credentials.insert(newCredential);
138 }
139 }
140
141 // generate hints for every authorization
142 AuthItemSet environmentToClient = environment;
143
144 RightAuthenticationLogger logger(auth.creatorAuditToken(), AUE_ssauthorize);
145
146 // create a vector with the first right first
147 std::vector<AuthItemRef> tempRights;
148 for (AuthItemSet::const_iterator it = inRights.begin(); it != inRights.end(); ++it) {
149 if (inRights.firstItemName != NULL && strcmp((*it)->name(), inRights.firstItemName) == 0)
150 tempRights.insert(tempRights.begin(), *it);
151 else
152 tempRights.push_back(*it);
153 }
154
155 bool authExtractPassword = false;
156 std::vector<AuthItemRef>::const_iterator end = tempRights.end();
157 for (std::vector<AuthItemRef>::const_iterator it = tempRights.begin(); it != end; ++it)
158 {
159 // Get the rule for each right we are trying to obtain.
160 const Rule &toplevelRule = mAuthdb.getRule(*it);
161
162 if (false == authExtractPassword)
163 authExtractPassword = toplevelRule->extractPassword();
164
165 string processName = "unknown";
166 string authCreatorName = "unknown";
167 if (SecCodeRef code = Server::process().currentGuest()) {
168 CFRef<CFURLRef> path;
169 if (!SecCodeCopyPath(code, kSecCSDefaultFlags, &path.aref()))
170 processName = cfString(path);
171 }
172 if (SecStaticCodeRef code = auth.creatorCode()) {
173 CFRef<CFURLRef> path;
174 if (!SecCodeCopyPath(code, kSecCSDefaultFlags, &path.aref()))
175 authCreatorName = cfString(path);
176 }
177
178 if (sandbox_check(Server::process().pid(), "authorization-right-obtain", SANDBOX_FILTER_RIGHT_NAME, (*it)->name())) {
179 Syslog::error("Sandbox denied authorizing right '%s' by client '%s' [%d]", (*it)->name(), processName.c_str(), Server::process().pid());
180 return errAuthorizationDenied;
181 }
182 if (auth.creatorSandboxed() && sandbox_check(auth.creatorPid(), "authorization-right-obtain", SANDBOX_FILTER_RIGHT_NAME, (*it)->name())) {
183 Syslog::error("Sandbox denied authorizing right '%s' for authorization created by '%s' [%d]", (*it)->name(), authCreatorName.c_str(), auth.creatorPid());
184 return errAuthorizationDenied;
185 }
186
187 OSStatus result = toplevelRule->evaluate(*it, toplevelRule, environmentToClient, flags, now, inCredentials, credentials, auth, reason, authExtractPassword);
188 secdebug("autheval", "evaluate rule %s for right %s returned %d.", toplevelRule->name().c_str(), (*it)->name(), int(result));
189 SECURITYD_AUTH_EVALRIGHT(&auth, (char *)(*it)->name(), result);
190
191 logger.setRight((*it)->name());
192 logger.logAuthorizationResult(processName.c_str(), authCreatorName.c_str(), result);
193
194 if (result == errAuthorizationSuccess)
195 {
196 outRights.insert(*it);
197 Syslog::info("Succeeded authorizing right '%s' by client '%s' [%d] for authorization created by '%s' [%d] (%X,%d)", (*it)->name(), processName.c_str(), Server::process().pid(), authCreatorName.c_str(), auth.creatorPid(), uint32_t(flags), auth.operatesAsLeastPrivileged());
198 }
199 else if (result == errAuthorizationDenied || result == errAuthorizationInteractionNotAllowed)
200 {
201 if (result == errAuthorizationDenied)
202 {
203 secdebug("autheval", "Failed to authorize right '%s' by client '%s' [%d] for authorization created by '%s' [%d] (%X,%d)", (*it)->name(), processName.c_str(), Server::process().pid(), authCreatorName.c_str(), auth.creatorPid(), uint32_t(flags), auth.operatesAsLeastPrivileged());
204 }
205
206 // add creator pid to authorization token
207 if (!(flags & kAuthorizationFlagPartialRights))
208 {
209 status = result;
210 break;
211 }
212 }
213 else if (result == errAuthorizationCanceled)
214 {
215 status = result;
216 break;
217 }
218 else
219 {
220 Syslog::error("Engine::authorize: Rule::evaluate returned %ld returning errAuthorizationInternal", result);
221 status = errAuthorizationInternal;
222 break;
223 }
224 }
225
226 // purge all uid credentials from the outCredentials for least privileged mode
227 if (auth.operatesAsLeastPrivileged()) {
228 CredentialSet::const_iterator current, it = outCredentials->begin();
229 while(it != outCredentials->end()) {
230 current = it++;
231 if (!(*current)->isRight()) {
232 outCredentials->erase(current);
233 }
234 }
235 }
236
237 if (outCredentials)
238 outCredentials->swap(credentials);
239
240 return status;
241 }
242
243 OSStatus
244 Engine::verifyModification(string inRightName, bool remove,
245 const CredentialSet *inCredentials, CredentialSet *outCredentials, AuthorizationToken &auth)
246 {
247 // Validate right
248
249 // meta rights are constructed as follows:
250 // we don't allow setting of wildcard rights, so you can only be more specific
251 // note that you should never restrict things with a wildcard right without disallowing
252 // changes to the entire domain. ie.
253 // system.privilege. -> never
254 // config.add.system.privilege. -> never
255 // config.modify.system.privilege. -> never
256 // config.delete.system.privilege. -> never
257 // For now we don't allow any configuration of configuration rules
258 // config.config. -> never
259
260 string rightnameToCheck;
261
262 // @@@ verify right name is is not NULL or zero length
263 if (inRightName.length() == 0)
264 return errAuthorizationDenied;
265
266 // @@@ make sure it isn't a wildcard right by checking trailing "."
267 if ( *(inRightName.rbegin()) == '.')
268 return errAuthorizationDenied;
269
270 // @@@ make sure it isn't a configure right by checking it doesn't start with config.
271 if (inRightName.find(kConfigRight, 0) != string::npos)
272 {
273 // special handling of meta right change:
274 // config.add. config.modify. config.remove. config.{}.
275 // check for config.<right> (which always starts with config.config.)
276 rightnameToCheck = string(kConfigRight) + inRightName;
277 }
278 else
279 {
280 // regular check of rights
281 bool existingRule = mAuthdb.existRule(inRightName);
282 if (!remove)
283 {
284 if (existingRule)
285 rightnameToCheck = string(kAuthorizationConfigRightModify) + inRightName;
286 else
287 rightnameToCheck = string(kAuthorizationConfigRightAdd) + inRightName;
288 }
289 else
290 {
291 if (existingRule)
292 rightnameToCheck = string(kAuthorizationConfigRightRemove) + inRightName;
293 else
294 {
295 secdebug("engine", "rule %s doesn't exist.", inRightName.c_str());
296 return errAuthorizationSuccess; // doesn't exist, done
297 }
298 }
299 }
300
301
302 AuthItemSet rights, environment, outRights;
303 rights.insert(AuthItemRef(rightnameToCheck.c_str()));
304 secdebug("engine", "authorizing %s for db modification.", rightnameToCheck.c_str());
305 return authorize(rights, environment, kAuthorizationFlagDefaults | kAuthorizationFlagInteractionAllowed | kAuthorizationFlagExtendRights, inCredentials, outCredentials, outRights, auth);
306 }
307
308 OSStatus
309 Engine::getRule(string &inRightName, CFDictionaryRef *outRuleDefinition)
310 {
311 // Get current time of day.
312 CFAbsoluteTime now = CFAbsoluteTimeGetCurrent();
313
314 // Update rules from database if needed
315 mAuthdb.sync(now);
316
317 CFDictionaryRef definition = mAuthdb.getRuleDefinition(inRightName);
318 if (definition)
319 {
320 if (outRuleDefinition)
321 *outRuleDefinition = definition;
322 else
323 CFRelease(definition);
324
325 return errAuthorizationSuccess;
326 }
327
328 return errAuthorizationDenied;
329 }
330
331 OSStatus
332 Engine::setRule(const char *inRightName, CFDictionaryRef inRuleDefinition, const CredentialSet *inCredentials, CredentialSet *outCredentials, AuthorizationToken &auth)
333 {
334 // Validate rule by constructing it from the passed dictionary
335 if (!mAuthdb.validateRule(inRightName, inRuleDefinition))
336 return errAuthorizationDenied; // @@@ separate error for this?
337
338 OSStatus result = verifyModification(inRightName, false /*setting, not removing*/, inCredentials, outCredentials, auth);
339 if (result != errAuthorizationSuccess)
340 return result;
341
342 // set the rule for the right and save the database
343 mAuthdb.setRule(inRightName, inRuleDefinition);
344
345 return errAuthorizationSuccess;
346 }
347
348 OSStatus
349 Engine::removeRule(const char *inRightName, const CredentialSet *inCredentials, CredentialSet *outCredentials, AuthorizationToken &auth)
350 {
351 // Get current time of day.
352 CFAbsoluteTime now = CFAbsoluteTimeGetCurrent();
353
354 // Update rules from database if needed
355 mAuthdb.sync(now);
356
357 OSStatus result = verifyModification(inRightName, true /*removing*/, inCredentials, outCredentials, auth);
358 if (result != errAuthorizationSuccess)
359 return result;
360
361 // set the rule for the right and save the database
362 mAuthdb.removeRule(inRightName);
363
364 return errAuthorizationSuccess;
365 }
366
367 } // end namespace Authorization