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 #define __STDC_WANT_LIB_EXT1__ 1
30 #include "agentquery.h"
31 #include "ccaudit_extensions.h"
33 #include <Security/AuthorizationTags.h>
34 #include <Security/AuthorizationTagsPriv.h>
35 #include <Security/checkpw.h>
36 #include <Security/Security.h>
37 #include <System/sys/fileport.h>
38 #include <bsm/audit.h>
39 #include <bsm/audit_uevents.h> // AUE_ssauthint
40 #include <membership.h>
41 #include <membershipPriv.h>
42 #include <security_utilities/logging.h>
43 #include <security_utilities/mach++.h>
46 #include <xpc/private.h>
47 #include "securityd_service/securityd_service/securityd_service_client.h"
49 #define SECURITYAGENT_BOOTSTRAP_NAME_BASE "com.apple.security.agent"
50 #define SECURITYAGENT_LOGINWINDOW_BOOTSTRAP_NAME_BASE "com.apple.security.agent.login"
52 #define AUTH_XPC_ITEM_NAME "_item_name"
53 #define AUTH_XPC_ITEM_FLAGS "_item_flags"
54 #define AUTH_XPC_ITEM_VALUE "_item_value"
55 #define AUTH_XPC_ITEM_TYPE "_item_type"
56 #define AUTH_XPC_ITEM_SENSITIVE_VALUE_LENGTH "_item_sensitive_value_length"
58 #define AUTH_XPC_REQUEST_METHOD_KEY "_agent_request_key"
59 #define AUTH_XPC_REQUEST_METHOD_CREATE "_agent_request_create"
60 #define AUTH_XPC_REQUEST_METHOD_INVOKE "_agent_request_invoke"
61 #define AUTH_XPC_REQUEST_METHOD_DEACTIVATE "_agent_request_deactivate"
62 #define AUTH_XPC_REQUEST_METHOD_DESTROY "_agent_request_destroy"
63 #define AUTH_XPC_REPLY_METHOD_KEY "_agent_reply_key"
64 #define AUTH_XPC_REPLY_METHOD_RESULT "_agent_reply_result"
65 #define AUTH_XPC_REPLY_METHOD_INTERRUPT "_agent_reply_interrupt"
66 #define AUTH_XPC_REPLY_METHOD_CREATE "_agent_reply_create"
67 #define AUTH_XPC_REPLY_METHOD_DEACTIVATE "_agent_reply_deactivate"
68 #define AUTH_XPC_PLUGIN_NAME "_agent_plugin"
69 #define AUTH_XPC_MECHANISM_NAME "_agent_mechanism"
70 #define AUTH_XPC_HINTS_NAME "_agent_hints"
71 #define AUTH_XPC_CONTEXT_NAME "_agent_context"
72 #define AUTH_XPC_IMMUTABLE_HINTS_NAME "_agent_immutable_hints"
73 #define AUTH_XPC_REQUEST_INSTANCE "_agent_instance"
74 #define AUTH_XPC_REPLY_RESULT_VALUE "_agent_reply_result_value"
75 #define AUTH_XPC_AUDIT_SESSION_PORT "_agent_audit_session_port"
76 #define AUTH_XPC_BOOTSTRAP_PORT "_agent_bootstrap_port"
78 #define UUID_INITIALIZER_FROM_SESSIONID(sessionid) \
79 { 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))) }
82 // SecurityAgentXPCConnection
84 SecurityAgentXPCConnection::SecurityAgentXPCConnection(Session
&session
)
85 : mHostInstance(session
.authhost()),
87 mConnection(&Server::connection()),
88 mAuditToken(Server::connection().auditToken())
90 // this may take a while
91 Server::active().longTermActivity();
92 secnotice("SecurityAgentConnection", "new SecurityAgentConnection(%p)", this);
93 mXPCConnection
= NULL
;
95 struct passwd
*pw
= getpwnam("nobody");
97 mNobodyUID
= pw
->pw_uid
;
101 SecurityAgentXPCConnection::~SecurityAgentXPCConnection()
103 secnotice("SecurityAgentConnection", "SecurityAgentConnection(%p) dying", this);
104 mConnection
->useAgent(NULL
);
106 // If a connection has been established, we need to tear it down.
107 if (NULL
!= mXPCConnection
) {
108 // Tearing this down is a multi-step process. First, request a cancellation.
109 // This is safe even if the connection is already in the canceled state.
110 xpc_connection_cancel(mXPCConnection
);
112 // Then release the XPC connection
113 xpc_release(mXPCConnection
);
114 mXPCConnection
= NULL
;
118 bool SecurityAgentXPCConnection::inDarkWake()
120 return mSession
.server().inDarkWake();
124 SecurityAgentXPCConnection::activate(bool ignoreUid
)
126 secnotice("SecurityAgentConnection", "activate(%p)", this);
128 mConnection
->useAgent(this);
129 if (mXPCConnection
!= NULL
) {
130 // If we already have an XPC connection, there's nothing to do.
135 uuid_t sessionUUID
= UUID_INITIALIZER_FROM_SESSIONID(mSession
.sessionId());
137 // Yes, these need to be throws, as we're still in securityd, and thus still have to do flow control with exceptions.
138 if (!(mSession
.attributes() & sessionHasGraphicAccess
))
139 CssmError::throwMe(CSSM_ERRCODE_NO_USER_INTERACTION
);
141 CssmError::throwMe(CSSM_ERRCODE_IN_DARK_WAKE
);
142 uid_t targetUid
= mHostInstance
->session().originatorUid();
144 secnotice("SecurityAgentXPCConnection","Retrieved UID %d for this session", targetUid
);
145 if (!ignoreUid
&& targetUid
!= 0 && targetUid
!= mNobodyUID
) {
146 mXPCConnection
= xpc_connection_create_mach_service(SECURITYAGENT_BOOTSTRAP_NAME_BASE
, NULL
, 0);
147 xpc_connection_set_target_uid(mXPCConnection
, targetUid
);
148 secnotice("SecurityAgentXPCConnection", "Creating a standard security agent");
150 mXPCConnection
= xpc_connection_create_mach_service(SECURITYAGENT_LOGINWINDOW_BOOTSTRAP_NAME_BASE
, NULL
, 0);
151 xpc_connection_set_instance(mXPCConnection
, sessionUUID
);
152 secnotice("SecurityAgentXPCConnection", "Creating a loginwindow security agent");
155 xpc_connection_set_event_handler(mXPCConnection
, ^(xpc_object_t object
) {
156 if (xpc_get_type(object
) == XPC_TYPE_ERROR
) {
157 secnotice("SecurityAgentXPCConnection", "error during xpc: %s", xpc_dictionary_get_string(object
, XPC_ERROR_KEY_DESCRIPTION
));
160 xpc_connection_resume(mXPCConnection
);
161 secnotice("SecurityAgentXPCConnection", "%p activated", this);
163 catch (MacOSError
&err
) {
164 mConnection
->useAgent(NULL
); // guess not
165 Syslog::error("SecurityAgentConnection: error activating SecurityAgent instance %p", this);
169 secnotice("SecurityAgentXPCConnection", "contact didn't throw (%p)", this);
173 SecurityAgentXPCConnection::terminate()
177 // @@@ This happens already in the destructor; presumably we do this to tear things down orderly
178 mConnection
->useAgent(NULL
);
182 using SecurityAgent::Reason
;
183 using namespace Authorization
;
185 ModuleNexus
<RecursiveMutex
> gAllXPCClientsMutex
;
186 ModuleNexus
<set
<SecurityAgentXPCQuery
*> > allXPCClients
;
189 SecurityAgentXPCQuery::killAllXPCClients()
191 // grab the lock for the client list -- we need to make sure no one modifies the structure while we are iterating it.
192 StLock
<Mutex
> _(gAllXPCClientsMutex());
194 set
<SecurityAgentXPCQuery
*>::iterator clientIterator
= allXPCClients().begin();
195 while (clientIterator
!= allXPCClients().end())
197 set
<SecurityAgentXPCQuery
*>::iterator thisClient
= clientIterator
++;
198 if ((*thisClient
)->getTerminateOnSleep())
200 (*thisClient
)->terminate();
206 SecurityAgentXPCQuery::SecurityAgentXPCQuery(Session
&session
)
207 : SecurityAgentXPCConnection(session
), mAgentConnected(false), mTerminateOnSleep(false)
209 secnotice("SecurityAgentXPCQuery", "new SecurityAgentXPCQuery(%p)", this);
212 SecurityAgentXPCQuery::~SecurityAgentXPCQuery()
214 secnotice("SecurityAgentXPCQuery", "SecurityAgentXPCQuery(%p) dying", this);
215 if (mAgentConnected
) {
221 SecurityAgentXPCQuery::inferHints(Process
&thisProcess
)
223 AuthItemSet clientHints
;
224 SecurityAgent::RequestorType type
= SecurityAgent::bundle
;
225 pid_t clientPid
= thisProcess
.pid();
226 uid_t clientUid
= thisProcess
.uid();
227 string guestPath
= thisProcess
.getPath();
228 Boolean ignoreSession
= TRUE
;
230 clientHints
.insert(AuthItemRef(AGENT_HINT_CLIENT_TYPE
, AuthValueOverlay(sizeof(type
), &type
)));
231 clientHints
.insert(AuthItemRef(AGENT_HINT_CLIENT_PATH
, AuthValueOverlay(guestPath
)));
232 clientHints
.insert(AuthItemRef(AGENT_HINT_CLIENT_PID
, AuthValueOverlay(sizeof(clientPid
), &clientPid
)));
233 clientHints
.insert(AuthItemRef(AGENT_HINT_CLIENT_UID
, AuthValueOverlay(sizeof(clientUid
), &clientUid
)));
236 * If its loginwindow that's asking, override the loginwindow shield detection
237 * up front so that it can trigger SecurityAgent dialogs (like password change)
238 * for when the OD password and keychain password is out of sync.
241 if (guestPath
== "/System/Library/CoreServices/loginwindow.app") {
242 clientHints
.insert(AuthItemRef(AGENT_HINT_IGNORE_SESSION
, AuthValueOverlay(sizeof(ignoreSession
), &ignoreSession
)));
245 mClientHints
.insert(clientHints
.begin(), clientHints
.end());
247 bool validSignature
= thisProcess
.checkAppleSigned();
248 AuthItemSet clientImmutableHints
;
250 clientImmutableHints
.insert(AuthItemRef(AGENT_HINT_CLIENT_SIGNED
, AuthValueOverlay(sizeof(validSignature
), &validSignature
)));
252 mImmutableHints
.insert(clientImmutableHints
.begin(), clientImmutableHints
.end());
255 void SecurityAgentXPCQuery::addHint(const char *name
, const void *value
, UInt32 valueLen
, UInt32 flags
)
257 AuthorizationItem item
= { name
, valueLen
, const_cast<void *>(value
), flags
};
258 mClientHints
.insert(AuthItemRef(item
));
263 SecurityAgentXPCQuery::readChoice()
268 AuthItem
*allowAction
= mOutContext
.find(AGENT_CONTEXT_ALLOW
);
272 if (allowAction
->getString(allowString
)
273 && (allowString
== "YES"))
277 AuthItem
*rememberAction
= mOutContext
.find(AGENT_CONTEXT_REMEMBER_ACTION
);
280 string rememberString
;
281 if (rememberAction
->getString(rememberString
)
282 && (rememberString
== "YES"))
288 SecurityAgentXPCQuery::disconnect()
290 if (NULL
!= mXPCConnection
) {
291 xpc_object_t requestObject
= xpc_dictionary_create(NULL
, NULL
, 0);
292 xpc_dictionary_set_string(requestObject
, AUTH_XPC_REQUEST_METHOD_KEY
, AUTH_XPC_REQUEST_METHOD_DESTROY
);
293 xpc_connection_send_message(mXPCConnection
, requestObject
);
294 xpc_release(requestObject
);
297 StLock
<Mutex
> _(gAllXPCClientsMutex());
298 allXPCClients().erase(this);
302 SecurityAgentXPCQuery::terminate()
307 static void xpcArrayToAuthItemSet(AuthItemSet
*setToBuild
, xpc_object_t input
) {
310 xpc_array_apply(input
, ^bool(size_t index
, xpc_object_t item
) {
311 const char *name
= xpc_dictionary_get_string(item
, AUTH_XPC_ITEM_NAME
);
314 const void *data
= xpc_dictionary_get_data(item
, AUTH_XPC_ITEM_VALUE
, &length
);
317 // <rdar://problem/13033889> authd is holding on to multiple copies of my password in the clear
318 bool sensitive
= xpc_dictionary_get_value(item
, AUTH_XPC_ITEM_SENSITIVE_VALUE_LENGTH
);
320 size_t sensitiveLength
= (size_t)xpc_dictionary_get_uint64(item
, AUTH_XPC_ITEM_SENSITIVE_VALUE_LENGTH
);
321 dataCopy
= malloc(sensitiveLength
);
322 memcpy(dataCopy
, data
, sensitiveLength
);
323 memset_s((void *)data
, length
, 0, sensitiveLength
); // clear the sensitive data, memset_s is never optimized away
324 length
= sensitiveLength
;
326 dataCopy
= malloc(length
);
327 memcpy(dataCopy
, data
, length
);
330 uint64_t flags
= xpc_dictionary_get_uint64(item
, AUTH_XPC_ITEM_FLAGS
);
331 AuthItemRef
nextItem(name
, AuthValueOverlay((uint32_t)length
, dataCopy
), (uint32_t)flags
);
332 setToBuild
->insert(nextItem
);
333 memset(dataCopy
, 0, length
); // The authorization items contain things like passwords, so wiping clean is important.
340 SecurityAgentXPCQuery::create(const char *pluginId
, const char *mechanismId
)
342 bool ignoreUid
= false;
347 mAgentConnected
= false;
349 xpc_object_t requestObject
= xpc_dictionary_create(NULL
, NULL
, 0);
350 xpc_dictionary_set_string(requestObject
, AUTH_XPC_REQUEST_METHOD_KEY
, AUTH_XPC_REQUEST_METHOD_CREATE
);
351 xpc_dictionary_set_string(requestObject
, AUTH_XPC_PLUGIN_NAME
, pluginId
);
352 xpc_dictionary_set_string(requestObject
, AUTH_XPC_MECHANISM_NAME
, mechanismId
);
354 uid_t targetUid
= Server::process().uid();
355 bool doSwitchAudit
= (ignoreUid
|| targetUid
== 0 || targetUid
== mNobodyUID
);
356 bool doSwitchBootstrap
= (ignoreUid
|| targetUid
== 0 || targetUid
== mNobodyUID
);
359 mach_port_name_t jobPort
;
360 if (0 == audit_session_port(mSession
.sessionId(), &jobPort
)) {
361 secnotice("SecurityAgentXPCQuery", "attaching an audit session port because the uid was %d", targetUid
);
362 xpc_dictionary_set_mach_send(requestObject
, AUTH_XPC_AUDIT_SESSION_PORT
, jobPort
);
363 if (mach_port_mod_refs(mach_task_self(), jobPort
, MACH_PORT_RIGHT_SEND
, -1) != KERN_SUCCESS
) {
364 secnotice("SecurityAgentXPCQuery", "unable to release send right for audit session, leaking");
369 if (doSwitchBootstrap
) {
370 secnotice("SecurityAgentXPCQuery", "attaching a bootstrap port because the uid was %d", targetUid
);
371 MachPlusPlus::Bootstrap processBootstrap
= Server::process().taskPort().bootstrap();
372 xpc_dictionary_set_mach_send(requestObject
, AUTH_XPC_BOOTSTRAP_PORT
, processBootstrap
);
375 xpc_object_t object
= xpc_connection_send_message_with_reply_sync(mXPCConnection
, requestObject
);
376 if (xpc_get_type(object
) == XPC_TYPE_DICTIONARY
) {
377 const char *replyType
= xpc_dictionary_get_string(object
, AUTH_XPC_REPLY_METHOD_KEY
);
378 if (0 == strcmp(replyType
, AUTH_XPC_REPLY_METHOD_CREATE
)) {
379 uint64_t status
= xpc_dictionary_get_uint64(object
, AUTH_XPC_REPLY_RESULT_VALUE
);
380 if (status
== kAuthorizationResultAllow
) {
381 mAgentConnected
= true;
383 secnotice("SecurityAgentXPCQuery", "plugin create failed in SecurityAgent");
384 MacOSError::throwMe(errAuthorizationInternal
);
387 } else if (xpc_get_type(object
) == XPC_TYPE_ERROR
) {
388 if (XPC_ERROR_CONNECTION_INVALID
== object
) {
389 // If we get an error before getting the create response, try again without the UID
391 secnotice("SecurityAgentXPCQuery", "failed to establish connection, no retries left");
393 MacOSError::throwMe(errAuthorizationInternal
);
395 secnotice("SecurityAgentXPCQuery", "failed to establish connection, retrying with no UID");
397 xpc_release(mXPCConnection
);
398 mXPCConnection
= NULL
;
400 } else if (XPC_ERROR_CONNECTION_INTERRUPTED
== object
) {
401 // If we get an error before getting the create response, try again
405 xpc_release(requestObject
);
406 } while (!mAgentConnected
);
408 StLock
<Mutex
> _(gAllXPCClientsMutex());
409 allXPCClients().insert(this);
412 static xpc_object_t
authItemSetToXPCArray(AuthItemSet input
) {
413 xpc_object_t outputArray
= xpc_array_create(NULL
, 0);
414 for (AuthItemSet::iterator i
= input
.begin(); i
!= input
.end(); i
++) {
415 AuthItemRef item
= *i
;
417 xpc_object_t xpc_data
= xpc_dictionary_create(NULL
, NULL
, 0);
418 xpc_dictionary_set_string(xpc_data
, AUTH_XPC_ITEM_NAME
, item
->name());
419 AuthorizationValue value
= item
->value();
420 if (value
.data
!= NULL
) {
421 xpc_dictionary_set_data(xpc_data
, AUTH_XPC_ITEM_VALUE
, value
.data
, value
.length
);
423 xpc_dictionary_set_uint64(xpc_data
, AUTH_XPC_ITEM_FLAGS
, item
->flags());
424 xpc_array_append_value(outputArray
, xpc_data
);
425 xpc_release(xpc_data
);
431 SecurityAgentXPCQuery::invoke() {
432 xpc_object_t hintsArray
= authItemSetToXPCArray(mInHints
);
433 xpc_object_t contextArray
= authItemSetToXPCArray(mInContext
);
434 xpc_object_t immutableHintsArray
= authItemSetToXPCArray(mImmutableHints
);
436 xpc_object_t requestObject
= xpc_dictionary_create(NULL
, NULL
, 0);
437 xpc_dictionary_set_string(requestObject
, AUTH_XPC_REQUEST_METHOD_KEY
, AUTH_XPC_REQUEST_METHOD_INVOKE
);
438 xpc_dictionary_set_value(requestObject
, AUTH_XPC_HINTS_NAME
, hintsArray
);
439 xpc_dictionary_set_value(requestObject
, AUTH_XPC_CONTEXT_NAME
, contextArray
);
440 xpc_dictionary_set_value(requestObject
, AUTH_XPC_IMMUTABLE_HINTS_NAME
, immutableHintsArray
);
442 xpc_object_t object
= xpc_connection_send_message_with_reply_sync(mXPCConnection
, requestObject
);
443 if (xpc_get_type(object
) == XPC_TYPE_DICTIONARY
) {
444 const char *replyType
= xpc_dictionary_get_string(object
, AUTH_XPC_REPLY_METHOD_KEY
);
445 if (0 == strcmp(replyType
, AUTH_XPC_REPLY_METHOD_RESULT
)) {
446 xpc_object_t xpcHints
= xpc_dictionary_get_value(object
, AUTH_XPC_HINTS_NAME
);
447 xpc_object_t xpcContext
= xpc_dictionary_get_value(object
, AUTH_XPC_CONTEXT_NAME
);
448 AuthItemSet tempHints
, tempContext
;
449 xpcArrayToAuthItemSet(&tempHints
, xpcHints
);
450 xpcArrayToAuthItemSet(&tempContext
, xpcContext
);
451 mOutHints
= tempHints
;
452 mOutContext
= tempContext
;
453 mLastResult
= xpc_dictionary_get_uint64(object
, AUTH_XPC_REPLY_RESULT_VALUE
);
455 } else if (xpc_get_type(object
) == XPC_TYPE_ERROR
) {
456 if (XPC_ERROR_CONNECTION_INVALID
== object
) {
457 // If the connection drops, return an "auth undefined" result, because we cannot continue
458 } else if (XPC_ERROR_CONNECTION_INTERRUPTED
== object
) {
459 // If the agent dies, return an "auth undefined" result, because we cannot continue
464 xpc_release(hintsArray
);
465 xpc_release(contextArray
);
466 xpc_release(immutableHintsArray
);
467 xpc_release(requestObject
);
470 void SecurityAgentXPCQuery::checkResult()
472 // now check the OSStatus return from the server side
473 switch (mLastResult
) {
474 case kAuthorizationResultAllow
: return;
475 case kAuthorizationResultDeny
:
476 case kAuthorizationResultUserCanceled
: CssmError::throwMe(CSSM_ERRCODE_USER_CANCELED
);
477 default: MacOSError::throwMe(errAuthorizationInternal
);
482 // Perform the "rogue app" access query dialog
484 QueryKeychainUse::QueryKeychainUse(bool needPass
, const Database
*db
)
485 : mPassphraseCheck(NULL
)
487 // if passphrase checking requested, save KeychainDatabase reference
488 // (will quietly disable check if db isn't a keychain)
490 mPassphraseCheck
= dynamic_cast<const KeychainDatabase
*>(db
);
492 setTerminateOnSleep(true);
495 Reason
QueryKeychainUse::queryUser (const char *database
, const char *description
, AclAuthorization action
)
497 Reason reason
= SecurityAgent::noReason
;
498 uint32_t retryCount
= 0;
499 AuthItemSet hints
, context
;
501 // prepopulate with client hints
502 hints
.insert(mClientHints
.begin(), mClientHints
.end());
504 // put action/operation (sint32) into hints
505 hints
.insert(AuthItemRef(AGENT_HINT_ACL_TAG
, AuthValueOverlay(sizeof(action
), static_cast<sint32
*>(&action
))));
507 // item name into hints
509 hints
.insert(AuthItemRef(AGENT_HINT_KEYCHAIN_ITEM_NAME
, AuthValueOverlay(description
? (uint32_t)strlen(description
) : 0, const_cast<char*>(description
))));
511 // keychain name into hints
512 hints
.insert(AuthItemRef(AGENT_HINT_KEYCHAIN_PATH
, AuthValueOverlay(database
? (uint32_t)strlen(database
) : 0, const_cast<char*>(database
))));
514 if (mPassphraseCheck
)
516 create("builtin", "confirm-access-password");
518 CssmAutoData
data(Allocator::standard(Allocator::sensitive
));
523 AuthItemRef
triesHint(AGENT_HINT_TRIES
, AuthValueOverlay(sizeof(retryCount
), &retryCount
));
524 hints
.erase(triesHint
); hints
.insert(triesHint
); // replace
526 if (retryCount
++ > kMaximumAuthorizationTries
)
528 reason
= SecurityAgent::tooManyTries
;
531 AuthItemRef
retryHint(AGENT_HINT_RETRY_REASON
, AuthValueOverlay(sizeof(reason
), &reason
));
532 hints
.erase(retryHint
); hints
.insert(retryHint
); // replace
534 setInput(hints
, context
);
537 if (retryCount
> kMaximumAuthorizationTries
)
544 AuthItem
*passwordItem
= mOutContext
.find(kAuthorizationEnvironmentPassword
);
548 passwordItem
->getCssmData(data
);
550 while ((reason
= (const_cast<KeychainDatabase
*>(mPassphraseCheck
)->decode(data
) ? SecurityAgent::noReason
: SecurityAgent::invalidPassphrase
)));
554 create("builtin", "confirm-access");
555 setInput(hints
, context
);
566 // Obtain passphrases and submit them to the accept() method until it is accepted
567 // or we can't get another passphrase. Accept() should consume the passphrase
568 // if it is accepted. If no passphrase is acceptable, throw out of here.
570 Reason
QueryOld::query()
572 Reason reason
= SecurityAgent::noReason
;
573 AuthItemSet hints
, context
;
574 CssmAutoData
passphrase(Allocator::standard(Allocator::sensitive
));
577 // prepopulate with client hints
579 const char *keychainPath
= database
.dbName();
580 hints
.insert(AuthItemRef(AGENT_HINT_KEYCHAIN_PATH
, AuthValueOverlay((uint32_t)strlen(keychainPath
), const_cast<char*>(keychainPath
))));
582 hints
.insert(mClientHints
.begin(), mClientHints
.end());
584 create("builtin", "unlock-keychain");
588 AuthItemRef
triesHint(AGENT_HINT_TRIES
, AuthValueOverlay(sizeof(retryCount
), &retryCount
));
589 hints
.erase(triesHint
); hints
.insert(triesHint
); // replace
593 if (retryCount
> maxTries
)
595 reason
= SecurityAgent::tooManyTries
;
598 AuthItemRef
retryHint(AGENT_HINT_RETRY_REASON
, AuthValueOverlay(sizeof(reason
), &reason
));
599 hints
.erase(retryHint
); hints
.insert(retryHint
); // replace
601 setInput(hints
, context
);
604 if (retryCount
> maxTries
)
611 AuthItem
*passwordItem
= mOutContext
.find(kAuthorizationEnvironmentPassword
);
615 passwordItem
->getCssmData(passphrase
);
618 while ((reason
= accept(passphrase
)));
620 return SecurityAgent::noReason
;
625 // Get existing passphrase (unlock) Query
627 Reason
QueryOld::operator () ()
634 // End-classes for old secrets
636 Reason
QueryUnlock::accept(CssmManagedData
&passphrase
)
638 if (safer_cast
<KeychainDatabase
&>(database
).decode(passphrase
))
639 return SecurityAgent::noReason
;
641 return SecurityAgent::invalidPassphrase
;
644 Reason
QueryUnlock::retrievePassword(CssmOwnedData
&passphrase
) {
645 CssmAutoData
pass(Allocator::standard(Allocator::sensitive
));
647 AuthItem
*passwordItem
= mOutContext
.find(kAuthorizationEnvironmentPassword
);
649 return SecurityAgent::invalidPassphrase
;
651 passwordItem
->getCssmData(pass
);
655 return SecurityAgent::noReason
;
658 QueryKeybagPassphrase::QueryKeybagPassphrase(Session
& session
, int32_t tries
) : mSession(session
), mContext(), mRetries(tries
)
660 setTerminateOnSleep(true);
661 mContext
= mSession
.get_current_service_context();
664 Reason
QueryKeybagPassphrase::query()
666 Reason reason
= SecurityAgent::noReason
;
667 AuthItemSet hints
, context
;
668 CssmAutoData
passphrase(Allocator::standard(Allocator::sensitive
));
671 // prepopulate with client hints
673 const char *keychainPath
= "iCloud";
674 hints
.insert(AuthItemRef(AGENT_HINT_KEYCHAIN_PATH
, AuthValueOverlay((uint32_t)strlen(keychainPath
), const_cast<char*>(keychainPath
))));
676 hints
.insert(mClientHints
.begin(), mClientHints
.end());
678 create("builtin", "unlock-keychain");
683 currentTry
= retryCount
;
684 if (retryCount
> mRetries
)
686 return SecurityAgent::tooManyTries
;
690 AuthItemRef
triesHint(AGENT_HINT_TRIES
, AuthValueOverlay(sizeof(currentTry
), ¤tTry
));
691 hints
.erase(triesHint
); hints
.insert(triesHint
); // replace
693 AuthItemRef
retryHint(AGENT_HINT_RETRY_REASON
, AuthValueOverlay(sizeof(reason
), &reason
));
694 hints
.erase(retryHint
); hints
.insert(retryHint
); // replace
696 setInput(hints
, context
);
701 AuthItem
*passwordItem
= mOutContext
.find(kAuthorizationEnvironmentPassword
);
705 passwordItem
->getCssmData(passphrase
);
707 while ((reason
= accept(passphrase
)));
709 return SecurityAgent::noReason
;
712 Reason
QueryKeybagPassphrase::accept(Security::CssmManagedData
& password
)
714 if (service_client_kb_unlock(&mContext
, password
.data(), (int)password
.length()) == 0) {
715 mSession
.keybagSetState(session_keybag_unlocked
);
716 return SecurityAgent::noReason
;
718 return SecurityAgent::invalidPassphrase
;
721 QueryKeybagNewPassphrase::QueryKeybagNewPassphrase(Session
& session
) : QueryKeybagPassphrase(session
) {}
723 Reason
QueryKeybagNewPassphrase::query(CssmOwnedData
&oldPassphrase
, CssmOwnedData
&passphrase
)
725 CssmAutoData
pass(Allocator::standard(Allocator::sensitive
));
726 CssmAutoData
oldPass(Allocator::standard(Allocator::sensitive
));
727 Reason reason
= SecurityAgent::noReason
;
728 AuthItemSet hints
, context
;
731 // prepopulate with client hints
733 const char *keychainPath
= "iCloud";
734 hints
.insert(AuthItemRef(AGENT_HINT_KEYCHAIN_PATH
, AuthValueOverlay((uint32_t)strlen(keychainPath
), const_cast<char*>(keychainPath
))));
736 const char *showResetString
= "YES";
737 hints
.insert(AuthItemRef(AGENT_HINT_SHOW_RESET
, AuthValueOverlay((uint32_t)strlen(showResetString
), const_cast<char*>(showResetString
))));
739 hints
.insert(mClientHints
.begin(), mClientHints
.end());
741 create("builtin", "change-passphrase");
744 AuthItem
*resetPassword
= NULL
;
747 currentTry
= retryCount
;
748 if (retryCount
> mRetries
)
750 return SecurityAgent::tooManyTries
;
754 AuthItemRef
triesHint(AGENT_HINT_TRIES
, AuthValueOverlay(sizeof(currentTry
), ¤tTry
));
755 hints
.erase(triesHint
); hints
.insert(triesHint
); // replace
757 AuthItemRef
retryHint(AGENT_HINT_RETRY_REASON
, AuthValueOverlay(sizeof(reason
), &reason
));
758 hints
.erase(retryHint
); hints
.insert(retryHint
); // replace
760 setInput(hints
, context
);
765 resetPassword
= mOutContext
.find(AGENT_CONTEXT_RESET_PASSWORD
);
766 if (resetPassword
!= NULL
) {
767 return SecurityAgent::resettingPassword
;
770 AuthItem
*oldPasswordItem
= mOutContext
.find(AGENT_PASSWORD
);
771 if (!oldPasswordItem
)
774 oldPasswordItem
->getCssmData(oldPass
);
776 while ((reason
= accept(oldPass
)));
778 if (reason
== SecurityAgent::noReason
) {
779 AuthItem
*passwordItem
= mOutContext
.find(AGENT_CONTEXT_NEW_PASSWORD
);
781 return SecurityAgent::invalidPassphrase
;
783 passwordItem
->getCssmData(pass
);
785 oldPassphrase
= oldPass
;
789 return SecurityAgent::noReason
;
792 QueryPIN::QueryPIN(Database
&db
)
793 : QueryOld(db
), mPin(Allocator::standard())
795 this->inferHints(Server::process());
799 Reason
QueryPIN::accept(CssmManagedData
&pin
)
801 // no retries for now
803 return SecurityAgent::noReason
;
808 // Obtain passphrases and submit them to the accept() method until it is accepted
809 // or we can't get another passphrase. Accept() should consume the passphrase
810 // if it is accepted. If no passphrase is acceptable, throw out of here.
812 Reason
QueryNewPassphrase::query()
814 Reason reason
= initialReason
;
815 CssmAutoData
passphrase(Allocator::standard(Allocator::sensitive
));
816 CssmAutoData
oldPassphrase(Allocator::standard(Allocator::sensitive
));
818 AuthItemSet hints
, context
;
822 // prepopulate with client hints
823 hints
.insert(mClientHints
.begin(), mClientHints
.end());
825 // keychain name into hints
826 hints
.insert(AuthItemRef(AGENT_HINT_KEYCHAIN_PATH
, AuthValueOverlay(database
.dbName())));
828 switch (initialReason
)
830 case SecurityAgent::newDatabase
:
831 create("builtin", "new-passphrase");
833 case SecurityAgent::changePassphrase
:
834 create("builtin", "change-passphrase");
842 AuthItemRef
triesHint(AGENT_HINT_TRIES
, AuthValueOverlay(sizeof(retryCount
), &retryCount
));
843 hints
.erase(triesHint
); hints
.insert(triesHint
); // replace
845 if (++retryCount
> maxTries
)
847 reason
= SecurityAgent::tooManyTries
;
850 AuthItemRef
retryHint(AGENT_HINT_RETRY_REASON
, AuthValueOverlay(sizeof(reason
), &reason
));
851 hints
.erase(retryHint
); hints
.insert(retryHint
); // replace
853 setInput(hints
, context
);
856 if (retryCount
> maxTries
)
863 if (SecurityAgent::changePassphrase
== initialReason
)
865 AuthItem
*oldPasswordItem
= mOutContext
.find(AGENT_PASSWORD
);
866 if (!oldPasswordItem
)
869 oldPasswordItem
->getCssmData(oldPassphrase
);
872 AuthItem
*passwordItem
= mOutContext
.find(AGENT_CONTEXT_NEW_PASSWORD
);
876 passwordItem
->getCssmData(passphrase
);
879 while ((reason
= accept(passphrase
, (initialReason
== SecurityAgent::changePassphrase
) ? &oldPassphrase
.get() : NULL
)));
881 return SecurityAgent::noReason
;
886 // Get new passphrase Query
888 Reason
QueryNewPassphrase::operator () (CssmOwnedData
&oldPassphrase
, CssmOwnedData
&passphrase
)
890 if (Reason result
= query())
891 return result
; // failed
892 passphrase
= mPassphrase
;
893 oldPassphrase
= mOldPassphrase
;
894 return SecurityAgent::noReason
; // success
897 Reason
QueryNewPassphrase::accept(CssmManagedData
&passphrase
, CssmData
*oldPassphrase
)
899 //@@@ acceptance criteria are currently hardwired here
900 //@@@ This validation presumes ASCII - UTF8 might be more lenient
902 // if we have an old passphrase, check it
903 if (oldPassphrase
&& !safer_cast
<KeychainDatabase
&>(database
).validatePassphrase(*oldPassphrase
))
904 return SecurityAgent::oldPassphraseWrong
;
906 // sanity check the new passphrase (but allow user override)
907 if (!(mPassphraseValid
&& passphrase
.get() == mPassphrase
)) {
908 mPassphrase
= passphrase
;
909 if (oldPassphrase
) mOldPassphrase
= *oldPassphrase
;
910 mPassphraseValid
= true;
911 if (mPassphrase
.length() == 0)
912 return SecurityAgent::passphraseIsNull
;
913 if (mPassphrase
.length() < 6)
914 return SecurityAgent::passphraseTooSimple
;
918 return SecurityAgent::noReason
;
922 // Get a passphrase for unspecified use
924 Reason
QueryGenericPassphrase::operator () (const CssmData
*prompt
, bool verify
,
927 return query(prompt
, verify
, passphrase
);
930 Reason
QueryGenericPassphrase::query(const CssmData
*prompt
, bool verify
,
933 Reason reason
= SecurityAgent::noReason
;
934 AuthItemSet hints
, context
;
936 hints
.insert(mClientHints
.begin(), mClientHints
.end());
937 hints
.insert(AuthItemRef(AGENT_HINT_CUSTOM_PROMPT
, AuthValueOverlay(prompt
? (UInt32
)prompt
->length() : 0, prompt
? prompt
->data() : NULL
)));
938 // XXX/gh defined by dmitch but no analogous hint in
939 // AuthorizationTagsPriv.h:
940 // CSSM_ATTRIBUTE_ALERT_TITLE (optional alert panel title)
942 if (false == verify
) { // import
943 create("builtin", "generic-unlock");
944 } else { // verify passphrase (export)
945 create("builtin", "generic-new-passphrase");
948 AuthItem
*passwordItem
;
951 setInput(hints
, context
);
954 passwordItem
= mOutContext
.find(AGENT_PASSWORD
);
956 } while (!passwordItem
);
958 passwordItem
->getString(passphrase
);
965 // Get a DB blob's passphrase--keychain synchronization
967 Reason
QueryDBBlobSecret::operator () (DbHandle
*dbHandleArray
, uint8 dbHandleArrayCount
, DbHandle
*dbHandleAuthenticated
)
969 return query(dbHandleArray
, dbHandleArrayCount
, dbHandleAuthenticated
);
972 Reason
QueryDBBlobSecret::query(DbHandle
*dbHandleArray
, uint8 dbHandleArrayCount
, DbHandle
*dbHandleAuthenticated
)
974 Reason reason
= SecurityAgent::noReason
;
975 CssmAutoData
passphrase(Allocator::standard(Allocator::sensitive
));
976 AuthItemSet hints
/*NUKEME*/, context
;
978 hints
.insert(mClientHints
.begin(), mClientHints
.end());
979 create("builtin", "generic-unlock-kcblob");
981 AuthItem
*secretItem
;
986 AuthItemRef
triesHint(AGENT_HINT_TRIES
, AuthValueOverlay(sizeof(retryCount
), &retryCount
));
987 hints
.erase(triesHint
); hints
.insert(triesHint
); // replace
989 if (++retryCount
> maxTries
)
991 reason
= SecurityAgent::tooManyTries
;
994 AuthItemRef
retryHint(AGENT_HINT_RETRY_REASON
, AuthValueOverlay(sizeof(reason
), &reason
));
995 hints
.erase(retryHint
); hints
.insert(retryHint
); // replace
997 setInput(hints
, context
);
1000 secretItem
= mOutContext
.find(AGENT_PASSWORD
);
1003 secretItem
->getCssmData(passphrase
);
1005 } while ((reason
= accept(passphrase
, dbHandleArray
, dbHandleArrayCount
, dbHandleAuthenticated
)));
1010 Reason
QueryDBBlobSecret::accept(CssmManagedData
&passphrase
,
1011 DbHandle
*dbHandlesToAuthenticate
, uint8 dbHandleCount
, DbHandle
*dbHandleAuthenticated
)
1013 DbHandle
*currHdl
= dbHandlesToAuthenticate
;
1015 Boolean authenticated
= false;
1016 for (index
=0; index
< dbHandleCount
&& !authenticated
; index
++)
1020 RefPointer
<KeychainDatabase
> dbToUnlock
= Server::keychain(*currHdl
);
1021 dbToUnlock
->unlockDb(passphrase
, false);
1022 authenticated
= true;
1023 *dbHandleAuthenticated
= *currHdl
; // return the DbHandle that 'passphrase' authenticated with.
1025 catch (const CommonError
&err
)
1027 currHdl
++; // we failed to authenticate with this one, onto the next one.
1030 if ( !authenticated
)
1031 return SecurityAgent::invalidPassphrase
;
1033 return SecurityAgent::noReason
;
1036 // @@@ no pluggable authentication possible!
1038 QueryKeychainAuth::operator () (const char *database
, const char *description
, AclAuthorization action
, const char *prompt
)
1040 Reason reason
= SecurityAgent::noReason
;
1041 AuthItemSet hints
, context
;
1046 using CommonCriteria::Securityd::KeychainAuthLogger
;
1047 KeychainAuthLogger
logger(mAuditToken
, (short)AUE_ssauthint
, database
, description
);
1049 hints
.insert(mClientHints
.begin(), mClientHints
.end());
1051 // put action/operation (sint32) into hints
1052 hints
.insert(AuthItemRef(AGENT_HINT_ACL_TAG
, AuthValueOverlay(sizeof(action
), static_cast<sint32
*>(&action
))));
1054 hints
.insert(AuthItemRef(AGENT_HINT_CUSTOM_PROMPT
, AuthValueOverlay(prompt
? (uint32_t)strlen(prompt
) : 0, const_cast<char*>(prompt
))));
1056 // item name into hints
1057 hints
.insert(AuthItemRef(AGENT_HINT_KEYCHAIN_ITEM_NAME
, AuthValueOverlay(description
? (uint32_t)strlen(description
) : 0, const_cast<char*>(description
))));
1059 // keychain name into hints
1060 hints
.insert(AuthItemRef(AGENT_HINT_KEYCHAIN_PATH
, AuthValueOverlay(database
? (uint32_t)strlen(database
) : 0, const_cast<char*>(database
))));
1062 create("builtin", "confirm-access-user-password");
1064 AuthItem
*usernameItem
;
1065 AuthItem
*passwordItem
;
1069 AuthItemRef
triesHint(AGENT_HINT_TRIES
, AuthValueOverlay(sizeof(retryCount
), &retryCount
));
1070 hints
.erase(triesHint
); hints
.insert(triesHint
); // replace
1072 if (++retryCount
> maxTries
)
1073 reason
= SecurityAgent::tooManyTries
;
1075 if (SecurityAgent::noReason
!= reason
)
1077 if (SecurityAgent::tooManyTries
== reason
)
1078 logger
.logFailure(NULL
, CommonCriteria::errTooManyTries
);
1080 logger
.logFailure();
1083 AuthItemRef
retryHint(AGENT_HINT_RETRY_REASON
, AuthValueOverlay(sizeof(reason
), &reason
));
1084 hints
.erase(retryHint
); hints
.insert(retryHint
); // replace
1086 setInput(hints
, context
);
1092 catch (...) // user probably clicked "deny"
1094 logger
.logFailure();
1097 usernameItem
= mOutContext
.find(AGENT_USERNAME
);
1098 passwordItem
= mOutContext
.find(AGENT_PASSWORD
);
1099 if (!usernameItem
|| !passwordItem
)
1101 usernameItem
->getString(username
);
1102 passwordItem
->getString(password
);
1103 } while ((reason
= accept(username
, password
)));
1105 if (SecurityAgent::noReason
== reason
)
1106 logger
.logSuccess();
1107 // else we logged the denial in the loop
1113 QueryKeychainAuth::accept(string
&username
, string
&passphrase
)
1115 // Note: QueryKeychainAuth currently requires that the
1116 // specified user be in the admin group. If this requirement
1117 // ever needs to change, the group name should be passed as
1118 // a separate argument to this method.
1120 const char *user
= username
.c_str();
1121 const char *passwd
= passphrase
.c_str();
1122 int checkpw_status
= checkpw(user
, passwd
);
1124 if (checkpw_status
!= CHECKPW_SUCCESS
) {
1125 return SecurityAgent::invalidPassphrase
;
1128 const char *group
= "admin";
1131 uuid_t group_uuid
, user_uuid
;
1132 rc
= mbr_group_name_to_uuid(group
, group_uuid
);
1133 if (rc
) { return SecurityAgent::userNotInGroup
; }
1135 rc
= mbr_user_name_to_uuid(user
, user_uuid
);
1136 if (rc
) { return SecurityAgent::userNotInGroup
; }
1138 rc
= mbr_check_membership(user_uuid
, group_uuid
, &ismember
);
1139 if (rc
|| !ismember
) { return SecurityAgent::userNotInGroup
; }
1142 return SecurityAgent::noReason
;