2 * Copyright (c) 2003-2004,2008-2009 Apple Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
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
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.
21 * @APPLE_LICENSE_HEADER_END@
23 * AuthorizationRule.cpp
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 <bsm/audit_uevents.h>
35 #include "ccaudit_extensions.h"
36 #include "authority.h"
39 #include "agentquery.h"
40 #include "AuthorizationMechEval.h"
45 #include <membership.h>
48 #include <membershipPriv.h>
51 using namespace CommonCriteria::Securityd
;
56 namespace Authorization
{
58 CFStringRef
RuleImpl::kUserGroupID
= CFSTR(kAuthorizationRuleParameterGroup
);
59 CFStringRef
RuleImpl::kTimeoutID
= CFSTR(kAuthorizationRuleParameterCredentialTimeout
);
60 CFStringRef
RuleImpl::kSharedID
= CFSTR(kAuthorizationRuleParameterCredentialShared
);
61 CFStringRef
RuleImpl::kAllowRootID
= CFSTR(kAuthorizationRuleParameterAllowRoot
);
62 CFStringRef
RuleImpl::kMechanismsID
= CFSTR(kAuthorizationRuleParameterMechanisms
);
63 CFStringRef
RuleImpl::kSessionOwnerID
= CFSTR(kAuthorizationRuleParameterCredentialSessionOwner
);
64 CFStringRef
RuleImpl::kKofNID
= CFSTR(kAuthorizationRuleParameterKofN
);
65 CFStringRef
RuleImpl::kPromptID
= CFSTR(kAuthorizationRuleParameterDefaultPrompt
);
66 CFStringRef
RuleImpl::kTriesID
= CFSTR("tries"); // XXX/cs move to AuthorizationTagsPriv.h
68 CFStringRef
RuleImpl::kRuleClassID
= CFSTR(kAuthorizationRuleClass
);
69 CFStringRef
RuleImpl::kRuleAllowID
= CFSTR(kAuthorizationRuleClassAllow
);
70 CFStringRef
RuleImpl::kRuleDenyID
= CFSTR(kAuthorizationRuleClassDeny
);
71 CFStringRef
RuleImpl::kRuleUserID
= CFSTR(kAuthorizationRuleClassUser
);
72 CFStringRef
RuleImpl::kRuleDelegateID
= CFSTR(kAuthorizationRightRule
);
73 CFStringRef
RuleImpl::kRuleMechanismsID
= CFSTR(kAuthorizationRuleClassMechanisms
);
74 CFStringRef
RuleImpl::kRuleAuthenticateUserID
= CFSTR(kAuthorizationRuleParameterAuthenticateUser
);
78 RuleImpl::Attribute::getString(CFDictionaryRef config
, CFStringRef key
, bool required
= false, const char *defaultValue
= "")
80 CFTypeRef value
= CFDictionaryGetValue(config
, key
);
81 if (value
&& (CFGetTypeID(value
) == CFStringGetTypeID()))
83 CFStringRef stringValue
= reinterpret_cast<CFStringRef
>(value
);
85 const char *ptr
= CFStringGetCStringPtr(stringValue
, kCFStringEncodingUTF8
);
88 if (CFStringGetCString(stringValue
, buffer
, sizeof(buffer
), kCFStringEncodingUTF8
))
92 Syslog::alert("Could not convert CFString to C string");
93 MacOSError::throwMe(errAuthorizationInternal
);
101 return string(defaultValue
);
104 Syslog::alert("Failed to get rule string");
105 MacOSError::throwMe(errAuthorizationInternal
);
110 RuleImpl::Attribute::getDouble(CFDictionaryRef config
, CFStringRef key
, bool required
= false, double defaultValue
= 0.0)
112 double doubleValue
= 0;
114 CFTypeRef value
= CFDictionaryGetValue(config
, key
);
115 if (value
&& (CFGetTypeID(value
) == CFNumberGetTypeID()))
117 CFNumberGetValue(reinterpret_cast<CFNumberRef
>(value
), kCFNumberDoubleType
, &doubleValue
);
124 Syslog::alert("Failed to get rule double value");
125 MacOSError::throwMe(errAuthorizationInternal
);
132 RuleImpl::Attribute::getBool(CFDictionaryRef config
, CFStringRef key
, bool required
= false, bool defaultValue
= false)
134 bool boolValue
= false;
135 CFTypeRef value
= CFDictionaryGetValue(config
, key
);
137 if (value
&& (CFGetTypeID(value
) == CFBooleanGetTypeID()))
139 boolValue
= CFBooleanGetValue(reinterpret_cast<CFBooleanRef
>(value
));
146 Syslog::alert("Failed to get rule bool value");
147 MacOSError::throwMe(errAuthorizationInternal
);
154 RuleImpl::Attribute::getVector(CFDictionaryRef config
, CFStringRef key
, bool required
= false)
156 vector
<string
> valueArray
;
158 CFTypeRef value
= CFDictionaryGetValue(config
, key
);
159 if (value
&& (CFGetTypeID(value
) == CFArrayGetTypeID()))
161 CFArrayRef evalArray
= reinterpret_cast<CFArrayRef
>(value
);
163 CFIndex numItems
= CFArrayGetCount(evalArray
);
164 for (CFIndex index
=0; index
< numItems
; index
++)
166 CFTypeRef arrayValue
= CFArrayGetValueAtIndex(evalArray
, index
);
167 if (arrayValue
&& (CFGetTypeID(arrayValue
) == CFStringGetTypeID()))
169 CFStringRef stringValue
= reinterpret_cast<CFStringRef
>(arrayValue
);
171 const char *ptr
= CFStringGetCStringPtr(stringValue
, kCFStringEncodingUTF8
);
174 if (CFStringGetCString(stringValue
, buffer
, sizeof(buffer
), kCFStringEncodingUTF8
))
178 Syslog::alert("Failed to convert CFString to C string for item %u in array", index
);
179 MacOSError::throwMe(errAuthorizationInternal
);
182 valueArray
.push_back(string(ptr
));
189 Syslog::alert("Value for key either not present or not a CFArray");
190 MacOSError::throwMe(errAuthorizationInternal
);
197 bool RuleImpl::Attribute::getLocalizedPrompts(CFDictionaryRef config
, map
<string
,string
> &localizedPrompts
)
199 CFIndex numberOfPrompts
= 0;
200 CFDictionaryRef promptsDict
;
201 if (CFDictionaryContainsKey(config
, kPromptID
))
203 promptsDict
= reinterpret_cast<CFDictionaryRef
>(CFDictionaryGetValue(config
, kPromptID
));
204 if (promptsDict
&& (CFGetTypeID(promptsDict
) == CFDictionaryGetTypeID()))
205 numberOfPrompts
= CFDictionaryGetCount(promptsDict
);
207 if (numberOfPrompts
== 0)
210 const void *keys
[numberOfPrompts
+1];
211 const void *values
[numberOfPrompts
+1];
212 CFDictionaryGetKeysAndValues(promptsDict
, &keys
[0], &values
[0]);
214 while (numberOfPrompts
-- > 0)
216 CFStringRef keyRef
= reinterpret_cast<CFStringRef
>(keys
[numberOfPrompts
]);
217 CFStringRef valueRef
= reinterpret_cast<CFStringRef
>(values
[numberOfPrompts
]);
218 if (!keyRef
|| (CFGetTypeID(keyRef
) != CFStringGetTypeID()))
220 if (!valueRef
|| (CFGetTypeID(valueRef
) != CFStringGetTypeID()))
222 string key
= cfString(keyRef
);
223 string value
= cfString(valueRef
);
224 localizedPrompts
[kAuthorizationRuleParameterDescription
+key
] = value
;
232 RuleImpl::RuleImpl() :
233 mType(kUser
), mGroupName("admin"), mMaxCredentialAge(300.0), mShared(true), mAllowRoot(false), mSessionOwner(false), mTries(0), mAuthenticateUser(true)
235 // XXX/cs read default descriptions from somewhere
236 // @@@ Default rule is shared admin group with 5 minute timeout
239 // return rule built from rule definition; throw if invalid.
240 RuleImpl::RuleImpl(const string
&inRightName
, CFDictionaryRef cfRight
, CFDictionaryRef cfRules
) : mRightName(inRightName
)
242 // @@@ make sure cfRight is non mutable and never used that way
244 if (CFGetTypeID(cfRight
) != CFDictionaryGetTypeID())
246 Syslog::alert("Invalid rights set");
247 MacOSError::throwMe(errAuthorizationInternal
);
252 string classTag
= Attribute::getString(cfRight
, kRuleClassID
, false, "");
254 if (classTag
.length())
256 if (classTag
== kAuthorizationRuleClassAllow
)
258 secdebug("authrule", "%s : rule allow", inRightName
.c_str());
261 else if (classTag
== kAuthorizationRuleClassDeny
)
263 secdebug("authrule", "%s : rule deny", inRightName
.c_str());
266 else if (classTag
== kAuthorizationRuleClassUser
)
269 mGroupName
= Attribute::getString(cfRight
, kUserGroupID
);
270 // grab other user-in-group attributes
271 mMaxCredentialAge
= Attribute::getDouble(cfRight
, kTimeoutID
, false, DBL_MAX
);
272 mShared
= Attribute::getBool(cfRight
, kSharedID
);
273 mAllowRoot
= Attribute::getBool(cfRight
, kAllowRootID
);
274 mSessionOwner
= Attribute::getBool(cfRight
, kSessionOwnerID
);
275 // authorization tags can have eval now too
276 mEvalDef
= Attribute::getVector(cfRight
, kMechanismsID
);
277 if (mEvalDef
.size() == 0 && cfRules
/*only rights default see appserver-admin*/)
279 CFDictionaryRef cfRuleDef
= reinterpret_cast<CFDictionaryRef
>(CFDictionaryGetValue(cfRules
, CFSTR("authenticate")));
280 if (cfRuleDef
&& CFGetTypeID(cfRuleDef
) == CFDictionaryGetTypeID())
281 mEvalDef
= Attribute::getVector(cfRuleDef
, kMechanismsID
);
283 mTries
= int(Attribute::getDouble(cfRight
, kTriesID
, false, double(kMaximumAuthorizationTries
)));
284 mAuthenticateUser
= Attribute::getBool(cfRight
, kRuleAuthenticateUserID
, false, true);
286 secdebug("authrule", "%s : rule user in group \"%s\" timeout %g%s%s",
288 mGroupName
.c_str(), mMaxCredentialAge
, mShared
? " shared" : "",
289 mAllowRoot
? " allow-root" : "");
292 else if (classTag
== kAuthorizationRuleClassMechanisms
)
294 secdebug("authrule", "%s : rule evaluate mechanisms", inRightName
.c_str());
295 mType
= kEvaluateMechanisms
;
296 // mechanisms to evaluate
297 mEvalDef
= Attribute::getVector(cfRight
, kMechanismsID
, true);
298 mTries
= int(Attribute::getDouble(cfRight
, kTriesID
, false, 0.0)); // "forever"
299 mShared
= Attribute::getBool(cfRight
, kSharedID
, false, true);
301 else if (classTag
== kAuthorizationRightRule
)
303 assert(cfRules
); // rules can't delegate to other rules
304 secdebug("authrule", "%s : rule delegate rule", inRightName
.c_str());
305 mType
= kRuleDelegation
;
308 string ruleDefString
= Attribute::getString(cfRight
, kRuleDelegateID
, false, "");
309 if (ruleDefString
.length())
311 CFStringRef ruleDefRef
= makeCFString(ruleDefString
);
312 CFDictionaryRef cfRuleDef
= reinterpret_cast<CFDictionaryRef
>(CFDictionaryGetValue(cfRules
, ruleDefRef
));
314 CFRelease(ruleDefRef
);
315 if (!cfRuleDef
|| CFGetTypeID(cfRuleDef
) != CFDictionaryGetTypeID())
317 Syslog::alert("'%s' does not name a built-in rule", ruleDefString
.c_str());
318 MacOSError::throwMe(errAuthorizationInternal
);
320 mRuleDef
.push_back(Rule(ruleDefString
, cfRuleDef
, cfRules
));
324 vector
<string
> ruleDef
= Attribute::getVector(cfRight
, kRuleDelegateID
, true);
325 for (vector
<string
>::const_iterator it
= ruleDef
.begin(); it
!= ruleDef
.end(); it
++)
327 CFStringRef ruleNameRef
= makeCFString(*it
);
328 CFDictionaryRef cfRuleDef
= reinterpret_cast<CFDictionaryRef
>(CFDictionaryGetValue(cfRules
, ruleNameRef
));
330 CFRelease(ruleNameRef
);
331 if (!cfRuleDef
|| (CFGetTypeID(cfRuleDef
) != CFDictionaryGetTypeID()))
333 Syslog::alert("Invalid rule '%s'in rule set", it
->c_str());
334 MacOSError::throwMe(errAuthorizationInternal
);
336 mRuleDef
.push_back(Rule(*it
, cfRuleDef
, cfRules
));
340 mKofN
= int(Attribute::getDouble(cfRight
, kKofNID
, false, 0.0));
347 secdebug("authrule", "%s : rule class '%s' unknown.", inRightName
.c_str(), classTag
.c_str());
348 Syslog::alert("%s : rule class '%s' unknown", inRightName
.c_str(), classTag
.c_str());
349 MacOSError::throwMe(errAuthorizationInternal
);
354 // no class tag means, this is the abbreviated specification from the API
355 // it _must_ have a definition for "rule" which will be used as a delegate
356 // it may have a comment (not extracted here)
357 // it may have a default prompt, or a whole dictionary of languages (not extracted here)
358 mType
= kRuleDelegation
;
359 string ruleName
= Attribute::getString(cfRight
, kRuleDelegateID
, true);
360 secdebug("authrule", "%s : rule delegate rule (1): %s", inRightName
.c_str(), ruleName
.c_str());
361 CFStringRef ruleNameRef
= makeCFString(ruleName
);
362 CFDictionaryRef cfRuleDef
= reinterpret_cast<CFDictionaryRef
>(CFDictionaryGetValue(cfRules
, ruleNameRef
));
364 CFRelease(ruleNameRef
);
365 if (!cfRuleDef
|| CFGetTypeID(cfRuleDef
) != CFDictionaryGetTypeID())
367 Syslog::alert("Rule '%s' for right '%s' does not exist or is not properly formed", ruleName
.c_str(), inRightName
.c_str());
368 MacOSError::throwMe(errAuthorizationInternal
);
370 mRuleDef
.push_back(Rule(ruleName
, cfRuleDef
, cfRules
));
373 Attribute::getLocalizedPrompts(cfRight
, mLocalizedPrompts
);
383 RuleImpl::setAgentHints(const AuthItemRef
&inRight
, const Rule
&inTopLevelRule
, AuthItemSet
&environmentToClient
, AuthorizationToken
&auth
) const
385 string
authorizeString(inRight
->name());
386 environmentToClient
.erase(AuthItemRef(AGENT_HINT_AUTHORIZE_RIGHT
));
387 environmentToClient
.insert(AuthItemRef(AGENT_HINT_AUTHORIZE_RIGHT
, AuthValueOverlay(authorizeString
)));
389 pid_t creatorPid
= auth
.creatorPid();
390 environmentToClient
.erase(AuthItemRef(AGENT_HINT_CREATOR_PID
));
391 environmentToClient
.insert(AuthItemRef(AGENT_HINT_CREATOR_PID
, AuthValueOverlay(sizeof(pid_t
), &creatorPid
)));
393 Process
&thisProcess
= Server::process();
395 if (SecStaticCodeRef clientCode
= auth
.creatorCode())
396 bundlePath
= codePath(clientCode
);
397 AuthItemSet processHints
= SecurityAgent::Client::clientHints(
398 SecurityAgent::bundle
, bundlePath
, thisProcess
.pid(), thisProcess
.uid());
399 environmentToClient
.erase(AuthItemRef(AGENT_HINT_CLIENT_TYPE
));
400 environmentToClient
.erase(AuthItemRef(AGENT_HINT_CLIENT_PATH
));
401 environmentToClient
.erase(AuthItemRef(AGENT_HINT_CLIENT_PID
));
402 environmentToClient
.erase(AuthItemRef(AGENT_HINT_CLIENT_UID
));
403 environmentToClient
.insert(processHints
.begin(), processHints
.end());
405 map
<string
,string
> defaultPrompts
= inTopLevelRule
->localizedPrompts();
407 if (defaultPrompts
.empty())
408 defaultPrompts
= localizedPrompts();
410 if (!defaultPrompts
.empty())
412 map
<string
,string
>::const_iterator it
;
413 for (it
= defaultPrompts
.begin(); it
!= defaultPrompts
.end(); it
++)
415 const string
&key
= it
->first
;
416 const string
&value
= it
->second
;
417 environmentToClient
.insert(AuthItemRef(key
.c_str(), AuthValueOverlay(value
)));
421 // add rulename as a hint
422 string ruleName
= name();
423 environmentToClient
.erase(AuthItemRef(AGENT_HINT_AUTHORIZE_RULE
));
424 environmentToClient
.insert(AuthItemRef(AGENT_HINT_AUTHORIZE_RULE
, AuthValueOverlay(ruleName
)));
427 // If a different evaluation for getting a credential is prescribed,
428 // we'll run that and validate the credentials from there.
429 // we fall back on a default configuration from the authenticate rule
431 RuleImpl::evaluateAuthentication(const AuthItemRef
&inRight
, const Rule
&inRule
,AuthItemSet
&environmentToClient
, AuthorizationFlags flags
, CFAbsoluteTime now
, const CredentialSet
*inCredentials
, CredentialSet
&credentials
, AuthorizationToken
&auth
, SecurityAgent::Reason
&reason
) const
433 OSStatus status
= errAuthorizationDenied
;
435 Credential hintCredential
;
436 if (errAuthorizationSuccess
== evaluateSessionOwner(inRight
, inRule
, environmentToClient
, now
, auth
, hintCredential
, reason
)) {
437 if (hintCredential
->username().length())
438 environmentToClient
.insert(AuthItemRef(AGENT_HINT_SUGGESTED_USER
, AuthValueOverlay(hintCredential
->username())));
439 if (hintCredential
->realname().length())
440 environmentToClient
.insert(AuthItemRef(AGENT_HINT_SUGGESTED_USER_LONG
, AuthValueOverlay(hintCredential
->realname())));
443 if ((mType
== kUser
) && (mGroupName
.length()))
444 environmentToClient
.insert(AuthItemRef(AGENT_HINT_REQUIRE_USER_IN_GROUP
, AuthValueOverlay(mGroupName
)));
447 reason
= SecurityAgent::noReason
;
449 Process
&cltProc
= Server::process();
450 // Authorization preserves creator's UID in setuid processes
451 // (which is nice, but cltUid ends up being unused except by the debug
452 // message -- AgentMechanismEvaluator ignores it)
453 uid_t cltUid
= (cltProc
.uid() != 0) ? cltProc
.uid() : auth
.creatorUid();
454 secdebug("AuthEvalMech", "Mechanism invocation by process %d (UID %d)", cltProc
.pid(), cltUid
);
456 // For auditing within AuthorizationMechEval, pass the right name.
457 size_t rightNameSize
= inRight
->name() ? strlen(inRight
->name()) : 0;
458 AuthorizationString rightName
= inRight
->name() ? inRight
->name() : "";
459 // @@@ AuthValueRef's ctor ought to take a const void *
460 AuthValueRef
rightValue(rightNameSize
, const_cast<char *>(rightName
));
461 AuthValueVector authValueVector
;
462 authValueVector
.push_back(rightValue
);
464 RightAuthenticationLogger
rightAuthLogger(auth
.creatorAuditToken(), AUE_ssauthint
);
465 rightAuthLogger
.setRight(rightName
);
467 AgentMechanismEvaluator
eval(cltUid
, auth
.session(), mEvalDef
);
469 for (tries
= 0; tries
< mTries
; tries
++)
471 AuthItemRef
retryHint(AGENT_HINT_RETRY_REASON
, AuthValueOverlay(sizeof(reason
), &reason
));
472 environmentToClient
.erase(retryHint
); environmentToClient
.insert(retryHint
); // replace
473 AuthItemRef
triesHint(AGENT_HINT_TRIES
, AuthValueOverlay(sizeof(tries
), &tries
));
474 environmentToClient
.erase(triesHint
); environmentToClient
.insert(triesHint
); // replace
476 status
= eval
.run(authValueVector
, environmentToClient
, auth
);
478 if ((status
== errAuthorizationSuccess
) ||
479 (status
== errAuthorizationCanceled
)) // @@@ can only pass back sideband through context
481 secdebug("AuthEvalMech", "storing new context for authorization");
482 auth
.setInfoSet(eval
.context());
485 // successfully ran mechanisms to obtain credential
486 if (status
== errAuthorizationSuccess
)
488 // deny is the default
489 status
= errAuthorizationDenied
;
491 CredentialSet newCredentials
= makeCredentials(auth
);
492 // clear context after extracting credentials
495 for (CredentialSet::const_iterator it
= newCredentials
.begin(); it
!= newCredentials
.end(); ++it
)
497 const Credential
& newCredential
= *it
;
499 // @@@ we log the uid a process was running under when it created the authref, which is misleading in the case of loginwindow
500 if (newCredential
->isValid()) {
501 Syslog::info("UID %u authenticated as user %s (UID %u) for right '%s'", auth
.creatorUid(), newCredential
->username().c_str(), newCredential
->uid(), rightName
);
502 rightAuthLogger
.logSuccess(auth
.creatorUid(), newCredential
->uid(), newCredential
->username().c_str());
504 // we can't be sure that the user actually exists so inhibit logging of uid
505 Syslog::error("UID %u failed to authenticate as user '%s' for right '%s'", auth
.creatorUid(), newCredential
->username().c_str(), rightName
);
506 rightAuthLogger
.logFailure(auth
.creatorUid(), newCredential
->username().c_str());
509 if (!newCredential
->isValid())
511 reason
= SecurityAgent::invalidPassphrase
;
515 // verify that this credential authorizes right
516 status
= evaluateUserCredentialForRight(auth
, inRight
, inRule
, environmentToClient
, now
, newCredential
, true, reason
);
518 if (status
== errAuthorizationSuccess
)
520 if (auth
.operatesAsLeastPrivileged()) {
521 Credential
rightCredential(rightName
, newCredential
->uid(), mShared
);
522 credentials
.erase(rightCredential
); credentials
.insert(rightCredential
);
524 credentials
.insert(Credential(rightName
, newCredential
->uid(), false));
526 // whack an equivalent credential, so it gets updated to a later achieved credential which must have been more stringent
527 credentials
.erase(newCredential
); credentials
.insert(newCredential
);
528 // just got a new credential - if it's shared also add a non-shared one that to stick in the authorizationref local cache
530 credentials
.insert(Credential(newCredential
->uid(), newCredential
->username(), newCredential
->realname(), newCredential
->groupname(), false));
533 // use valid credential to set context info
534 // XXX/cs keeping this for now, such that the uid is passed back
535 auth
.setCredentialInfo(newCredential
);
536 secdebug("SSevalMech", "added valid credential for user %s", newCredential
->username().c_str());
537 status
= errAuthorizationSuccess
;
542 if (status
== errAuthorizationSuccess
)
546 if ((status
== errAuthorizationCanceled
) || (status
== errAuthorizationInternal
))
551 else // last mechanism is now authentication - fail
552 if (status
== errAuthorizationDenied
)
553 reason
= SecurityAgent::invalidPassphrase
;
556 // If we fell out of the loop because of too many tries, notify user
559 reason
= SecurityAgent::tooManyTries
;
560 AuthItemRef
retryHint (AGENT_HINT_RETRY_REASON
, AuthValueOverlay(sizeof(reason
), &reason
));
561 environmentToClient
.erase(retryHint
); environmentToClient
.insert(retryHint
); // replace
562 AuthItemRef
triesHint(AGENT_HINT_TRIES
, AuthValueOverlay(sizeof(tries
), &tries
));
563 environmentToClient
.erase(triesHint
); environmentToClient
.insert(triesHint
); // replace
564 eval
.run(AuthValueVector(), environmentToClient
, auth
);
565 // XXX/cs is this still necessary?
568 rightAuthLogger
.logFailure(NULL
, CommonCriteria::errTooManyTries
);
574 // create externally verified credentials on the basis of
575 // mechanism-provided information
577 RuleImpl::makeCredentials(const AuthorizationToken
&auth
) const
579 // fetch context and construct a credential to be tested
580 const AuthItemSet
&context
= const_cast<AuthorizationToken
&>(auth
).infoSet();
581 CredentialSet newCredentials
;
584 AuthItemSet::const_iterator found
= find_if(context
.begin(), context
.end(), FindAuthItemByRightName(kAuthorizationEnvironmentUsername
) );
585 if (found
== context
.end())
587 string username
= (**found
).stringValue();
588 secdebug("AuthEvalMech", "found username");
590 const uid_t
*uid
= NULL
;
591 found
= find_if(context
.begin(), context
.end(), FindAuthItemByRightName("uid") );
592 if (found
!= context
.end())
594 uid
= static_cast<const uid_t
*>((**found
).value().data
);
595 secdebug("AuthEvalMech", "found uid");
598 if (username
.length() && uid
)
600 // credential is valid because mechanism says so
601 newCredentials
.insert(Credential(*uid
, username
, "", "", mShared
));
605 return newCredentials
;
608 // evaluate whether a good credential of the current session owner would authorize a right
610 RuleImpl::evaluateSessionOwner(const AuthItemRef
&inRight
, const Rule
&inRule
, const AuthItemSet
&environment
, const CFAbsoluteTime now
, const AuthorizationToken
&auth
, Credential
&credential
, SecurityAgent::Reason
&reason
) const
612 // username hint is taken from the user who created the authorization, unless it's clearly ineligible
613 // @@@ we have no access to current requester uid here and the process uid is only taken when the authorization is created
614 // meaning that a process like loginwindow that drops privs later is screwed.
617 Session
&session
= auth
.session();
618 Credential sessionCredential
;
619 if (session
.haveOriginatorUid()) {
620 // preflight session credential as if it were a fresh copy
621 const Credential
&cred
= session
.originatorCredential();
622 sessionCredential
= Credential(cred
->uid(), cred
->username(), cred
->realname(), cred
->groupname(), mShared
/*ignored*/);
624 uid
= auth
.creatorUid();
625 Server::active().longTermActivity();
626 struct passwd
*pw
= getpwuid(uid
);
628 // avoid hinting a locked account
629 if ( (pw
->pw_passwd
== NULL
) ||
630 strcmp(pw
->pw_passwd
, "*") ) {
631 // Check if username will authorize the request and set username to
632 // be used as a hint to the user if so
633 secdebug("AuthEvalMech", "preflight credential from current user, result follows:");
634 sessionCredential
= Credential(pw
->pw_uid
, pw
->pw_name
, pw
->pw_gecos
, "", mShared
/*ignored*/);
639 OSStatus status
= evaluateUserCredentialForRight(auth
, inRight
, inRule
, environment
, now
, sessionCredential
, true, reason
);
640 if (errAuthorizationSuccess
== status
)
641 credential
= sessionCredential
;
648 RuleImpl::evaluateCredentialForRight(const AuthorizationToken
&auth
, const AuthItemRef
&inRight
, const Rule
&inRule
, const AuthItemSet
&environment
, CFAbsoluteTime now
, const Credential
&credential
, bool ignoreShared
, SecurityAgent::Reason
&reason
) const
650 if (auth
.operatesAsLeastPrivileged()) {
651 if (credential
->isRight() && credential
->isValid() && (inRight
->name() == credential
->rightname()))
652 return errAuthorizationSuccess
;
655 // @@@ no proper SA::Reason
656 reason
= SecurityAgent::unknownReason
;
657 return errAuthorizationDenied
;
660 return evaluateUserCredentialForRight(auth
, inRight
, inRule
, environment
, now
, credential
, false, reason
);
663 // Return errAuthorizationSuccess if this rule allows access based on the specified credential,
664 // return errAuthorizationDenied otherwise.
666 RuleImpl::evaluateUserCredentialForRight(const AuthorizationToken
&auth
, const AuthItemRef
&inRight
, const Rule
&inRule
, const AuthItemSet
&environment
, CFAbsoluteTime now
, const Credential
&credential
, bool ignoreShared
, SecurityAgent::Reason
&reason
) const
668 assert(mType
== kUser
);
670 // Ideally we'd set the AGENT_HINT_RETRY_REASON hint in this method, but
671 // evaluateAuthentication() overwrites it before
672 // AgentMechanismEvaluator::run(). That's what led to passing "reason"
673 // everywhere, from RuleImpl::evaluate() on down.
675 // Get the username from the credential
676 const char *user
= credential
->username().c_str();
678 // If the credential is not valid or its age is more than the allowed maximum age
679 // for a credential, deny.
680 if (!credential
->isValid())
682 // @@@ it could be the username, not password, was invalid
683 reason
= SecurityAgent::invalidPassphrase
;
684 secdebug("autheval", "credential for user %s is invalid, denying right %s", user
, inRight
->name());
685 return errAuthorizationDenied
;
688 if (now
- credential
->creationTime() > mMaxCredentialAge
)
690 // @@@ no proper SA::Reason
691 reason
= SecurityAgent::unknownReason
;
692 secdebug("autheval", "credential for user %s has expired, denying right %s", user
, inRight
->name());
693 return errAuthorizationDenied
;
696 if (!ignoreShared
&& !mShared
&& credential
->isShared())
698 // @@@ no proper SA::Reason
699 reason
= SecurityAgent::unknownReason
;
700 secdebug("autheval", "shared credential for user %s cannot be used, denying right %s", user
, inRight
->name());
701 return errAuthorizationDenied
;
704 // A root (uid == 0) user can do anything
705 if (credential
->uid() == 0)
707 secdebug("autheval", "user %s has uid 0, granting right %s", user
, inRight
->name());
708 return errAuthorizationSuccess
;
713 Session
&session
= auth
.session();
714 if (session
.haveOriginatorUid())
716 uid_t console_user
= session
.originatorUid();
718 if (credential
->uid() == console_user
)
720 secdebug("autheval", "user %s is session-owner(uid: %d), granting right %s", user
, console_user
, inRight
->name());
721 return errAuthorizationSuccess
;
723 // set "reason" in this case? not that a proper SA::Reason exists
727 // @@@ no proper SA::Reason
728 reason
= SecurityAgent::unknownReason
;
729 secdebug("autheval", "session-owner check failed.");
733 if (mGroupName
.length())
735 const char *groupname
= mGroupName
.c_str();
736 Server::active().longTermActivity();
739 return errAuthorizationDenied
;
743 uuid_t group_uuid
, user_uuid
;
746 // @@@ it'd be nice to have SA::Reason codes for the failures
747 // associated with the pre-check-membership mbr_*() functions,
748 // but userNotInGroup will do
749 if (mbr_group_name_to_uuid(groupname
, group_uuid
))
752 if (mbr_uid_to_uuid(credential
->uid(), user_uuid
))
755 if (mbr_check_membership(user_uuid
, group_uuid
, &is_member
))
760 credential
->setGroupname(mGroupName
);
761 secdebug("autheval", "user %s is a member of group %s, granting right %s",
762 user
, groupname
, inRight
->name());
763 return errAuthorizationSuccess
;
769 reason
= SecurityAgent::userNotInGroup
;
770 secdebug("autheval", "user %s is not a member of group %s, denying right %s",
771 user
, groupname
, inRight
->name());
773 else if (mSessionOwner
) // rule asks only if user is the session owner
775 reason
= SecurityAgent::unacceptableUser
;
778 return errAuthorizationDenied
;
784 RuleImpl::evaluateUser(const AuthItemRef
&inRight
, const Rule
&inRule
, AuthItemSet
&environmentToClient
, AuthorizationFlags flags
, CFAbsoluteTime now
, const CredentialSet
*inCredentials
, CredentialSet
&credentials
, AuthorizationToken
&auth
, SecurityAgent::Reason
&reason
) const
786 // If we got here, this is a kUser type rule, let's start looking for a
787 // credential that is satisfactory
789 // Zeroth -- Here is an extra special saucy ugly hack to allow authorizations
790 // created by a proccess running as root to automatically get a right.
791 if (mAllowRoot
&& auth
.creatorUid() == 0)
793 SECURITYD_AUTH_USER_ALLOWROOT(&auth
);
795 secdebug("autheval", "creator of authorization has uid == 0 granting right %s",
797 return errAuthorizationSuccess
;
800 // if we're not supposed to authenticate evaluate the session-owner against the group
801 if (!mAuthenticateUser
)
803 Credential hintCredential
;
804 OSStatus status
= evaluateSessionOwner(inRight
, inRule
, environmentToClient
, now
, auth
, hintCredential
, reason
);
808 SECURITYD_AUTH_USER_ALLOWSESSIONOWNER(&auth
);
809 return errAuthorizationSuccess
;
812 return errAuthorizationDenied
;
815 // First -- go though the credentials we either already used or obtained during this authorize operation.
816 for (CredentialSet::const_iterator it
= credentials
.begin(); it
!= credentials
.end(); ++it
)
818 // Passed-in user credentials are allowed for least-privileged mode
819 if (auth
.operatesAsLeastPrivileged() && !(*it
)->isRight() && (*it
)->isValid())
821 OSStatus status
= evaluateUserCredentialForRight(auth
, inRight
, inRule
, environmentToClient
, now
, *it
, false, reason
);
822 if (errAuthorizationSuccess
== status
) {
823 Credential
rightCredential(inRight
->name(), (*it
)->uid(), mShared
);
824 credentials
.erase(rightCredential
); credentials
.insert(rightCredential
);
826 credentials
.insert(Credential(inRight
->name(), (*it
)->uid(), false));
831 // if this is least privileged, this will function differently: match credential to requested right
832 OSStatus status
= evaluateCredentialForRight(auth
, inRight
, inRule
, environmentToClient
, now
, *it
, false, reason
);
834 if (status
!= errAuthorizationDenied
) {
835 // add credential to authinfo
836 auth
.setCredentialInfo(*it
);
842 // Second -- go though the credentials passed in to this authorize operation by the state management layer.
845 for (CredentialSet::const_iterator it
= inCredentials
->begin(); it
!= inCredentials
->end(); ++it
)
847 // if this is least privileged, this will function differently: match credential to requested right
848 OSStatus status
= evaluateCredentialForRight(auth
, inRight
, inRule
, environmentToClient
, now
, *it
, false, reason
);
850 if (status
== errAuthorizationSuccess
)
852 // Add the credential we used to the output set.
853 // whack an equivalent credential, so it gets updated to a later achieved credential which must have been more stringent
854 credentials
.erase(*it
); credentials
.insert(*it
);
855 // add credential to authinfo
856 auth
.setCredentialInfo(*it
);
860 else if (status
!= errAuthorizationDenied
)
865 // Finally -- We didn't find the credential in our passed in credential lists. Obtain a new credential if our flags let us do so.
866 if (!(flags
& kAuthorizationFlagExtendRights
))
867 return errAuthorizationDenied
;
869 // authorizations that timeout immediately cannot be preauthorized
870 if ((flags
& kAuthorizationFlagPreAuthorize
) &&
871 (mMaxCredentialAge
== 0.0))
873 inRight
->setFlags(inRight
->flags() | kAuthorizationFlagCanNotPreAuthorize
);
874 return errAuthorizationSuccess
;
877 if (!(flags
& kAuthorizationFlagInteractionAllowed
))
878 return errAuthorizationInteractionNotAllowed
;
880 setAgentHints(inRight
, inRule
, environmentToClient
, auth
);
882 return evaluateAuthentication(inRight
, inRule
, environmentToClient
, flags
, now
, inCredentials
, credentials
, auth
, reason
);
886 RuleImpl::evaluateMechanismOnly(const AuthItemRef
&inRight
, const Rule
&inRule
, AuthItemSet
&environmentToClient
, AuthorizationToken
&auth
, CredentialSet
&outCredentials
) const
891 Process
&cltProc
= Server::process();
892 // Authorization preserves creator's UID in setuid processes
893 uid_t cltUid
= (cltProc
.uid() != 0) ? cltProc
.uid() : auth
.creatorUid();
894 secdebug("AuthEvalMech", "Mechanism invocation by process %d (UID %d)", cltProc
.pid(), cltUid
);
897 AgentMechanismEvaluator
eval(cltUid
, auth
.session(), mEvalDef
);
898 // For auditing within AuthorizationMechEval, pass the right name.
899 size_t rightNameSize
= inRight
->name() ? strlen(inRight
->name()) : 0;
900 AuthorizationString rightName
= inRight
->name() ? inRight
->name() : "";
901 // @@@ AuthValueRef's ctor ought to take a const void *
902 AuthValueRef
rightValue(rightNameSize
, const_cast<char *>(rightName
));
903 AuthValueVector authValueVector
;
904 authValueVector
.push_back(rightValue
);
908 setAgentHints(inRight
, inRule
, environmentToClient
, auth
);
909 AuthItemRef
triesHint(AGENT_HINT_TRIES
, AuthValueOverlay(sizeof(tries
), &tries
));
910 environmentToClient
.erase(triesHint
); environmentToClient
.insert(triesHint
); // replace
912 status
= eval
.run(authValueVector
, environmentToClient
, auth
);
913 if ((status
== errAuthorizationSuccess
) ||
914 (status
== errAuthorizationCanceled
)) // @@@ can only pass back sideband through context
916 secdebug("AuthEvalMech", "storing new context for authorization");
917 auth
.setInfoSet(eval
.context());
918 if (status
== errAuthorizationSuccess
)
920 // (try to) attach the authorizing UID to the least-priv cred
921 if (auth
.operatesAsLeastPrivileged())
923 RightAuthenticationLogger
logger(auth
.creatorAuditToken(), AUE_ssauthint
);
924 logger
.setRight(rightName
);
926 AuthItem
*uidItem
= eval
.context().find(AGENT_CONTEXT_UID
);
930 memcpy(&authorizedUid
, uidItem
->value().data
, sizeof(authorizedUid
));
931 secdebug("AuthEvalMech", "generating least-privilege cred for '%s' authorized by UID %u", inRight
->name(), authorizedUid
);
932 outCredentials
.insert(Credential(rightName
, authorizedUid
, mShared
));
933 logger
.logLeastPrivilege(authorizedUid
, true);
935 else // cltUid is better than nothing
937 secdebug("AuthEvalMech", "generating least-privilege cred for '%s' with process- or auth-UID %u", inRight
->name(), cltUid
);
938 outCredentials
.insert(Credential(rightName
, cltUid
, mShared
));
939 logger
.logLeastPrivilege(cltUid
, false);
943 outCredentials
= makeCredentials(auth
);
949 while ((status
== errAuthorizationDenied
) // only if we have an expected failure we continue
950 && ((mTries
== 0) // mTries == 0 means we try forever
951 || ((mTries
> 0) // mTries > 0 means we try up to mTries times
952 && (tries
< mTries
))));
955 // HACK kill all hosts to free pages for low memory systems
956 // (XXX/gh there should be a #define for this right)
957 if (name() == "system.login.done")
959 // one case where we don't want to mark the agents as "busy"
960 QueryInvokeMechanism
query(securityAgent
, auth
.session());
961 query
.terminateAgent();
962 QueryInvokeMechanism
query2(privilegedAuthHost
, auth
.session());
963 query2
.terminateAgent();
970 RuleImpl::evaluateRules(const AuthItemRef
&inRight
, const Rule
&inRule
, AuthItemSet
&environmentToClient
, AuthorizationFlags flags
, CFAbsoluteTime now
, const CredentialSet
*inCredentials
, CredentialSet
&credentials
, AuthorizationToken
&auth
, SecurityAgent::Reason
&reason
) const
972 // line up the rules to try
973 if (!mRuleDef
.size())
974 return errAuthorizationSuccess
;
977 OSStatus status
= errAuthorizationSuccess
;
978 vector
<Rule
>::const_iterator it
;
980 for (it
= mRuleDef
.begin();it
!= mRuleDef
.end(); it
++)
983 if ((mType
== kKofN
) && (count
== mKofN
))
984 return errAuthorizationSuccess
;
986 // get a rule and try it
987 status
= (*it
)->evaluate(inRight
, inRule
, environmentToClient
, flags
, now
, inCredentials
, credentials
, auth
, reason
);
989 // if status is cancel/internal error abort
990 if ((status
== errAuthorizationCanceled
) || (status
== errAuthorizationInternal
))
993 if (status
!= errAuthorizationSuccess
)
995 // continue if we're only looking for k of n
1005 return status
; // return the last failure
1010 RuleImpl::evaluate(const AuthItemRef
&inRight
, const Rule
&inRule
, AuthItemSet
&environmentToClient
, AuthorizationFlags flags
, CFAbsoluteTime now
, const CredentialSet
*inCredentials
, CredentialSet
&credentials
, AuthorizationToken
&auth
, SecurityAgent::Reason
&reason
) const
1015 SECURITYD_AUTH_ALLOW(&auth
, (char *)name().c_str());
1016 return errAuthorizationSuccess
;
1018 SECURITYD_AUTH_DENY(&auth
, (char *)name().c_str());
1019 return errAuthorizationDenied
;
1021 SECURITYD_AUTH_USER(&auth
, (char *)name().c_str());
1022 return evaluateUser(inRight
, inRule
, environmentToClient
, flags
, now
, inCredentials
, credentials
, auth
, reason
);
1023 case kRuleDelegation
:
1024 SECURITYD_AUTH_RULES(&auth
, (char *)name().c_str());
1025 return evaluateRules(inRight
, inRule
, environmentToClient
, flags
, now
, inCredentials
, credentials
, auth
, reason
);
1027 SECURITYD_AUTH_KOFN(&auth
, (char *)name().c_str());
1028 return evaluateRules(inRight
, inRule
, environmentToClient
, flags
, now
, inCredentials
, credentials
, auth
, reason
);
1029 case kEvaluateMechanisms
:
1030 SECURITYD_AUTH_MECHRULE(&auth
, (char *)name().c_str());
1031 // if we had a SecurityAgent::Reason code for "mechanism denied,"
1032 // it would make sense to pass down "reason"
1033 return evaluateMechanismOnly(inRight
, inRule
, environmentToClient
, auth
, credentials
);
1035 Syslog::alert("Unrecognized rule type %d", mType
);
1036 MacOSError::throwMe(errAuthorizationInternal
); // invalid rule
1040 Rule::Rule() : RefPointer
<RuleImpl
>(new RuleImpl()) {}
1041 Rule::Rule(const string
&inRightName
, CFDictionaryRef cfRight
, CFDictionaryRef cfRules
) : RefPointer
<RuleImpl
>(new RuleImpl(inRightName
, cfRight
, cfRules
)) {}
1045 } // end namespace Authorization