2 * Copyright (c) 2000-2015 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@
25 // passphrases - canonical code to obtain passphrases
27 #include "agentquery.h"
28 #include "ccaudit_extensions.h"
30 #include <Security/AuthorizationTags.h>
31 #include <Security/AuthorizationTagsPriv.h>
32 #include <Security/checkpw.h>
33 #include <Security/Security.h>
34 #include <System/sys/fileport.h>
35 #include <bsm/audit.h>
36 #include <bsm/audit_uevents.h> // AUE_ssauthint
37 #include <membership.h>
38 #include <membershipPriv.h>
39 #include <security_utilities/logging.h>
40 #include <security_utilities/mach++.h>
43 #include <xpc/private.h>
44 #include "securityd_service/securityd_service/securityd_service_client.h"
46 #define SECURITYAGENT_BOOTSTRAP_NAME_BASE "com.apple.security.agent"
47 #define SECURITYAGENT_LOGINWINDOW_BOOTSTRAP_NAME_BASE "com.apple.security.agent.login"
49 #define AUTH_XPC_ITEM_NAME "_item_name"
50 #define AUTH_XPC_ITEM_FLAGS "_item_flags"
51 #define AUTH_XPC_ITEM_VALUE "_item_value"
52 #define AUTH_XPC_ITEM_TYPE "_item_type"
54 #define AUTH_XPC_REQUEST_METHOD_KEY "_agent_request_key"
55 #define AUTH_XPC_REQUEST_METHOD_CREATE "_agent_request_create"
56 #define AUTH_XPC_REQUEST_METHOD_INVOKE "_agent_request_invoke"
57 #define AUTH_XPC_REQUEST_METHOD_DEACTIVATE "_agent_request_deactivate"
58 #define AUTH_XPC_REQUEST_METHOD_DESTROY "_agent_request_destroy"
59 #define AUTH_XPC_REPLY_METHOD_KEY "_agent_reply_key"
60 #define AUTH_XPC_REPLY_METHOD_RESULT "_agent_reply_result"
61 #define AUTH_XPC_REPLY_METHOD_INTERRUPT "_agent_reply_interrupt"
62 #define AUTH_XPC_REPLY_METHOD_CREATE "_agent_reply_create"
63 #define AUTH_XPC_REPLY_METHOD_DEACTIVATE "_agent_reply_deactivate"
64 #define AUTH_XPC_PLUGIN_NAME "_agent_plugin"
65 #define AUTH_XPC_MECHANISM_NAME "_agent_mechanism"
66 #define AUTH_XPC_HINTS_NAME "_agent_hints"
67 #define AUTH_XPC_CONTEXT_NAME "_agent_context"
68 #define AUTH_XPC_IMMUTABLE_HINTS_NAME "_agent_immutable_hints"
69 #define AUTH_XPC_REQUEST_INSTANCE "_agent_instance"
70 #define AUTH_XPC_REPLY_RESULT_VALUE "_agent_reply_result_value"
71 #define AUTH_XPC_AUDIT_SESSION_PORT "_agent_audit_session_port"
72 #define AUTH_XPC_BOOTSTRAP_PORT "_agent_bootstrap_port"
74 #define UUID_INITIALIZER_FROM_SESSIONID(sessionid) \
75 { 0,0,0,0, 0,0,0,0, 0,0,0,0, (unsigned char)((0xff000000 & (sessionid))>>24), (unsigned char)((0x00ff0000 & (sessionid))>>16), (unsigned char)((0x0000ff00 & (sessionid))>>8), (unsigned char)((0x000000ff & (sessionid))) }
78 // SecurityAgentXPCConnection
80 SecurityAgentXPCConnection::SecurityAgentXPCConnection(Session
&session
)
81 : mHostInstance(session
.authhost()),
83 mConnection(&Server::connection()),
84 mAuditToken(Server::connection().auditToken())
86 // this may take a while
87 Server::active().longTermActivity();
88 secnotice("SecurityAgentConnection", "new SecurityAgentConnection(%p)", this);
89 mXPCConnection
= NULL
;
91 struct passwd
*pw
= getpwnam("nobody");
93 mNobodyUID
= pw
->pw_uid
;
97 SecurityAgentXPCConnection::~SecurityAgentXPCConnection()
99 secnotice("SecurityAgentConnection", "SecurityAgentConnection(%p) dying", this);
100 mConnection
->useAgent(NULL
);
102 // If a connection has been established, we need to tear it down.
103 if (NULL
!= mXPCConnection
) {
104 // Tearing this down is a multi-step process. First, request a cancellation.
105 // This is safe even if the connection is already in the cancelled state.
106 xpc_connection_cancel(mXPCConnection
);
108 // Then release the XPC connection
109 xpc_release(mXPCConnection
);
110 mXPCConnection
= NULL
;
114 bool SecurityAgentXPCConnection::inDarkWake()
116 return mSession
.server().inDarkWake();
120 SecurityAgentXPCConnection::activate(bool ignoreUid
)
122 secnotice("SecurityAgentConnection", "activate(%p)", this);
124 mConnection
->useAgent(this);
125 if (mXPCConnection
!= NULL
) {
126 // If we already have an XPC connection, there's nothing to do.
131 uuid_t sessionUUID
= UUID_INITIALIZER_FROM_SESSIONID(mSession
.sessionId());
133 // Yes, these need to be throws, as we're still in securityd, and thus still have to do flow control with exceptions.
134 if (!(mSession
.attributes() & sessionHasGraphicAccess
))
135 CssmError::throwMe(CSSM_ERRCODE_NO_USER_INTERACTION
);
137 CssmError::throwMe(CSSM_ERRCODE_IN_DARK_WAKE
);
138 uid_t targetUid
= mHostInstance
->session().originatorUid();
140 secnotice("SecurityAgentXPCConnection","Retrieved UID %d for this session", targetUid
);
141 if (!ignoreUid
&& targetUid
!= 0 && targetUid
!= mNobodyUID
) {
142 mXPCConnection
= xpc_connection_create_mach_service(SECURITYAGENT_BOOTSTRAP_NAME_BASE
, NULL
, 0);
143 xpc_connection_set_target_uid(mXPCConnection
, targetUid
);
144 secnotice("SecurityAgentXPCConnection", "Creating a standard security agent");
146 mXPCConnection
= xpc_connection_create_mach_service(SECURITYAGENT_LOGINWINDOW_BOOTSTRAP_NAME_BASE
, NULL
, 0);
147 xpc_connection_set_instance(mXPCConnection
, sessionUUID
);
148 secnotice("SecurityAgentXPCConnection", "Creating a loginwindow security agent");
151 xpc_connection_set_event_handler(mXPCConnection
, ^(xpc_object_t object
) {
152 if (xpc_get_type(object
) == XPC_TYPE_ERROR
) {
153 secnotice("SecurityAgentXPCConnection", "error during xpc: %s", xpc_dictionary_get_string(object
, XPC_ERROR_KEY_DESCRIPTION
));
156 xpc_connection_resume(mXPCConnection
);
157 secnotice("SecurityAgentXPCConnection", "%p activated", this);
159 catch (MacOSError
&err
) {
160 mConnection
->useAgent(NULL
); // guess not
161 Syslog::error("SecurityAgentConnection: error activating SecurityAgent instance %p", this);
165 secnotice("SecurityAgentXPCConnection", "contact didn't throw (%p)", this);
169 SecurityAgentXPCConnection::terminate()
173 // @@@ This happens already in the destructor; presumably we do this to tear things down orderly
174 mConnection
->useAgent(NULL
);
178 using SecurityAgent::Reason
;
179 using namespace Authorization
;
181 ModuleNexus
<RecursiveMutex
> gAllXPCClientsMutex
;
182 ModuleNexus
<set
<SecurityAgentXPCQuery
*> > allXPCClients
;
185 SecurityAgentXPCQuery::killAllXPCClients()
187 // grab the lock for the client list -- we need to make sure no one modifies the structure while we are iterating it.
188 StLock
<Mutex
> _(gAllXPCClientsMutex());
190 set
<SecurityAgentXPCQuery
*>::iterator clientIterator
= allXPCClients().begin();
191 while (clientIterator
!= allXPCClients().end())
193 set
<SecurityAgentXPCQuery
*>::iterator thisClient
= clientIterator
++;
194 if ((*thisClient
)->getTerminateOnSleep())
196 (*thisClient
)->terminate();
202 SecurityAgentXPCQuery::SecurityAgentXPCQuery(Session
&session
)
203 : SecurityAgentXPCConnection(session
), mAgentConnected(false), mTerminateOnSleep(false)
205 secnotice("SecurityAgentXPCQuery", "new SecurityAgentXPCQuery(%p)", this);
208 SecurityAgentXPCQuery::~SecurityAgentXPCQuery()
210 secnotice("SecurityAgentXPCQuery", "SecurityAgentXPCQuery(%p) dying", this);
211 if (mAgentConnected
) {
217 SecurityAgentXPCQuery::inferHints(Process
&thisProcess
)
219 AuthItemSet clientHints
;
220 SecurityAgent::RequestorType type
= SecurityAgent::bundle
;
221 pid_t clientPid
= thisProcess
.pid();
222 uid_t clientUid
= thisProcess
.uid();
223 string guestPath
= thisProcess
.getPath();
225 clientHints
.insert(AuthItemRef(AGENT_HINT_CLIENT_TYPE
, AuthValueOverlay(sizeof(type
), &type
)));
226 clientHints
.insert(AuthItemRef(AGENT_HINT_CLIENT_PATH
, AuthValueOverlay(guestPath
)));
227 clientHints
.insert(AuthItemRef(AGENT_HINT_CLIENT_PID
, AuthValueOverlay(sizeof(clientPid
), &clientPid
)));
228 clientHints
.insert(AuthItemRef(AGENT_HINT_CLIENT_UID
, AuthValueOverlay(sizeof(clientUid
), &clientUid
)));
231 mClientHints
.insert(clientHints
.begin(), clientHints
.end());
233 bool validSignature
= thisProcess
.checkAppleSigned();
234 AuthItemSet clientImmutableHints
;
236 clientImmutableHints
.insert(AuthItemRef(AGENT_HINT_PROCESS_SIGNED
, AuthValueOverlay(sizeof(validSignature
), &validSignature
)));
238 mImmutableHints
.insert(clientImmutableHints
.begin(), clientImmutableHints
.end());
241 void SecurityAgentXPCQuery::addHint(const char *name
, const void *value
, UInt32 valueLen
, UInt32 flags
)
243 AuthorizationItem item
= { name
, valueLen
, const_cast<void *>(value
), flags
};
244 mClientHints
.insert(AuthItemRef(item
));
249 SecurityAgentXPCQuery::readChoice()
254 AuthItem
*allowAction
= mOutContext
.find(AGENT_CONTEXT_ALLOW
);
258 if (allowAction
->getString(allowString
)
259 && (allowString
== "YES"))
263 AuthItem
*rememberAction
= mOutContext
.find(AGENT_CONTEXT_REMEMBER_ACTION
);
266 string rememberString
;
267 if (rememberAction
->getString(rememberString
)
268 && (rememberString
== "YES"))
274 SecurityAgentXPCQuery::disconnect()
276 if (NULL
!= mXPCConnection
) {
277 xpc_object_t requestObject
= xpc_dictionary_create(NULL
, NULL
, 0);
278 xpc_dictionary_set_string(requestObject
, AUTH_XPC_REQUEST_METHOD_KEY
, AUTH_XPC_REQUEST_METHOD_DESTROY
);
279 xpc_connection_send_message(mXPCConnection
, requestObject
);
280 xpc_release(requestObject
);
283 StLock
<Mutex
> _(gAllXPCClientsMutex());
284 allXPCClients().erase(this);
288 SecurityAgentXPCQuery::terminate()
293 static void xpcArrayToAuthItemSet(AuthItemSet
*setToBuild
, xpc_object_t input
) {
296 xpc_array_apply(input
, ^bool(size_t index
, xpc_object_t item
) {
297 const char *name
= xpc_dictionary_get_string(item
, AUTH_XPC_ITEM_NAME
);
300 const void *data
= xpc_dictionary_get_data(item
, AUTH_XPC_ITEM_VALUE
, &length
);
301 void *dataCopy
= malloc(length
);
302 memcpy(dataCopy
, data
, length
);
304 uint64_t flags
= xpc_dictionary_get_uint64(item
, AUTH_XPC_ITEM_FLAGS
);
305 AuthItemRef
nextItem(name
, AuthValueOverlay((uint32_t)length
, dataCopy
), (uint32_t)flags
);
306 setToBuild
->insert(nextItem
);
307 memset(dataCopy
, 0, length
); // The authorization items contain things like passwords, so wiping clean is important.
314 SecurityAgentXPCQuery::create(const char *pluginId
, const char *mechanismId
)
316 bool ignoreUid
= false;
321 mAgentConnected
= false;
323 xpc_object_t requestObject
= xpc_dictionary_create(NULL
, NULL
, 0);
324 xpc_dictionary_set_string(requestObject
, AUTH_XPC_REQUEST_METHOD_KEY
, AUTH_XPC_REQUEST_METHOD_CREATE
);
325 xpc_dictionary_set_string(requestObject
, AUTH_XPC_PLUGIN_NAME
, pluginId
);
326 xpc_dictionary_set_string(requestObject
, AUTH_XPC_MECHANISM_NAME
, mechanismId
);
328 uid_t targetUid
= Server::process().uid();
329 bool doSwitchAudit
= (ignoreUid
|| targetUid
== 0 || targetUid
== mNobodyUID
);
330 bool doSwitchBootstrap
= (ignoreUid
|| targetUid
== 0 || targetUid
== mNobodyUID
);
333 mach_port_name_t jobPort
;
334 if (0 == audit_session_port(mSession
.sessionId(), &jobPort
)) {
335 secnotice("SecurityAgentXPCQuery", "attaching an audit session port because the uid was %d", targetUid
);
336 xpc_dictionary_set_mach_send(requestObject
, AUTH_XPC_AUDIT_SESSION_PORT
, jobPort
);
337 if (mach_port_mod_refs(mach_task_self(), jobPort
, MACH_PORT_RIGHT_SEND
, -1) != KERN_SUCCESS
) {
338 secnotice("SecurityAgentXPCQuery", "unable to release send right for audit session, leaking");
343 if (doSwitchBootstrap
) {
344 secnotice("SecurityAgentXPCQuery", "attaching a bootstrap port because the uid was %d", targetUid
);
345 MachPlusPlus::Bootstrap processBootstrap
= Server::process().taskPort().bootstrap();
346 xpc_dictionary_set_mach_send(requestObject
, AUTH_XPC_BOOTSTRAP_PORT
, processBootstrap
);
349 xpc_object_t object
= xpc_connection_send_message_with_reply_sync(mXPCConnection
, requestObject
);
350 if (xpc_get_type(object
) == XPC_TYPE_DICTIONARY
) {
351 const char *replyType
= xpc_dictionary_get_string(object
, AUTH_XPC_REPLY_METHOD_KEY
);
352 if (0 == strcmp(replyType
, AUTH_XPC_REPLY_METHOD_CREATE
)) {
353 uint64_t status
= xpc_dictionary_get_uint64(object
, AUTH_XPC_REPLY_RESULT_VALUE
);
354 if (status
== kAuthorizationResultAllow
) {
355 mAgentConnected
= true;
357 secnotice("SecurityAgentXPCQuery", "plugin create failed in SecurityAgent");
358 MacOSError::throwMe(errAuthorizationInternal
);
361 } else if (xpc_get_type(object
) == XPC_TYPE_ERROR
) {
362 if (XPC_ERROR_CONNECTION_INVALID
== object
) {
363 // If we get an error before getting the create response, try again without the UID
365 secnotice("SecurityAgentXPCQuery", "failed to establish connection, no retries left");
367 MacOSError::throwMe(errAuthorizationInternal
);
369 secnotice("SecurityAgentXPCQuery", "failed to establish connection, retrying with no UID");
371 xpc_release(mXPCConnection
);
372 mXPCConnection
= NULL
;
374 } else if (XPC_ERROR_CONNECTION_INTERRUPTED
== object
) {
375 // If we get an error before getting the create response, try again
379 xpc_release(requestObject
);
380 } while (!mAgentConnected
);
382 StLock
<Mutex
> _(gAllXPCClientsMutex());
383 allXPCClients().insert(this);
386 static xpc_object_t
authItemSetToXPCArray(AuthItemSet input
) {
387 xpc_object_t outputArray
= xpc_array_create(NULL
, 0);
388 for (AuthItemSet::iterator i
= input
.begin(); i
!= input
.end(); i
++) {
389 AuthItemRef item
= *i
;
391 xpc_object_t xpc_data
= xpc_dictionary_create(NULL
, NULL
, 0);
392 xpc_dictionary_set_string(xpc_data
, AUTH_XPC_ITEM_NAME
, item
->name());
393 AuthorizationValue value
= item
->value();
394 if (value
.data
!= NULL
) {
395 xpc_dictionary_set_data(xpc_data
, AUTH_XPC_ITEM_VALUE
, value
.data
, value
.length
);
397 xpc_dictionary_set_uint64(xpc_data
, AUTH_XPC_ITEM_FLAGS
, item
->flags());
398 xpc_array_append_value(outputArray
, xpc_data
);
399 xpc_release(xpc_data
);
405 SecurityAgentXPCQuery::invoke() {
406 __block OSStatus status
= kAuthorizationResultUndefined
;
408 xpc_object_t hintsArray
= authItemSetToXPCArray(mInHints
);
409 xpc_object_t contextArray
= authItemSetToXPCArray(mInContext
);
410 xpc_object_t immutableHintsArray
= authItemSetToXPCArray(mImmutableHints
);
412 xpc_object_t requestObject
= xpc_dictionary_create(NULL
, NULL
, 0);
413 xpc_dictionary_set_string(requestObject
, AUTH_XPC_REQUEST_METHOD_KEY
, AUTH_XPC_REQUEST_METHOD_INVOKE
);
414 xpc_dictionary_set_value(requestObject
, AUTH_XPC_HINTS_NAME
, hintsArray
);
415 xpc_dictionary_set_value(requestObject
, AUTH_XPC_CONTEXT_NAME
, contextArray
);
416 xpc_dictionary_set_value(requestObject
, AUTH_XPC_IMMUTABLE_HINTS_NAME
, immutableHintsArray
);
418 xpc_object_t object
= xpc_connection_send_message_with_reply_sync(mXPCConnection
, requestObject
);
419 if (xpc_get_type(object
) == XPC_TYPE_DICTIONARY
) {
420 const char *replyType
= xpc_dictionary_get_string(object
, AUTH_XPC_REPLY_METHOD_KEY
);
421 if (0 == strcmp(replyType
, AUTH_XPC_REPLY_METHOD_RESULT
)) {
422 xpc_object_t xpcHints
= xpc_dictionary_get_value(object
, AUTH_XPC_HINTS_NAME
);
423 xpc_object_t xpcContext
= xpc_dictionary_get_value(object
, AUTH_XPC_CONTEXT_NAME
);
424 AuthItemSet tempHints
, tempContext
;
425 xpcArrayToAuthItemSet(&tempHints
, xpcHints
);
426 xpcArrayToAuthItemSet(&tempContext
, xpcContext
);
427 mOutHints
= tempHints
;
428 mOutContext
= tempContext
;
429 mLastResult
= xpc_dictionary_get_uint64(object
, AUTH_XPC_REPLY_RESULT_VALUE
);
431 } else if (xpc_get_type(object
) == XPC_TYPE_ERROR
) {
432 if (XPC_ERROR_CONNECTION_INVALID
== object
) {
433 // If the connection drops, return an "auth undefined" result, because we cannot continue
434 } else if (XPC_ERROR_CONNECTION_INTERRUPTED
== object
) {
435 // If the agent dies, return an "auth undefined" result, because we cannot continue
440 xpc_release(hintsArray
);
441 xpc_release(contextArray
);
442 xpc_release(immutableHintsArray
);
443 xpc_release(requestObject
);
448 void SecurityAgentXPCQuery::checkResult()
450 // now check the OSStatus return from the server side
451 switch (mLastResult
) {
452 case kAuthorizationResultAllow
: return;
453 case kAuthorizationResultDeny
:
454 case kAuthorizationResultUserCanceled
: CssmError::throwMe(CSSM_ERRCODE_USER_CANCELED
);
455 default: MacOSError::throwMe(errAuthorizationInternal
);
460 // Perform the "rogue app" access query dialog
462 QueryKeychainUse::QueryKeychainUse(bool needPass
, const Database
*db
)
463 : mPassphraseCheck(NULL
)
465 // if passphrase checking requested, save KeychainDatabase reference
466 // (will quietly disable check if db isn't a keychain)
468 mPassphraseCheck
= dynamic_cast<const KeychainDatabase
*>(db
);
470 setTerminateOnSleep(true);
473 Reason
QueryKeychainUse::queryUser (const char *database
, const char *description
, AclAuthorization action
)
475 Reason reason
= SecurityAgent::noReason
;
478 AuthItemSet hints
, context
;
480 // prepopulate with client hints
481 hints
.insert(mClientHints
.begin(), mClientHints
.end());
483 // put action/operation (sint32) into hints
484 hints
.insert(AuthItemRef(AGENT_HINT_ACL_TAG
, AuthValueOverlay(sizeof(action
), static_cast<sint32
*>(&action
))));
486 // item name into hints
488 hints
.insert(AuthItemRef(AGENT_HINT_KEYCHAIN_ITEM_NAME
, AuthValueOverlay(description
? (uint32_t)strlen(description
) : 0, const_cast<char*>(description
))));
490 // keychain name into hints
491 hints
.insert(AuthItemRef(AGENT_HINT_KEYCHAIN_PATH
, AuthValueOverlay(database
? (uint32_t)strlen(database
) : 0, const_cast<char*>(database
))));
493 if (mPassphraseCheck
)
495 create("builtin", "confirm-access-password");
497 CssmAutoData
data(Allocator::standard(Allocator::sensitive
));
502 AuthItemRef
triesHint(AGENT_HINT_TRIES
, AuthValueOverlay(sizeof(retryCount
), &retryCount
));
503 hints
.erase(triesHint
); hints
.insert(triesHint
); // replace
505 if (retryCount
++ > kMaximumAuthorizationTries
)
507 reason
= SecurityAgent::tooManyTries
;
510 AuthItemRef
retryHint(AGENT_HINT_RETRY_REASON
, AuthValueOverlay(sizeof(reason
), &reason
));
511 hints
.erase(retryHint
); hints
.insert(retryHint
); // replace
513 setInput(hints
, context
);
516 if (retryCount
> kMaximumAuthorizationTries
)
523 AuthItem
*passwordItem
= mOutContext
.find(kAuthorizationEnvironmentPassword
);
527 passwordItem
->getCssmData(data
);
529 while ((reason
= (const_cast<KeychainDatabase
*>(mPassphraseCheck
)->decode(data
) ? SecurityAgent::noReason
: SecurityAgent::invalidPassphrase
)));
533 create("builtin", "confirm-access");
534 setInput(hints
, context
);
545 // Obtain passphrases and submit them to the accept() method until it is accepted
546 // or we can't get another passphrase. Accept() should consume the passphrase
547 // if it is accepted. If no passphrase is acceptable, throw out of here.
549 Reason
QueryOld::query()
551 Reason reason
= SecurityAgent::noReason
;
553 AuthItemSet hints
, context
;
554 CssmAutoData
passphrase(Allocator::standard(Allocator::sensitive
));
557 // prepopulate with client hints
559 const char *keychainPath
= database
.dbName();
560 hints
.insert(AuthItemRef(AGENT_HINT_KEYCHAIN_PATH
, AuthValueOverlay((uint32_t)strlen(keychainPath
), const_cast<char*>(keychainPath
))));
562 hints
.insert(mClientHints
.begin(), mClientHints
.end());
564 create("builtin", "unlock-keychain");
568 AuthItemRef
triesHint(AGENT_HINT_TRIES
, AuthValueOverlay(sizeof(retryCount
), &retryCount
));
569 hints
.erase(triesHint
); hints
.insert(triesHint
); // replace
573 if (retryCount
> maxTries
)
575 reason
= SecurityAgent::tooManyTries
;
578 AuthItemRef
retryHint(AGENT_HINT_RETRY_REASON
, AuthValueOverlay(sizeof(reason
), &reason
));
579 hints
.erase(retryHint
); hints
.insert(retryHint
); // replace
581 setInput(hints
, context
);
584 if (retryCount
> maxTries
)
591 AuthItem
*passwordItem
= mOutContext
.find(kAuthorizationEnvironmentPassword
);
595 passwordItem
->getCssmData(passphrase
);
598 while ((reason
= accept(passphrase
)));
600 return SecurityAgent::noReason
;
605 // Get existing passphrase (unlock) Query
607 Reason
QueryOld::operator () ()
614 // End-classes for old secrets
616 Reason
QueryUnlock::accept(CssmManagedData
&passphrase
)
618 if (safer_cast
<KeychainDatabase
&>(database
).decode(passphrase
))
619 return SecurityAgent::noReason
;
621 return SecurityAgent::invalidPassphrase
;
624 Reason
QueryUnlock::retrievePassword(CssmOwnedData
&passphrase
) {
625 CssmAutoData
pass(Allocator::standard(Allocator::sensitive
));
627 AuthItem
*passwordItem
= mOutContext
.find(kAuthorizationEnvironmentPassword
);
629 return SecurityAgent::invalidPassphrase
;
631 passwordItem
->getCssmData(pass
);
635 return SecurityAgent::noReason
;
638 QueryKeybagPassphrase::QueryKeybagPassphrase(Session
& session
, int32_t tries
) : mSession(session
), mContext(), mRetries(tries
)
640 setTerminateOnSleep(true);
641 mContext
= mSession
.get_current_service_context();
644 Reason
QueryKeybagPassphrase::query()
646 Reason reason
= SecurityAgent::noReason
;
648 AuthItemSet hints
, context
;
649 CssmAutoData
passphrase(Allocator::standard(Allocator::sensitive
));
652 // prepopulate with client hints
654 const char *keychainPath
= "iCloud";
655 hints
.insert(AuthItemRef(AGENT_HINT_KEYCHAIN_PATH
, AuthValueOverlay((uint32_t)strlen(keychainPath
), const_cast<char*>(keychainPath
))));
657 hints
.insert(mClientHints
.begin(), mClientHints
.end());
659 create("builtin", "unlock-keychain");
664 currentTry
= retryCount
;
665 if (retryCount
> mRetries
)
667 return SecurityAgent::tooManyTries
;
671 AuthItemRef
triesHint(AGENT_HINT_TRIES
, AuthValueOverlay(sizeof(currentTry
), ¤tTry
));
672 hints
.erase(triesHint
); hints
.insert(triesHint
); // replace
674 AuthItemRef
retryHint(AGENT_HINT_RETRY_REASON
, AuthValueOverlay(sizeof(reason
), &reason
));
675 hints
.erase(retryHint
); hints
.insert(retryHint
); // replace
677 setInput(hints
, context
);
682 AuthItem
*passwordItem
= mOutContext
.find(kAuthorizationEnvironmentPassword
);
686 passwordItem
->getCssmData(passphrase
);
688 while ((reason
= accept(passphrase
)));
690 return SecurityAgent::noReason
;
693 Reason
QueryKeybagPassphrase::accept(Security::CssmManagedData
& password
)
695 if (service_client_kb_unlock(&mContext
, password
.data(), (int)password
.length()) == 0) {
696 mSession
.keybagSetState(session_keybag_unlocked
);
697 return SecurityAgent::noReason
;
699 return SecurityAgent::invalidPassphrase
;
702 QueryKeybagNewPassphrase::QueryKeybagNewPassphrase(Session
& session
) : QueryKeybagPassphrase(session
) {}
704 Reason
QueryKeybagNewPassphrase::query(CssmOwnedData
&oldPassphrase
, CssmOwnedData
&passphrase
)
706 CssmAutoData
pass(Allocator::standard(Allocator::sensitive
));
707 CssmAutoData
oldPass(Allocator::standard(Allocator::sensitive
));
708 Reason reason
= SecurityAgent::noReason
;
710 AuthItemSet hints
, context
;
713 // prepopulate with client hints
715 const char *keychainPath
= "iCloud";
716 hints
.insert(AuthItemRef(AGENT_HINT_KEYCHAIN_PATH
, AuthValueOverlay((uint32_t)strlen(keychainPath
), const_cast<char*>(keychainPath
))));
718 const char *showResetString
= "YES";
719 hints
.insert(AuthItemRef(AGENT_HINT_SHOW_RESET
, AuthValueOverlay((uint32_t)strlen(showResetString
), const_cast<char*>(showResetString
))));
721 hints
.insert(mClientHints
.begin(), mClientHints
.end());
723 create("builtin", "change-passphrase");
726 AuthItem
*resetPassword
= NULL
;
729 currentTry
= retryCount
;
730 if (retryCount
> mRetries
)
732 return SecurityAgent::tooManyTries
;
736 AuthItemRef
triesHint(AGENT_HINT_TRIES
, AuthValueOverlay(sizeof(currentTry
), ¤tTry
));
737 hints
.erase(triesHint
); hints
.insert(triesHint
); // replace
739 AuthItemRef
retryHint(AGENT_HINT_RETRY_REASON
, AuthValueOverlay(sizeof(reason
), &reason
));
740 hints
.erase(retryHint
); hints
.insert(retryHint
); // replace
742 setInput(hints
, context
);
747 resetPassword
= mOutContext
.find(AGENT_CONTEXT_RESET_PASSWORD
);
748 if (resetPassword
!= NULL
) {
749 return SecurityAgent::resettingPassword
;
752 AuthItem
*oldPasswordItem
= mOutContext
.find(AGENT_PASSWORD
);
753 if (!oldPasswordItem
)
756 oldPasswordItem
->getCssmData(oldPass
);
758 while ((reason
= accept(oldPass
)));
760 if (reason
== SecurityAgent::noReason
) {
761 AuthItem
*passwordItem
= mOutContext
.find(AGENT_CONTEXT_NEW_PASSWORD
);
763 return SecurityAgent::invalidPassphrase
;
765 passwordItem
->getCssmData(pass
);
767 oldPassphrase
= oldPass
;
771 return SecurityAgent::noReason
;
774 QueryPIN::QueryPIN(Database
&db
)
775 : QueryOld(db
), mPin(Allocator::standard())
777 this->inferHints(Server::process());
781 Reason
QueryPIN::accept(CssmManagedData
&pin
)
783 // no retries for now
785 return SecurityAgent::noReason
;
790 // Obtain passphrases and submit them to the accept() method until it is accepted
791 // or we can't get another passphrase. Accept() should consume the passphrase
792 // if it is accepted. If no passphrase is acceptable, throw out of here.
794 Reason
QueryNewPassphrase::query()
796 Reason reason
= initialReason
;
797 CssmAutoData
passphrase(Allocator::standard(Allocator::sensitive
));
798 CssmAutoData
oldPassphrase(Allocator::standard(Allocator::sensitive
));
801 AuthItemSet hints
, context
;
805 // prepopulate with client hints
806 hints
.insert(mClientHints
.begin(), mClientHints
.end());
808 // keychain name into hints
809 hints
.insert(AuthItemRef(AGENT_HINT_KEYCHAIN_PATH
, AuthValueOverlay(database
.dbName())));
811 switch (initialReason
)
813 case SecurityAgent::newDatabase
:
814 create("builtin", "new-passphrase");
816 case SecurityAgent::changePassphrase
:
817 create("builtin", "change-passphrase");
825 AuthItemRef
triesHint(AGENT_HINT_TRIES
, AuthValueOverlay(sizeof(retryCount
), &retryCount
));
826 hints
.erase(triesHint
); hints
.insert(triesHint
); // replace
828 if (++retryCount
> maxTries
)
830 reason
= SecurityAgent::tooManyTries
;
833 AuthItemRef
retryHint(AGENT_HINT_RETRY_REASON
, AuthValueOverlay(sizeof(reason
), &reason
));
834 hints
.erase(retryHint
); hints
.insert(retryHint
); // replace
836 setInput(hints
, context
);
839 if (retryCount
> maxTries
)
846 if (SecurityAgent::changePassphrase
== initialReason
)
848 AuthItem
*oldPasswordItem
= mOutContext
.find(AGENT_PASSWORD
);
849 if (!oldPasswordItem
)
852 oldPasswordItem
->getCssmData(oldPassphrase
);
855 AuthItem
*passwordItem
= mOutContext
.find(AGENT_CONTEXT_NEW_PASSWORD
);
859 passwordItem
->getCssmData(passphrase
);
862 while ((reason
= accept(passphrase
, (initialReason
== SecurityAgent::changePassphrase
) ? &oldPassphrase
.get() : NULL
)));
864 return SecurityAgent::noReason
;
869 // Get new passphrase Query
871 Reason
QueryNewPassphrase::operator () (CssmOwnedData
&oldPassphrase
, CssmOwnedData
&passphrase
)
873 if (Reason result
= query())
874 return result
; // failed
875 passphrase
= mPassphrase
;
876 oldPassphrase
= mOldPassphrase
;
877 return SecurityAgent::noReason
; // success
880 Reason
QueryNewPassphrase::accept(CssmManagedData
&passphrase
, CssmData
*oldPassphrase
)
882 //@@@ acceptance criteria are currently hardwired here
883 //@@@ This validation presumes ASCII - UTF8 might be more lenient
885 // if we have an old passphrase, check it
886 if (oldPassphrase
&& !safer_cast
<KeychainDatabase
&>(database
).validatePassphrase(*oldPassphrase
))
887 return SecurityAgent::oldPassphraseWrong
;
889 // sanity check the new passphrase (but allow user override)
890 if (!(mPassphraseValid
&& passphrase
.get() == mPassphrase
)) {
891 mPassphrase
= passphrase
;
892 if (oldPassphrase
) mOldPassphrase
= *oldPassphrase
;
893 mPassphraseValid
= true;
894 if (mPassphrase
.length() == 0)
895 return SecurityAgent::passphraseIsNull
;
896 if (mPassphrase
.length() < 6)
897 return SecurityAgent::passphraseTooSimple
;
901 return SecurityAgent::noReason
;
905 // Get a passphrase for unspecified use
907 Reason
QueryGenericPassphrase::operator () (const CssmData
*prompt
, bool verify
,
910 return query(prompt
, verify
, passphrase
);
913 Reason
QueryGenericPassphrase::query(const CssmData
*prompt
, bool verify
,
916 Reason reason
= SecurityAgent::noReason
;
917 OSStatus status
; // not really used; remove?
918 AuthItemSet hints
, context
;
920 hints
.insert(mClientHints
.begin(), mClientHints
.end());
921 hints
.insert(AuthItemRef(AGENT_HINT_CUSTOM_PROMPT
, AuthValueOverlay(prompt
? (UInt32
)prompt
->length() : 0, prompt
? prompt
->data() : NULL
)));
922 // XXX/gh defined by dmitch but no analogous hint in
923 // AuthorizationTagsPriv.h:
924 // CSSM_ATTRIBUTE_ALERT_TITLE (optional alert panel title)
926 if (false == verify
) { // import
927 create("builtin", "generic-unlock");
928 } else { // verify passphrase (export)
929 create("builtin", "generic-new-passphrase");
932 AuthItem
*passwordItem
;
935 setInput(hints
, context
);
938 passwordItem
= mOutContext
.find(AGENT_PASSWORD
);
940 } while (!passwordItem
);
942 passwordItem
->getString(passphrase
);
949 // Get a DB blob's passphrase--keychain synchronization
951 Reason
QueryDBBlobSecret::operator () (DbHandle
*dbHandleArray
, uint8 dbHandleArrayCount
, DbHandle
*dbHandleAuthenticated
)
953 return query(dbHandleArray
, dbHandleArrayCount
, dbHandleAuthenticated
);
956 Reason
QueryDBBlobSecret::query(DbHandle
*dbHandleArray
, uint8 dbHandleArrayCount
, DbHandle
*dbHandleAuthenticated
)
958 Reason reason
= SecurityAgent::noReason
;
959 CssmAutoData
passphrase(Allocator::standard(Allocator::sensitive
));
960 OSStatus status
; // not really used; remove?
961 AuthItemSet hints
/*NUKEME*/, context
;
963 hints
.insert(mClientHints
.begin(), mClientHints
.end());
964 create("builtin", "generic-unlock-kcblob");
966 AuthItem
*secretItem
;
971 AuthItemRef
triesHint(AGENT_HINT_TRIES
, AuthValueOverlay(sizeof(retryCount
), &retryCount
));
972 hints
.erase(triesHint
); hints
.insert(triesHint
); // replace
974 if (++retryCount
> maxTries
)
976 reason
= SecurityAgent::tooManyTries
;
979 AuthItemRef
retryHint(AGENT_HINT_RETRY_REASON
, AuthValueOverlay(sizeof(reason
), &reason
));
980 hints
.erase(retryHint
); hints
.insert(retryHint
); // replace
982 setInput(hints
, context
);
985 secretItem
= mOutContext
.find(AGENT_PASSWORD
);
988 secretItem
->getCssmData(passphrase
);
990 } while ((reason
= accept(passphrase
, dbHandleArray
, dbHandleArrayCount
, dbHandleAuthenticated
)));
995 Reason
QueryDBBlobSecret::accept(CssmManagedData
&passphrase
,
996 DbHandle
*dbHandlesToAuthenticate
, uint8 dbHandleCount
, DbHandle
*dbHandleAuthenticated
)
998 DbHandle
*currHdl
= dbHandlesToAuthenticate
;
1000 Boolean authenticated
= false;
1001 for (index
=0; index
< dbHandleCount
&& !authenticated
; index
++)
1005 RefPointer
<KeychainDatabase
> dbToUnlock
= Server::keychain(*currHdl
);
1006 dbToUnlock
->unlockDb(passphrase
, false);
1007 authenticated
= true;
1008 *dbHandleAuthenticated
= *currHdl
; // return the DbHandle that 'passphrase' authenticated with.
1010 catch (const CommonError
&err
)
1012 currHdl
++; // we failed to authenticate with this one, onto the next one.
1015 if ( !authenticated
)
1016 return SecurityAgent::invalidPassphrase
;
1018 return SecurityAgent::noReason
;
1021 // @@@ no pluggable authentication possible!
1023 QueryKeychainAuth::operator () (const char *database
, const char *description
, AclAuthorization action
, const char *prompt
)
1025 Reason reason
= SecurityAgent::noReason
;
1026 AuthItemSet hints
, context
;
1031 using CommonCriteria::Securityd::KeychainAuthLogger
;
1032 KeychainAuthLogger
logger(mAuditToken
, AUE_ssauthint
, database
, description
);
1034 hints
.insert(mClientHints
.begin(), mClientHints
.end());
1036 // put action/operation (sint32) into hints
1037 hints
.insert(AuthItemRef(AGENT_HINT_ACL_TAG
, AuthValueOverlay(sizeof(action
), static_cast<sint32
*>(&action
))));
1039 hints
.insert(AuthItemRef(AGENT_HINT_CUSTOM_PROMPT
, AuthValueOverlay(prompt
? (uint32_t)strlen(prompt
) : 0, const_cast<char*>(prompt
))));
1041 // item name into hints
1042 hints
.insert(AuthItemRef(AGENT_HINT_KEYCHAIN_ITEM_NAME
, AuthValueOverlay(description
? (uint32_t)strlen(description
) : 0, const_cast<char*>(description
))));
1044 // keychain name into hints
1045 hints
.insert(AuthItemRef(AGENT_HINT_KEYCHAIN_PATH
, AuthValueOverlay(database
? (uint32_t)strlen(database
) : 0, const_cast<char*>(database
))));
1047 create("builtin", "confirm-access-user-password");
1049 AuthItem
*usernameItem
;
1050 AuthItem
*passwordItem
;
1054 AuthItemRef
triesHint(AGENT_HINT_TRIES
, AuthValueOverlay(sizeof(retryCount
), &retryCount
));
1055 hints
.erase(triesHint
); hints
.insert(triesHint
); // replace
1057 if (++retryCount
> maxTries
)
1058 reason
= SecurityAgent::tooManyTries
;
1060 if (SecurityAgent::noReason
!= reason
)
1062 if (SecurityAgent::tooManyTries
== reason
)
1063 logger
.logFailure(NULL
, CommonCriteria::errTooManyTries
);
1065 logger
.logFailure();
1068 AuthItemRef
retryHint(AGENT_HINT_RETRY_REASON
, AuthValueOverlay(sizeof(reason
), &reason
));
1069 hints
.erase(retryHint
); hints
.insert(retryHint
); // replace
1071 setInput(hints
, context
);
1077 catch (...) // user probably clicked "deny"
1079 logger
.logFailure();
1082 usernameItem
= mOutContext
.find(AGENT_USERNAME
);
1083 passwordItem
= mOutContext
.find(AGENT_PASSWORD
);
1084 if (!usernameItem
|| !passwordItem
)
1086 usernameItem
->getString(username
);
1087 passwordItem
->getString(password
);
1088 } while ((reason
= accept(username
, password
)));
1090 if (SecurityAgent::noReason
== reason
)
1091 logger
.logSuccess();
1092 // else we logged the denial in the loop
1098 QueryKeychainAuth::accept(string
&username
, string
&passphrase
)
1100 // Note: QueryKeychainAuth currently requires that the
1101 // specified user be in the admin group. If this requirement
1102 // ever needs to change, the group name should be passed as
1103 // a separate argument to this method.
1105 const char *user
= username
.c_str();
1106 const char *passwd
= passphrase
.c_str();
1107 int checkpw_status
= checkpw(user
, passwd
);
1109 if (checkpw_status
!= CHECKPW_SUCCESS
) {
1110 return SecurityAgent::invalidPassphrase
;
1113 const char *group
= "admin";
1116 uuid_t group_uuid
, user_uuid
;
1117 rc
= mbr_group_name_to_uuid(group
, group_uuid
);
1118 if (rc
) { return SecurityAgent::userNotInGroup
; }
1120 rc
= mbr_user_name_to_uuid(user
, user_uuid
);
1121 if (rc
) { return SecurityAgent::userNotInGroup
; }
1123 rc
= mbr_check_membership(user_uuid
, group_uuid
, &ismember
);
1124 if (rc
|| !ismember
) { return SecurityAgent::userNotInGroup
; }
1127 return SecurityAgent::noReason
;