]> git.saurik.com Git - apple/securityd.git/blob - src/AuthorizationRule.cpp
securityd-29035.tar.gz
[apple/securityd.git] / src / AuthorizationRule.cpp
1 /*
2 * Copyright (c) 2003-2004 Apple Computer, 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 * AuthorizationRule.cpp
24 * Security
25 *
26 */
27
28 #include "AuthorizationRule.h"
29 #include <Security/AuthorizationTags.h>
30 #include <Security/AuthorizationTagsPriv.h>
31 #include <Security/AuthorizationDB.h>
32 #include <Security/AuthorizationPriv.h>
33 #include <security_utilities/logging.h>
34 #include <security_utilities/ccaudit.h>
35 #include <bsm/audit_uevents.h>
36 #include "authority.h"
37 #include "server.h"
38 #include "process.h"
39 #include "agentquery.h"
40 #include "AuthorizationMechEval.h"
41
42 #include <pwd.h>
43 #include <grp.h>
44 #include <unistd.h>
45 #include <membership.h>
46
47 extern "C" {
48 #include <membershipPriv.h>
49 }
50
51 //
52 // Rule class
53 //
54 namespace Authorization {
55
56 CFStringRef RuleImpl::kUserGroupID = CFSTR(kAuthorizationRuleParameterGroup);
57 CFStringRef RuleImpl::kTimeoutID = CFSTR(kAuthorizationRuleParameterCredentialTimeout);
58 CFStringRef RuleImpl::kSharedID = CFSTR(kAuthorizationRuleParameterCredentialShared);
59 CFStringRef RuleImpl::kAllowRootID = CFSTR(kAuthorizationRuleParameterAllowRoot);
60 CFStringRef RuleImpl::kMechanismsID = CFSTR(kAuthorizationRuleParameterMechanisms);
61 CFStringRef RuleImpl::kSessionOwnerID = CFSTR(kAuthorizationRuleParameterCredentialSessionOwner);
62 CFStringRef RuleImpl::kKofNID = CFSTR(kAuthorizationRuleParameterKofN);
63 CFStringRef RuleImpl::kPromptID = CFSTR(kAuthorizationRuleParameterDefaultPrompt);
64 CFStringRef RuleImpl::kTriesID = CFSTR("tries"); // XXX/cs move to AuthorizationTagsPriv.h
65
66 CFStringRef RuleImpl::kRuleClassID = CFSTR(kAuthorizationRuleClass);
67 CFStringRef RuleImpl::kRuleAllowID = CFSTR(kAuthorizationRuleClassAllow);
68 CFStringRef RuleImpl::kRuleDenyID = CFSTR(kAuthorizationRuleClassDeny);
69 CFStringRef RuleImpl::kRuleUserID = CFSTR(kAuthorizationRuleClassUser);
70 CFStringRef RuleImpl::kRuleDelegateID = CFSTR(kAuthorizationRightRule);
71 CFStringRef RuleImpl::kRuleMechanismsID = CFSTR(kAuthorizationRuleClassMechanisms);
72 CFStringRef RuleImpl::kRuleAuthenticateUserID = CFSTR(kAuthorizationRuleParameterAuthenticateUser);
73
74
75 string
76 RuleImpl::Attribute::getString(CFDictionaryRef config, CFStringRef key, bool required = false, char *defaultValue = "")
77 {
78 CFTypeRef value = CFDictionaryGetValue(config, key);
79 if (value && (CFGetTypeID(value) == CFStringGetTypeID()))
80 {
81 CFStringRef stringValue = reinterpret_cast<CFStringRef>(value);
82 char buffer[512];
83 const char *ptr = CFStringGetCStringPtr(stringValue, kCFStringEncodingUTF8);
84 if (ptr == NULL)
85 {
86 if (CFStringGetCString(stringValue, buffer, sizeof(buffer), kCFStringEncodingUTF8))
87 ptr = buffer;
88 else
89 MacOSError::throwMe(errAuthorizationInternal); // XXX/cs invalid rule
90 }
91
92 return string(ptr);
93 }
94 else
95 if (!required)
96 return string(defaultValue);
97 else
98 MacOSError::throwMe(errAuthorizationInternal); // XXX/cs invalid rule
99 }
100
101 double
102 RuleImpl::Attribute::getDouble(CFDictionaryRef config, CFStringRef key, bool required = false, double defaultValue = 0.0)
103 {
104 double doubleValue = 0;
105
106 CFTypeRef value = CFDictionaryGetValue(config, key);
107 if (value && (CFGetTypeID(value) == CFNumberGetTypeID()))
108 {
109 CFNumberGetValue(reinterpret_cast<CFNumberRef>(value), kCFNumberDoubleType, &doubleValue);
110 }
111 else
112 if (!required)
113 return defaultValue;
114 else
115 MacOSError::throwMe(errAuthorizationInternal); // XXX/cs invalid rule
116
117 return doubleValue;
118 }
119
120 bool
121 RuleImpl::Attribute::getBool(CFDictionaryRef config, CFStringRef key, bool required = false, bool defaultValue = false)
122 {
123 bool boolValue = false;
124 CFTypeRef value = CFDictionaryGetValue(config, key);
125
126 if (value && (CFGetTypeID(value) == CFBooleanGetTypeID()))
127 {
128 boolValue = CFBooleanGetValue(reinterpret_cast<CFBooleanRef>(value));
129 }
130 else
131 if (!required)
132 return defaultValue;
133 else
134 MacOSError::throwMe(errAuthorizationInternal); // XXX/cs invalid rule
135
136 return boolValue;
137 }
138
139 vector<string>
140 RuleImpl::Attribute::getVector(CFDictionaryRef config, CFStringRef key, bool required = false)
141 {
142 vector<string> valueArray;
143
144 CFTypeRef value = CFDictionaryGetValue(config, key);
145 if (value && (CFGetTypeID(value) == CFArrayGetTypeID()))
146 {
147 CFArrayRef evalArray = reinterpret_cast<CFArrayRef>(value);
148
149 for (int index=0; index < CFArrayGetCount(evalArray); index++)
150 {
151 CFTypeRef arrayValue = CFArrayGetValueAtIndex(evalArray, index);
152 if (arrayValue && (CFGetTypeID(arrayValue) == CFStringGetTypeID()))
153 {
154 CFStringRef stringValue = reinterpret_cast<CFStringRef>(arrayValue);
155 char buffer[512];
156 const char *ptr = CFStringGetCStringPtr(stringValue, kCFStringEncodingUTF8);
157 if (ptr == NULL)
158 {
159 if (CFStringGetCString(stringValue, buffer, sizeof(buffer), kCFStringEncodingUTF8))
160 ptr = buffer;
161 else
162 MacOSError::throwMe(errAuthorizationInternal); // XXX/cs invalid rule
163 }
164 valueArray.push_back(string(ptr));
165 }
166 }
167 }
168 else
169 if (required)
170 MacOSError::throwMe(errAuthorizationInternal); // XXX/cs invalid rule
171
172 return valueArray;
173 }
174
175
176 bool RuleImpl::Attribute::getLocalizedPrompts(CFDictionaryRef config, map<string,string> &localizedPrompts)
177 {
178 CFIndex numberOfPrompts = 0;
179 CFDictionaryRef promptsDict;
180 if (CFDictionaryContainsKey(config, kPromptID))
181 {
182 promptsDict = reinterpret_cast<CFDictionaryRef>(CFDictionaryGetValue(config, kPromptID));
183 if (promptsDict && (CFGetTypeID(promptsDict) == CFDictionaryGetTypeID()))
184 numberOfPrompts = CFDictionaryGetCount(promptsDict);
185 }
186 if (numberOfPrompts == 0)
187 return false;
188
189 const void *keys[numberOfPrompts+1];
190 const void *values[numberOfPrompts+1];
191 CFDictionaryGetKeysAndValues(promptsDict, &keys[0], &values[0]);
192
193 while (numberOfPrompts-- > 0)
194 {
195 CFStringRef keyRef = reinterpret_cast<CFStringRef>(keys[numberOfPrompts]);
196 CFStringRef valueRef = reinterpret_cast<CFStringRef>(values[numberOfPrompts]);
197 if (!keyRef || (CFGetTypeID(keyRef) != CFStringGetTypeID()))
198 continue;
199 if (!valueRef || (CFGetTypeID(valueRef) != CFStringGetTypeID()))
200 continue;
201 string key = cfString(keyRef);
202 string value = cfString(valueRef);
203 localizedPrompts[kAuthorizationRuleParameterDescription+key] = value;
204 }
205
206 return true;
207 }
208
209
210 // default rule
211 RuleImpl::RuleImpl() :
212 mType(kUser), mGroupName("admin"), mMaxCredentialAge(300.0), mShared(true), mAllowRoot(false), mSessionOwner(false), mTries(0), mAuthenticateUser(true)
213 {
214 // XXX/cs read default descriptions from somewhere
215 // @@@ Default rule is shared admin group with 5 minute timeout
216 }
217
218 // return rule built from rule definition; throw if invalid.
219 RuleImpl::RuleImpl(const string &inRightName, CFDictionaryRef cfRight, CFDictionaryRef cfRules) : mRightName(inRightName)
220 {
221 // @@@ make sure cfRight is non mutable and never used that way
222
223 if (CFGetTypeID(cfRight) != CFDictionaryGetTypeID())
224 MacOSError::throwMe(errAuthorizationInternal); // XXX/cs invalid rule
225
226 mTries = 0;
227
228 string classTag = Attribute::getString(cfRight, kRuleClassID, false, "");
229
230 if (classTag.length())
231 {
232 if (classTag == kAuthorizationRuleClassAllow)
233 {
234 secdebug("authrule", "%s : rule allow", inRightName.c_str());
235 mType = kAllow;
236 }
237 else if (classTag == kAuthorizationRuleClassDeny)
238 {
239 secdebug("authrule", "%s : rule deny", inRightName.c_str());
240 mType = kDeny;
241 }
242 else if (classTag == kAuthorizationRuleClassUser)
243 {
244 mType = kUser;
245 mGroupName = Attribute::getString(cfRight, kUserGroupID);
246 // grab other user-in-group attributes
247 mMaxCredentialAge = Attribute::getDouble(cfRight, kTimeoutID, false, DBL_MAX);
248 mShared = Attribute::getBool(cfRight, kSharedID);
249 mAllowRoot = Attribute::getBool(cfRight, kAllowRootID);
250 mSessionOwner = Attribute::getBool(cfRight, kSessionOwnerID);
251 // authorization tags can have eval now too
252 mEvalDef = Attribute::getVector(cfRight, kMechanismsID);
253 if (mEvalDef.size() == 0 && cfRules /*only rights default see appserver-admin*/)
254 {
255 CFDictionaryRef cfRuleDef = reinterpret_cast<CFDictionaryRef>(CFDictionaryGetValue(cfRules, CFSTR("authenticate")));
256 if (cfRuleDef && CFGetTypeID(cfRuleDef) == CFDictionaryGetTypeID())
257 mEvalDef = Attribute::getVector(cfRuleDef, kMechanismsID);
258 }
259 mTries = int(Attribute::getDouble(cfRight, kTriesID, false, 3.0)); // XXX/cs double(kAuthorizationMaxTries)
260 mAuthenticateUser = Attribute::getBool(cfRight, kRuleAuthenticateUserID, false, true);
261
262 secdebug("authrule", "%s : rule user in group \"%s\" timeout %g%s%s",
263 inRightName.c_str(),
264 mGroupName.c_str(), mMaxCredentialAge, mShared ? " shared" : "",
265 mAllowRoot ? " allow-root" : "");
266
267 }
268 else if (classTag == kAuthorizationRuleClassMechanisms)
269 {
270 secdebug("authrule", "%s : rule evaluate mechanisms", inRightName.c_str());
271 mType = kEvaluateMechanisms;
272 // mechanisms to evaluate
273 mEvalDef = Attribute::getVector(cfRight, kMechanismsID, true);
274 mTries = int(Attribute::getDouble(cfRight, kTriesID, false, 0.0)); // "forever"
275 mShared = Attribute::getBool(cfRight, kSharedID, false, true);
276 }
277 else if (classTag == kAuthorizationRightRule)
278 {
279 assert(cfRules); // rules can't delegate to other rules
280 secdebug("authrule", "%s : rule delegate rule", inRightName.c_str());
281 mType = kRuleDelegation;
282
283 // string or
284 string ruleDefString = Attribute::getString(cfRight, kRuleDelegateID, false, "");
285 if (ruleDefString.length())
286 {
287 CFStringRef ruleDefRef = makeCFString(ruleDefString);
288 CFDictionaryRef cfRuleDef = reinterpret_cast<CFDictionaryRef>(CFDictionaryGetValue(cfRules, ruleDefRef));
289 if (ruleDefRef)
290 CFRelease(ruleDefRef);
291 if (!cfRuleDef || CFGetTypeID(cfRuleDef) != CFDictionaryGetTypeID())
292 MacOSError::throwMe(errAuthorizationInternal); // XXX/cs invalid rule
293 mRuleDef.push_back(Rule(ruleDefString, cfRuleDef, cfRules));
294 }
295 else // array
296 {
297 vector<string> ruleDef = Attribute::getVector(cfRight, kRuleDelegateID, true);
298 for (vector<string>::const_iterator it = ruleDef.begin(); it != ruleDef.end(); it++)
299 {
300 CFStringRef ruleNameRef = makeCFString(*it);
301 CFDictionaryRef cfRuleDef = reinterpret_cast<CFDictionaryRef>(CFDictionaryGetValue(cfRules, ruleNameRef));
302 if (ruleNameRef)
303 CFRelease(ruleNameRef);
304 if (!cfRuleDef || (CFGetTypeID(cfRuleDef) != CFDictionaryGetTypeID()))
305 MacOSError::throwMe(errAuthorizationInternal); // XXX/cs invalid rule
306 mRuleDef.push_back(Rule(*it, cfRuleDef, cfRules));
307 }
308 }
309
310 mKofN = int(Attribute::getDouble(cfRight, kKofNID, false, 0.0));
311 if (mKofN)
312 mType = kKofN;
313
314 }
315 else
316 {
317 secdebug("authrule", "%s : rule class unknown %s.", inRightName.c_str(), classTag.c_str());
318 MacOSError::throwMe(errAuthorizationInternal); // XXX/cs invalid rule
319 }
320 }
321 else
322 {
323 // no class tag means, this is the abbreviated specification from the API
324 // it _must_ have a definition for "rule" which will be used as a delegate
325 // it may have a comment (not extracted here)
326 // it may have a default prompt, or a whole dictionary of languages (not extracted here)
327 mType = kRuleDelegation;
328 string ruleName = Attribute::getString(cfRight, kRuleDelegateID, true);
329 secdebug("authrule", "%s : rule delegate rule (1): %s", inRightName.c_str(), ruleName.c_str());
330 CFStringRef ruleNameRef = makeCFString(ruleName);
331 CFDictionaryRef cfRuleDef = reinterpret_cast<CFDictionaryRef>(CFDictionaryGetValue(cfRules, ruleNameRef));
332 if (ruleNameRef)
333 CFRelease(ruleNameRef);
334 if (!cfRuleDef || CFGetTypeID(cfRuleDef) != CFDictionaryGetTypeID())
335 MacOSError::throwMe(errAuthorizationInternal); // XXX/cs invalid rule
336 mRuleDef.push_back(Rule(ruleName, cfRuleDef, cfRules));
337 }
338
339 Attribute::getLocalizedPrompts(cfRight, mLocalizedPrompts);
340 }
341
342 /*
343 RuleImpl::~Rule()
344 {
345 }
346 */
347
348 void
349 RuleImpl::setAgentHints(const AuthItemRef &inRight, const Rule &inTopLevelRule, AuthItemSet &environmentToClient, AuthorizationToken &auth) const
350 {
351 string authorizeString(inRight->name());
352 environmentToClient.erase(AuthItemRef(AGENT_HINT_AUTHORIZE_RIGHT));
353 environmentToClient.insert(AuthItemRef(AGENT_HINT_AUTHORIZE_RIGHT, AuthValueOverlay(authorizeString)));
354
355 pid_t creatorPid = auth.creatorPid();
356 environmentToClient.erase(AuthItemRef(AGENT_HINT_CREATOR_PID));
357 environmentToClient.insert(AuthItemRef(AGENT_HINT_CREATOR_PID, AuthValueOverlay(sizeof(pid_t), &creatorPid)));
358
359 Process &thisProcess = Server::process();
360 RefPointer<OSXCode> clientCode = auth.creatorCode();
361 SecurityAgent::RequestorType requestorType = SecurityAgent::unknown;
362 string bundlePath;
363
364 if (clientCode)
365 {
366 string encodedBundle = clientCode->encode();
367 char bundleType = (encodedBundle.c_str())[0]; // yay, no accessor
368 switch(bundleType)
369 {
370 case 'b': requestorType = SecurityAgent::bundle; break;
371 case 't': requestorType = SecurityAgent::tool; break;
372 }
373 bundlePath = clientCode->canonicalPath();
374 }
375
376 AuthItemSet processHints = SecurityAgent::Client::clientHints(requestorType, bundlePath, thisProcess.pid(), thisProcess.uid());
377 environmentToClient.erase(AuthItemRef(AGENT_HINT_CLIENT_TYPE));
378 environmentToClient.erase(AuthItemRef(AGENT_HINT_CLIENT_PATH));
379 environmentToClient.erase(AuthItemRef(AGENT_HINT_CLIENT_PID));
380 environmentToClient.erase(AuthItemRef(AGENT_HINT_CLIENT_UID));
381 environmentToClient.insert(processHints.begin(), processHints.end());
382
383 map<string,string> defaultPrompts = inTopLevelRule->localizedPrompts();
384
385 if (defaultPrompts.empty())
386 defaultPrompts = localizedPrompts();
387
388 if (!defaultPrompts.empty())
389 {
390 map<string,string>::const_iterator it;
391 for (it = defaultPrompts.begin(); it != defaultPrompts.end(); it++)
392 {
393 const string &key = it->first;
394 const string &value = it->second;
395 environmentToClient.insert(AuthItemRef(key.c_str(), AuthValueOverlay(value)));
396 }
397 }
398
399 // add rulename as a hint
400 string ruleName = name();
401 environmentToClient.erase(AuthItemRef(AGENT_HINT_AUTHORIZE_RULE));
402 environmentToClient.insert(AuthItemRef(AGENT_HINT_AUTHORIZE_RULE, AuthValueOverlay(ruleName)));
403 }
404
405 OSStatus
406 RuleImpl::evaluateAuthorization(const AuthItemRef &inRight, const Rule &inRule,
407 AuthItemSet &environmentToClient,
408 AuthorizationFlags flags, CFAbsoluteTime now,
409 const CredentialSet *inCredentials,
410 CredentialSet &credentials, AuthorizationToken &auth) const
411 {
412 OSStatus status = errAuthorizationDenied;
413
414 string usernamehint;
415 evaluateSessionOwner(inRight, inRule, environmentToClient, now, auth, usernamehint);
416 if (usernamehint.length())
417 environmentToClient.insert(AuthItemRef(AGENT_HINT_SUGGESTED_USER, AuthValueOverlay(usernamehint)));
418
419 if ((mType == kUser) && (mGroupName.length()))
420 environmentToClient.insert(AuthItemRef(AGENT_HINT_REQUIRE_USER_IN_GROUP, AuthValueOverlay(mGroupName)));
421
422 uint32 tries;
423 SecurityAgent::Reason reason = SecurityAgent::noReason;
424
425 Process &cltProc = Server::process();
426 // Authorization preserves creator's UID in setuid processes
427 uid_t cltUid = (cltProc.uid() != 0) ? cltProc.uid() : auth.creatorUid();
428 secdebug("AuthEvalMech", "Mechanism invocation by process %d (UID %d)", cltProc.pid(), cltUid);
429
430 AgentMechanismEvaluator eval(cltUid, auth.session(), mEvalDef);
431
432 for (tries = 0; tries < mTries; tries++)
433 {
434 AuthItemRef retryHint(AGENT_HINT_RETRY_REASON, AuthValueOverlay(sizeof(reason), &reason));
435 environmentToClient.erase(retryHint); environmentToClient.insert(retryHint); // replace
436 AuthItemRef triesHint(AGENT_HINT_TRIES, AuthValueOverlay(sizeof(tries), &tries));
437 environmentToClient.erase(triesHint); environmentToClient.insert(triesHint); // replace
438
439 status = eval.run(AuthValueVector(), environmentToClient, auth);
440
441 if ((status == errAuthorizationSuccess) ||
442 (status == errAuthorizationCanceled)) // @@@ can only pass back sideband through context
443 {
444 secdebug("AuthEvalMech", "storing new context for authorization");
445 auth.setInfoSet(eval.context());
446 }
447
448 // successfully ran mechanisms to obtain credential
449 if (status == errAuthorizationSuccess)
450 {
451 // deny is the default
452 status = errAuthorizationDenied;
453
454 CredentialSet newCredentials = makeCredentials(auth);
455 // clear context after extracting credentials
456 auth.scrubInfoSet();
457
458 for (CredentialSet::const_iterator it = newCredentials.begin(); it != newCredentials.end(); ++it)
459 {
460 const Credential& newCredential = *it;
461
462 // @@@ we log the uid a process was running under when it created the authref, which is misleading in the case of loginwindow
463 if (newCredential->isValid())
464 Syslog::info("uid %lu succeeded authenticating as user %s (uid %lu) for right %s.", auth.creatorUid(), newCredential->username().c_str(), newCredential->uid(), inRight->name());
465 else
466 // we can't be sure that the user actually exists so inhibit logging of uid
467 Syslog::error("uid %lu failed to authenticate as user %s for right %s.", auth.creatorUid(), newCredential->username().c_str(), inRight->name());
468
469 if (!newCredential->isValid())
470 {
471 reason = SecurityAgent::invalidPassphrase; //invalidPassphrase;
472 continue;
473 }
474
475 // verify that this credential authorizes right
476 status = evaluateCredentialForRight(auth, inRight, inRule, environmentToClient, now, newCredential, true);
477
478 if (status == errAuthorizationSuccess)
479 {
480 // whack an equivalent credential, so it gets updated to a later achieved credential which must have been more stringent
481 credentials.erase(newCredential); credentials.insert(newCredential);
482 // use valid credential to set context info
483 // XXX/cs keeping this for now, such that the uid is passed back
484 auth.setCredentialInfo(newCredential);
485 secdebug("SSevalMech", "added valid credential for user %s", newCredential->username().c_str());
486 status = errAuthorizationSuccess;
487 break;
488 }
489 else
490 reason = SecurityAgent::userNotInGroup; //unacceptableUser; // userNotInGroup
491 }
492
493 if (status == errAuthorizationSuccess)
494 break;
495 }
496 else
497 if ((status == errAuthorizationCanceled) ||
498 (status == errAuthorizationInternal))
499 {
500 auth.scrubInfoSet();
501 break;
502 }
503 else // last mechanism is now authentication - fail
504 if (status == errAuthorizationDenied)
505 reason = SecurityAgent::invalidPassphrase;
506
507 }
508
509 // If we fell out of the loop because of too many tries, notify user
510 if (tries == mTries)
511 {
512 reason = SecurityAgent::tooManyTries;
513 AuthItemRef retryHint (AGENT_HINT_RETRY_REASON, AuthValueOverlay(sizeof(reason), &reason));
514 environmentToClient.erase(retryHint); environmentToClient.insert(retryHint); // replace
515 AuthItemRef triesHint(AGENT_HINT_TRIES, AuthValueOverlay(sizeof(tries), &tries));
516 environmentToClient.erase(triesHint); environmentToClient.insert(triesHint); // replace
517 eval.run(AuthValueVector(), environmentToClient, auth);
518 // XXX/cs is this still necessary?
519 auth.scrubInfoSet();
520
521 CommonCriteria::AuditRecord auditrec(auth.creatorAuditToken());
522 auditrec.submit(AUE_ssauthorize, CommonCriteria::errTooManyTries, inRight->name());
523 }
524
525 return status;
526 }
527
528 // create externally verified credentials on the basis of
529 // mechanism-provided information
530 CredentialSet
531 RuleImpl::makeCredentials(const AuthorizationToken &auth) const
532 {
533 // fetch context and construct a credential to be tested
534 const AuthItemSet &context = const_cast<AuthorizationToken &>(auth).infoSet();
535 CredentialSet newCredentials;
536
537 do {
538 AuthItemSet::const_iterator found = find_if(context.begin(), context.end(), FindAuthItemByRightName(kAuthorizationEnvironmentUsername) );
539 if (found == context.end())
540 break;
541 string username = (**found).stringValue();
542 secdebug("AuthEvalMech", "found username");
543
544 const uid_t *uid = NULL;
545 found = find_if(context.begin(), context.end(), FindAuthItemByRightName("uid") );
546 if (found != context.end())
547 {
548 uid = static_cast<const uid_t *>((**found).value().data);
549 secdebug("AuthEvalMech", "found uid");
550 }
551
552 const gid_t *gid = NULL;
553 found = find_if(context.begin(), context.end(), FindAuthItemByRightName("gid") );
554 if (found != context.end())
555 {
556 gid = static_cast<const gid_t *>((**found).value().data);
557 secdebug("AuthEvalMech", "found gid");
558 }
559
560 if (username.length() && uid && gid)
561 {
562 // credential is valid because mechanism says so
563 newCredentials.insert(Credential(username, *uid, *gid, mShared));
564 }
565 else
566 {
567 found = find_if(context.begin(), context.end(), FindAuthItemByRightName(kAuthorizationEnvironmentPassword) );
568 if (found != context.end())
569 {
570 secdebug("AuthEvalMech", "found password");
571 string password = (**found).stringValue();
572 secdebug("AuthEvalMech", "falling back on username/password credential if valid");
573 // Call to checkpw in DS
574 Server::active().longTermActivity();
575 Credential newCred(username, password, mShared);
576 newCredentials.insert(newCred);
577 CommonCriteria::AuditRecord auditrec(auth.creatorAuditToken());
578 if (newCred->isValid())
579 auditrec.submit(AUE_ssauthorize, CommonCriteria::errNone, name().c_str());
580 else
581 auditrec.submit(AUE_ssauthorize, CommonCriteria::errInvalidCredential, name().c_str());
582 }
583 }
584 } while(0);
585
586 return newCredentials;
587 }
588
589 // evaluate whether a good credential of the current session owner would authorize a right
590 OSStatus
591 RuleImpl::evaluateSessionOwner(const AuthItemRef &inRight, const Rule &inRule,
592 const AuthItemSet &environment,
593 const CFAbsoluteTime now,
594 const AuthorizationToken &auth,
595 string& usernamehint) const
596 {
597 // username hint is taken from the user who created the authorization, unless it's clearly ineligible
598 OSStatus status = noErr;
599 // @@@ we have no access to current requester uid here and the process uid is only taken when the authorization is created
600 // meaning that a process like loginwindow that drops privs later is screwed.
601
602 uid_t uid;
603 Session &session = auth.session();
604
605 if (session.haveOriginatorUid())
606 uid = session.originatorUid();
607 else
608 uid = auth.creatorUid();
609
610 Server::active().longTermActivity();
611 struct passwd *pw = getpwuid(uid);
612 if (pw != NULL)
613 {
614 // avoid hinting a locked account
615 if ( (pw->pw_passwd == NULL) ||
616 strcmp(pw->pw_passwd, "*") ) {
617 // Check if username will authorize the request and set username to
618 // be used as a hint to the user if so
619 secdebug("AuthEvalMech", "preflight credential from current user, result follows:");
620 status = evaluateCredentialForRight(auth, inRight, inRule, environment, now, Credential(pw->pw_name, pw->pw_uid, pw->pw_gid, mShared), true);
621
622 if (status == errAuthorizationSuccess)
623 usernamehint = pw->pw_name;
624 } //fi
625 endpwent();
626 }
627 return status;
628 }
629
630
631
632 // Return errAuthorizationSuccess if this rule allows access based on the specified credential,
633 // return errAuthorizationDenied otherwise.
634 OSStatus
635 RuleImpl::evaluateCredentialForRight(const AuthorizationToken &auth, const AuthItemRef &inRight, const Rule &inRule, const AuthItemSet &environment, CFAbsoluteTime now, const Credential &credential, bool ignoreShared) const
636 {
637 assert(mType == kUser);
638
639 // Get the username from the credential
640 const char *user = credential->username().c_str();
641
642 // If the credential is not valid or it's age is more than the allowed maximum age
643 // for a credential, deny.
644 if (!credential->isValid())
645 {
646 secdebug("autheval", "credential for user %s is invalid, denying right %s", user, inRight->name());
647 return errAuthorizationDenied;
648 }
649
650 if (now - credential->creationTime() > mMaxCredentialAge)
651 {
652 secdebug("autheval", "credential for user %s has expired, denying right %s", user, inRight->name());
653 return errAuthorizationDenied;
654 }
655
656 if (!ignoreShared && !mShared && credential->isShared())
657 {
658 secdebug("autheval", "shared credential for user %s cannot be used, denying right %s", user, inRight->name());
659 return errAuthorizationDenied;
660 }
661
662 // A root (uid == 0) user can do anything
663 if (credential->uid() == 0)
664 {
665 secdebug("autheval", "user %s has uid 0, granting right %s", user, inRight->name());
666 return errAuthorizationSuccess;
667 }
668
669 if (mSessionOwner)
670 {
671 Session &session = auth.session();
672 if (session.haveOriginatorUid())
673 {
674 uid_t console_user = session.originatorUid();
675
676 if (credential->uid() == console_user)
677 {
678 secdebug("autheval", "user %s is session-owner(uid: %d), granting right %s", user, console_user, inRight->name());
679 return errAuthorizationSuccess;
680 }
681 }
682 else
683 secdebug("autheval", "session-owner check failed.");
684 }
685
686 if (mGroupName.length())
687 {
688 const char *groupname = mGroupName.c_str();
689 Server::active().longTermActivity();
690
691 if (!groupname)
692 return errAuthorizationDenied;
693
694 do
695 {
696 uuid_t group_uuid, user_uuid;
697 int is_member;
698
699 if (mbr_group_name_to_uuid(groupname, group_uuid))
700 break;
701
702 if (mbr_uid_to_uuid(credential->uid(), user_uuid))
703 break;
704
705 if (mbr_check_membership(user_uuid, group_uuid, &is_member))
706 break;
707
708 if (is_member)
709 {
710 secdebug("autheval", "user %s is a member of group %s, granting right %s",
711 user, groupname, inRight->name());
712 return errAuthorizationSuccess;
713 }
714
715 }
716 while (0);
717
718 secdebug("autheval", "user %s is not a member of group %s, denying right %s",
719 user, groupname, inRight->name());
720 }
721
722 return errAuthorizationDenied;
723 }
724
725
726
727 OSStatus
728 RuleImpl::evaluateUser(const AuthItemRef &inRight, const Rule &inRule,
729 AuthItemSet &environmentToClient, AuthorizationFlags flags,
730 CFAbsoluteTime now, const CredentialSet *inCredentials, CredentialSet &credentials,
731 AuthorizationToken &auth) const
732 {
733 // If we got here, this is a kUser type rule, let's start looking for a
734 // credential that is satisfactory
735
736 // Zeroth -- Here is an extra special saucy ugly hack to allow authorizations
737 // created by a proccess running as root to automatically get a right.
738 if (mAllowRoot && auth.creatorUid() == 0)
739 {
740 secdebug("autheval", "creator of authorization has uid == 0 granting right %s",
741 inRight->name());
742 return errAuthorizationSuccess;
743 }
744
745 // if we're not supposed to authenticate evaluate the session-owner against the group
746 if (!mAuthenticateUser)
747 {
748 string username;
749 OSStatus status = evaluateSessionOwner(inRight, inRule, environmentToClient, now, auth, username);
750
751 if (!status)
752 return errAuthorizationSuccess;
753
754 return errAuthorizationDenied;
755 }
756
757 // First -- go though the credentials we either already used or obtained during this authorize operation.
758 for (CredentialSet::const_iterator it = credentials.begin(); it != credentials.end(); ++it)
759 {
760 OSStatus status = evaluateCredentialForRight(auth, inRight, inRule, environmentToClient, now, *it, true);
761 if (status != errAuthorizationDenied)
762 {
763 // add credential to authinfo
764 auth.setCredentialInfo(*it);
765 return status;
766 }
767 }
768
769 // Second -- go though the credentials passed in to this authorize operation by the state management layer.
770 if (inCredentials)
771 {
772 for (CredentialSet::const_iterator it = inCredentials->begin(); it != inCredentials->end(); ++it)
773 {
774 OSStatus status = evaluateCredentialForRight(auth, inRight, inRule, environmentToClient, now, *it, false);
775 if (status == errAuthorizationSuccess)
776 {
777 // Add the credential we used to the output set.
778 // whack an equivalent credential, so it gets updated to a later achieved credential which must have been more stringent
779 credentials.erase(*it); credentials.insert(*it);
780 // add credential to authinfo
781 auth.setCredentialInfo(*it);
782
783 return status;
784 }
785 else if (status != errAuthorizationDenied)
786 return status;
787 }
788 }
789
790 // Finally -- We didn't find the credential in our passed in credential lists. Obtain a new credential if
791 // our flags let us do so.
792 if (!(flags & kAuthorizationFlagExtendRights))
793 return errAuthorizationDenied;
794
795 // authorizations that timeout immediately cannot be preauthorized
796 if ((flags & kAuthorizationFlagPreAuthorize) &&
797 (mMaxCredentialAge == 0.0))
798 {
799 inRight->setFlags(inRight->flags() | kAuthorizationFlagCanNotPreAuthorize);
800 return errAuthorizationSuccess;
801 }
802
803 if (!(flags & kAuthorizationFlagInteractionAllowed))
804 return errAuthorizationInteractionNotAllowed;
805
806 setAgentHints(inRight, inRule, environmentToClient, auth);
807
808 // If a different evaluation is prescribed,
809 // we'll run that and validate the credentials from there
810 // we fall back on a default configuration
811 return evaluateAuthorization(inRight, inRule, environmentToClient, flags, now, inCredentials, credentials, auth);
812 }
813
814 OSStatus
815 RuleImpl::evaluateMechanismOnly(const AuthItemRef &inRight, const Rule &inRule, AuthItemSet &environmentToClient, AuthorizationToken &auth, CredentialSet &outCredentials) const
816 {
817 uint32 tries = 0;
818 OSStatus status;
819
820 Process &cltProc = Server::process();
821 // Authorization preserves creator's UID in setuid processes
822 uid_t cltUid = (cltProc.uid() != 0) ? cltProc.uid() : auth.creatorUid();
823 secdebug("AuthEvalMech", "Mechanism invocation by process %d (UID %d)", cltProc.pid(), cltUid);
824
825 {
826 AgentMechanismEvaluator eval(cltUid, auth.session(), mEvalDef);
827
828 do
829 {
830 setAgentHints(inRight, inRule, environmentToClient, auth);
831 AuthItemRef triesHint(AGENT_HINT_TRIES, AuthValueOverlay(sizeof(tries), &tries));
832 environmentToClient.erase(triesHint); environmentToClient.insert(triesHint); // replace
833
834 status = eval.run(AuthValueVector(), environmentToClient, auth);
835
836 if ((status == errAuthorizationSuccess) ||
837 (status == errAuthorizationCanceled)) // @@@ can only pass back sideband through context
838 {
839 secdebug("AuthEvalMech", "storing new context for authorization");
840 auth.setInfoSet(eval.context());
841 if (status == errAuthorizationSuccess)
842 {
843 outCredentials = makeCredentials(auth);
844 }
845 }
846
847 tries++;
848 }
849 while ((status == errAuthorizationDenied) // only if we have an expected failure we continue
850 && ((mTries == 0) // mTries == 0 means we try forever
851 || ((mTries > 0) // mTries > 0 means we try up to mTries times
852 && (tries < mTries))));
853 }
854
855 // HACK kill all hosts to free pages for low memory systems
856 if (name() == "system.login.console")
857 {
858 QueryInvokeMechanism query(securityAgent, auth.session());
859 query.terminateAgent();
860 QueryInvokeMechanism query2(privilegedAuthHost, auth.session());
861 query2.terminateAgent();
862 }
863
864 return status;
865 }
866
867 OSStatus
868 RuleImpl::evaluateRules(const AuthItemRef &inRight, const Rule &inRule,
869 AuthItemSet &environmentToClient, AuthorizationFlags flags,
870 CFAbsoluteTime now, const CredentialSet *inCredentials, CredentialSet &credentials,
871 AuthorizationToken &auth) const
872 {
873 // line up the rules to try
874 if (!mRuleDef.size())
875 return errAuthorizationSuccess;
876
877 uint32_t count = 0;
878 OSStatus status = errAuthorizationSuccess;
879 vector<Rule>::const_iterator it;
880
881 for (it = mRuleDef.begin();it != mRuleDef.end(); it++)
882 {
883 // are we at k yet?
884 if ((mType == kKofN) && (count == mKofN))
885 return errAuthorizationSuccess;
886
887 // get a rule and try it
888 status = (*it)->evaluate(inRight, inRule, environmentToClient, flags, now, inCredentials, credentials, auth);
889
890 // if status is cancel/internal error abort
891 if ((status == errAuthorizationCanceled) || (status == errAuthorizationInternal))
892 return status;
893
894 if (status != errAuthorizationSuccess)
895 {
896 // continue if we're only looking for k of n
897 if (mType == kKofN)
898 continue;
899
900 break;
901 }
902 else
903 count++;
904 }
905
906 return status; // return the last failure
907 }
908
909
910 OSStatus
911 RuleImpl::evaluate(const AuthItemRef &inRight, const Rule &inRule,
912 AuthItemSet &environmentToClient, AuthorizationFlags flags,
913 CFAbsoluteTime now, const CredentialSet *inCredentials, CredentialSet &credentials,
914 AuthorizationToken &auth) const
915 {
916 switch (mType)
917 {
918 case kAllow:
919 secdebug("autheval", "rule is always allow");
920 return errAuthorizationSuccess;
921 case kDeny:
922 secdebug("autheval", "rule is always deny");
923 return errAuthorizationDenied;
924 case kUser:
925 secdebug("autheval", "rule is user");
926 return evaluateUser(inRight, inRule, environmentToClient, flags, now, inCredentials, credentials, auth);
927 case kRuleDelegation:
928 secdebug("autheval", "rule evaluates rules");
929 return evaluateRules(inRight, inRule, environmentToClient, flags, now, inCredentials, credentials, auth);
930 case kKofN:
931 secdebug("autheval", "rule evaluates k-of-n rules");
932 return evaluateRules(inRight, inRule, environmentToClient, flags, now, inCredentials, credentials, auth);
933 case kEvaluateMechanisms:
934 secdebug("autheval", "rule evaluates mechanisms");
935 return evaluateMechanismOnly(inRight, inRule, environmentToClient, auth, credentials);
936 default:
937 MacOSError::throwMe(errAuthorizationInternal); // XXX/cs invalid rule
938 }
939 }
940
941 Rule::Rule() : RefPointer<RuleImpl>(new RuleImpl()) {}
942 Rule::Rule(const string &inRightName, CFDictionaryRef cfRight, CFDictionaryRef cfRules) : RefPointer<RuleImpl>(new RuleImpl(inRightName, cfRight, cfRules)) {}
943
944
945
946 } // end namespace Authorization