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 cancelled 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_PROCESS_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 __block OSStatus status
= kAuthorizationResultUndefined
;
434 xpc_object_t hintsArray
= authItemSetToXPCArray(mInHints
);
435 xpc_object_t contextArray
= authItemSetToXPCArray(mInContext
);
436 xpc_object_t immutableHintsArray
= authItemSetToXPCArray(mImmutableHints
);
438 xpc_object_t requestObject
= xpc_dictionary_create(NULL
, NULL
, 0);
439 xpc_dictionary_set_string(requestObject
, AUTH_XPC_REQUEST_METHOD_KEY
, AUTH_XPC_REQUEST_METHOD_INVOKE
);
440 xpc_dictionary_set_value(requestObject
, AUTH_XPC_HINTS_NAME
, hintsArray
);
441 xpc_dictionary_set_value(requestObject
, AUTH_XPC_CONTEXT_NAME
, contextArray
);
442 xpc_dictionary_set_value(requestObject
, AUTH_XPC_IMMUTABLE_HINTS_NAME
, immutableHintsArray
);
444 xpc_object_t object
= xpc_connection_send_message_with_reply_sync(mXPCConnection
, requestObject
);
445 if (xpc_get_type(object
) == XPC_TYPE_DICTIONARY
) {
446 const char *replyType
= xpc_dictionary_get_string(object
, AUTH_XPC_REPLY_METHOD_KEY
);
447 if (0 == strcmp(replyType
, AUTH_XPC_REPLY_METHOD_RESULT
)) {
448 xpc_object_t xpcHints
= xpc_dictionary_get_value(object
, AUTH_XPC_HINTS_NAME
);
449 xpc_object_t xpcContext
= xpc_dictionary_get_value(object
, AUTH_XPC_CONTEXT_NAME
);
450 AuthItemSet tempHints
, tempContext
;
451 xpcArrayToAuthItemSet(&tempHints
, xpcHints
);
452 xpcArrayToAuthItemSet(&tempContext
, xpcContext
);
453 mOutHints
= tempHints
;
454 mOutContext
= tempContext
;
455 mLastResult
= xpc_dictionary_get_uint64(object
, AUTH_XPC_REPLY_RESULT_VALUE
);
457 } else if (xpc_get_type(object
) == XPC_TYPE_ERROR
) {
458 if (XPC_ERROR_CONNECTION_INVALID
== object
) {
459 // If the connection drops, return an "auth undefined" result, because we cannot continue
460 } else if (XPC_ERROR_CONNECTION_INTERRUPTED
== object
) {
461 // If the agent dies, return an "auth undefined" result, because we cannot continue
466 xpc_release(hintsArray
);
467 xpc_release(contextArray
);
468 xpc_release(immutableHintsArray
);
469 xpc_release(requestObject
);
474 void SecurityAgentXPCQuery::checkResult()
476 // now check the OSStatus return from the server side
477 switch (mLastResult
) {
478 case kAuthorizationResultAllow
: return;
479 case kAuthorizationResultDeny
:
480 case kAuthorizationResultUserCanceled
: CssmError::throwMe(CSSM_ERRCODE_USER_CANCELED
);
481 default: MacOSError::throwMe(errAuthorizationInternal
);
486 // Perform the "rogue app" access query dialog
488 QueryKeychainUse::QueryKeychainUse(bool needPass
, const Database
*db
)
489 : mPassphraseCheck(NULL
)
491 // if passphrase checking requested, save KeychainDatabase reference
492 // (will quietly disable check if db isn't a keychain)
494 mPassphraseCheck
= dynamic_cast<const KeychainDatabase
*>(db
);
496 setTerminateOnSleep(true);
499 Reason
QueryKeychainUse::queryUser (const char *database
, const char *description
, AclAuthorization action
)
501 Reason reason
= SecurityAgent::noReason
;
502 uint32_t retryCount
= 0;
504 AuthItemSet hints
, context
;
506 // prepopulate with client hints
507 hints
.insert(mClientHints
.begin(), mClientHints
.end());
509 // put action/operation (sint32) into hints
510 hints
.insert(AuthItemRef(AGENT_HINT_ACL_TAG
, AuthValueOverlay(sizeof(action
), static_cast<sint32
*>(&action
))));
512 // item name into hints
514 hints
.insert(AuthItemRef(AGENT_HINT_KEYCHAIN_ITEM_NAME
, AuthValueOverlay(description
? (uint32_t)strlen(description
) : 0, const_cast<char*>(description
))));
516 // keychain name into hints
517 hints
.insert(AuthItemRef(AGENT_HINT_KEYCHAIN_PATH
, AuthValueOverlay(database
? (uint32_t)strlen(database
) : 0, const_cast<char*>(database
))));
519 if (mPassphraseCheck
)
521 create("builtin", "confirm-access-password");
523 CssmAutoData
data(Allocator::standard(Allocator::sensitive
));
528 AuthItemRef
triesHint(AGENT_HINT_TRIES
, AuthValueOverlay(sizeof(retryCount
), &retryCount
));
529 hints
.erase(triesHint
); hints
.insert(triesHint
); // replace
531 if (retryCount
++ > kMaximumAuthorizationTries
)
533 reason
= SecurityAgent::tooManyTries
;
536 AuthItemRef
retryHint(AGENT_HINT_RETRY_REASON
, AuthValueOverlay(sizeof(reason
), &reason
));
537 hints
.erase(retryHint
); hints
.insert(retryHint
); // replace
539 setInput(hints
, context
);
542 if (retryCount
> kMaximumAuthorizationTries
)
549 AuthItem
*passwordItem
= mOutContext
.find(kAuthorizationEnvironmentPassword
);
553 passwordItem
->getCssmData(data
);
555 while ((reason
= (const_cast<KeychainDatabase
*>(mPassphraseCheck
)->decode(data
) ? SecurityAgent::noReason
: SecurityAgent::invalidPassphrase
)));
559 create("builtin", "confirm-access");
560 setInput(hints
, context
);
571 // Obtain passphrases and submit them to the accept() method until it is accepted
572 // or we can't get another passphrase. Accept() should consume the passphrase
573 // if it is accepted. If no passphrase is acceptable, throw out of here.
575 Reason
QueryOld::query()
577 Reason reason
= SecurityAgent::noReason
;
579 AuthItemSet hints
, context
;
580 CssmAutoData
passphrase(Allocator::standard(Allocator::sensitive
));
583 // prepopulate with client hints
585 const char *keychainPath
= database
.dbName();
586 hints
.insert(AuthItemRef(AGENT_HINT_KEYCHAIN_PATH
, AuthValueOverlay((uint32_t)strlen(keychainPath
), const_cast<char*>(keychainPath
))));
588 hints
.insert(mClientHints
.begin(), mClientHints
.end());
590 create("builtin", "unlock-keychain");
594 AuthItemRef
triesHint(AGENT_HINT_TRIES
, AuthValueOverlay(sizeof(retryCount
), &retryCount
));
595 hints
.erase(triesHint
); hints
.insert(triesHint
); // replace
599 if (retryCount
> maxTries
)
601 reason
= SecurityAgent::tooManyTries
;
604 AuthItemRef
retryHint(AGENT_HINT_RETRY_REASON
, AuthValueOverlay(sizeof(reason
), &reason
));
605 hints
.erase(retryHint
); hints
.insert(retryHint
); // replace
607 setInput(hints
, context
);
610 if (retryCount
> maxTries
)
617 AuthItem
*passwordItem
= mOutContext
.find(kAuthorizationEnvironmentPassword
);
621 passwordItem
->getCssmData(passphrase
);
624 while ((reason
= accept(passphrase
)));
626 return SecurityAgent::noReason
;
631 // Get existing passphrase (unlock) Query
633 Reason
QueryOld::operator () ()
640 // End-classes for old secrets
642 Reason
QueryUnlock::accept(CssmManagedData
&passphrase
)
644 if (safer_cast
<KeychainDatabase
&>(database
).decode(passphrase
))
645 return SecurityAgent::noReason
;
647 return SecurityAgent::invalidPassphrase
;
650 Reason
QueryUnlock::retrievePassword(CssmOwnedData
&passphrase
) {
651 CssmAutoData
pass(Allocator::standard(Allocator::sensitive
));
653 AuthItem
*passwordItem
= mOutContext
.find(kAuthorizationEnvironmentPassword
);
655 return SecurityAgent::invalidPassphrase
;
657 passwordItem
->getCssmData(pass
);
661 return SecurityAgent::noReason
;
664 QueryKeybagPassphrase::QueryKeybagPassphrase(Session
& session
, int32_t tries
) : mSession(session
), mContext(), mRetries(tries
)
666 setTerminateOnSleep(true);
667 mContext
= mSession
.get_current_service_context();
670 Reason
QueryKeybagPassphrase::query()
672 Reason reason
= SecurityAgent::noReason
;
674 AuthItemSet hints
, context
;
675 CssmAutoData
passphrase(Allocator::standard(Allocator::sensitive
));
678 // prepopulate with client hints
680 const char *keychainPath
= "iCloud";
681 hints
.insert(AuthItemRef(AGENT_HINT_KEYCHAIN_PATH
, AuthValueOverlay((uint32_t)strlen(keychainPath
), const_cast<char*>(keychainPath
))));
683 hints
.insert(mClientHints
.begin(), mClientHints
.end());
685 create("builtin", "unlock-keychain");
690 currentTry
= retryCount
;
691 if (retryCount
> mRetries
)
693 return SecurityAgent::tooManyTries
;
697 AuthItemRef
triesHint(AGENT_HINT_TRIES
, AuthValueOverlay(sizeof(currentTry
), ¤tTry
));
698 hints
.erase(triesHint
); hints
.insert(triesHint
); // replace
700 AuthItemRef
retryHint(AGENT_HINT_RETRY_REASON
, AuthValueOverlay(sizeof(reason
), &reason
));
701 hints
.erase(retryHint
); hints
.insert(retryHint
); // replace
703 setInput(hints
, context
);
708 AuthItem
*passwordItem
= mOutContext
.find(kAuthorizationEnvironmentPassword
);
712 passwordItem
->getCssmData(passphrase
);
714 while ((reason
= accept(passphrase
)));
716 return SecurityAgent::noReason
;
719 Reason
QueryKeybagPassphrase::accept(Security::CssmManagedData
& password
)
721 if (service_client_kb_unlock(&mContext
, password
.data(), (int)password
.length()) == 0) {
722 mSession
.keybagSetState(session_keybag_unlocked
);
723 return SecurityAgent::noReason
;
725 return SecurityAgent::invalidPassphrase
;
728 QueryKeybagNewPassphrase::QueryKeybagNewPassphrase(Session
& session
) : QueryKeybagPassphrase(session
) {}
730 Reason
QueryKeybagNewPassphrase::query(CssmOwnedData
&oldPassphrase
, CssmOwnedData
&passphrase
)
732 CssmAutoData
pass(Allocator::standard(Allocator::sensitive
));
733 CssmAutoData
oldPass(Allocator::standard(Allocator::sensitive
));
734 Reason reason
= SecurityAgent::noReason
;
736 AuthItemSet hints
, context
;
739 // prepopulate with client hints
741 const char *keychainPath
= "iCloud";
742 hints
.insert(AuthItemRef(AGENT_HINT_KEYCHAIN_PATH
, AuthValueOverlay((uint32_t)strlen(keychainPath
), const_cast<char*>(keychainPath
))));
744 const char *showResetString
= "YES";
745 hints
.insert(AuthItemRef(AGENT_HINT_SHOW_RESET
, AuthValueOverlay((uint32_t)strlen(showResetString
), const_cast<char*>(showResetString
))));
747 hints
.insert(mClientHints
.begin(), mClientHints
.end());
749 create("builtin", "change-passphrase");
752 AuthItem
*resetPassword
= NULL
;
755 currentTry
= retryCount
;
756 if (retryCount
> mRetries
)
758 return SecurityAgent::tooManyTries
;
762 AuthItemRef
triesHint(AGENT_HINT_TRIES
, AuthValueOverlay(sizeof(currentTry
), ¤tTry
));
763 hints
.erase(triesHint
); hints
.insert(triesHint
); // replace
765 AuthItemRef
retryHint(AGENT_HINT_RETRY_REASON
, AuthValueOverlay(sizeof(reason
), &reason
));
766 hints
.erase(retryHint
); hints
.insert(retryHint
); // replace
768 setInput(hints
, context
);
773 resetPassword
= mOutContext
.find(AGENT_CONTEXT_RESET_PASSWORD
);
774 if (resetPassword
!= NULL
) {
775 return SecurityAgent::resettingPassword
;
778 AuthItem
*oldPasswordItem
= mOutContext
.find(AGENT_PASSWORD
);
779 if (!oldPasswordItem
)
782 oldPasswordItem
->getCssmData(oldPass
);
784 while ((reason
= accept(oldPass
)));
786 if (reason
== SecurityAgent::noReason
) {
787 AuthItem
*passwordItem
= mOutContext
.find(AGENT_CONTEXT_NEW_PASSWORD
);
789 return SecurityAgent::invalidPassphrase
;
791 passwordItem
->getCssmData(pass
);
793 oldPassphrase
= oldPass
;
797 return SecurityAgent::noReason
;
800 QueryPIN::QueryPIN(Database
&db
)
801 : QueryOld(db
), mPin(Allocator::standard())
803 this->inferHints(Server::process());
807 Reason
QueryPIN::accept(CssmManagedData
&pin
)
809 // no retries for now
811 return SecurityAgent::noReason
;
816 // Obtain passphrases and submit them to the accept() method until it is accepted
817 // or we can't get another passphrase. Accept() should consume the passphrase
818 // if it is accepted. If no passphrase is acceptable, throw out of here.
820 Reason
QueryNewPassphrase::query()
822 Reason reason
= initialReason
;
823 CssmAutoData
passphrase(Allocator::standard(Allocator::sensitive
));
824 CssmAutoData
oldPassphrase(Allocator::standard(Allocator::sensitive
));
827 AuthItemSet hints
, context
;
831 // prepopulate with client hints
832 hints
.insert(mClientHints
.begin(), mClientHints
.end());
834 // keychain name into hints
835 hints
.insert(AuthItemRef(AGENT_HINT_KEYCHAIN_PATH
, AuthValueOverlay(database
.dbName())));
837 switch (initialReason
)
839 case SecurityAgent::newDatabase
:
840 create("builtin", "new-passphrase");
842 case SecurityAgent::changePassphrase
:
843 create("builtin", "change-passphrase");
851 AuthItemRef
triesHint(AGENT_HINT_TRIES
, AuthValueOverlay(sizeof(retryCount
), &retryCount
));
852 hints
.erase(triesHint
); hints
.insert(triesHint
); // replace
854 if (++retryCount
> maxTries
)
856 reason
= SecurityAgent::tooManyTries
;
859 AuthItemRef
retryHint(AGENT_HINT_RETRY_REASON
, AuthValueOverlay(sizeof(reason
), &reason
));
860 hints
.erase(retryHint
); hints
.insert(retryHint
); // replace
862 setInput(hints
, context
);
865 if (retryCount
> maxTries
)
872 if (SecurityAgent::changePassphrase
== initialReason
)
874 AuthItem
*oldPasswordItem
= mOutContext
.find(AGENT_PASSWORD
);
875 if (!oldPasswordItem
)
878 oldPasswordItem
->getCssmData(oldPassphrase
);
881 AuthItem
*passwordItem
= mOutContext
.find(AGENT_CONTEXT_NEW_PASSWORD
);
885 passwordItem
->getCssmData(passphrase
);
888 while ((reason
= accept(passphrase
, (initialReason
== SecurityAgent::changePassphrase
) ? &oldPassphrase
.get() : NULL
)));
890 return SecurityAgent::noReason
;
895 // Get new passphrase Query
897 Reason
QueryNewPassphrase::operator () (CssmOwnedData
&oldPassphrase
, CssmOwnedData
&passphrase
)
899 if (Reason result
= query())
900 return result
; // failed
901 passphrase
= mPassphrase
;
902 oldPassphrase
= mOldPassphrase
;
903 return SecurityAgent::noReason
; // success
906 Reason
QueryNewPassphrase::accept(CssmManagedData
&passphrase
, CssmData
*oldPassphrase
)
908 //@@@ acceptance criteria are currently hardwired here
909 //@@@ This validation presumes ASCII - UTF8 might be more lenient
911 // if we have an old passphrase, check it
912 if (oldPassphrase
&& !safer_cast
<KeychainDatabase
&>(database
).validatePassphrase(*oldPassphrase
))
913 return SecurityAgent::oldPassphraseWrong
;
915 // sanity check the new passphrase (but allow user override)
916 if (!(mPassphraseValid
&& passphrase
.get() == mPassphrase
)) {
917 mPassphrase
= passphrase
;
918 if (oldPassphrase
) mOldPassphrase
= *oldPassphrase
;
919 mPassphraseValid
= true;
920 if (mPassphrase
.length() == 0)
921 return SecurityAgent::passphraseIsNull
;
922 if (mPassphrase
.length() < 6)
923 return SecurityAgent::passphraseTooSimple
;
927 return SecurityAgent::noReason
;
931 // Get a passphrase for unspecified use
933 Reason
QueryGenericPassphrase::operator () (const CssmData
*prompt
, bool verify
,
936 return query(prompt
, verify
, passphrase
);
939 Reason
QueryGenericPassphrase::query(const CssmData
*prompt
, bool verify
,
942 Reason reason
= SecurityAgent::noReason
;
943 OSStatus status
; // not really used; remove?
944 AuthItemSet hints
, context
;
946 hints
.insert(mClientHints
.begin(), mClientHints
.end());
947 hints
.insert(AuthItemRef(AGENT_HINT_CUSTOM_PROMPT
, AuthValueOverlay(prompt
? (UInt32
)prompt
->length() : 0, prompt
? prompt
->data() : NULL
)));
948 // XXX/gh defined by dmitch but no analogous hint in
949 // AuthorizationTagsPriv.h:
950 // CSSM_ATTRIBUTE_ALERT_TITLE (optional alert panel title)
952 if (false == verify
) { // import
953 create("builtin", "generic-unlock");
954 } else { // verify passphrase (export)
955 create("builtin", "generic-new-passphrase");
958 AuthItem
*passwordItem
;
961 setInput(hints
, context
);
964 passwordItem
= mOutContext
.find(AGENT_PASSWORD
);
966 } while (!passwordItem
);
968 passwordItem
->getString(passphrase
);
975 // Get a DB blob's passphrase--keychain synchronization
977 Reason
QueryDBBlobSecret::operator () (DbHandle
*dbHandleArray
, uint8 dbHandleArrayCount
, DbHandle
*dbHandleAuthenticated
)
979 return query(dbHandleArray
, dbHandleArrayCount
, dbHandleAuthenticated
);
982 Reason
QueryDBBlobSecret::query(DbHandle
*dbHandleArray
, uint8 dbHandleArrayCount
, DbHandle
*dbHandleAuthenticated
)
984 Reason reason
= SecurityAgent::noReason
;
985 CssmAutoData
passphrase(Allocator::standard(Allocator::sensitive
));
986 OSStatus status
; // not really used; remove?
987 AuthItemSet hints
/*NUKEME*/, context
;
989 hints
.insert(mClientHints
.begin(), mClientHints
.end());
990 create("builtin", "generic-unlock-kcblob");
992 AuthItem
*secretItem
;
997 AuthItemRef
triesHint(AGENT_HINT_TRIES
, AuthValueOverlay(sizeof(retryCount
), &retryCount
));
998 hints
.erase(triesHint
); hints
.insert(triesHint
); // replace
1000 if (++retryCount
> maxTries
)
1002 reason
= SecurityAgent::tooManyTries
;
1005 AuthItemRef
retryHint(AGENT_HINT_RETRY_REASON
, AuthValueOverlay(sizeof(reason
), &reason
));
1006 hints
.erase(retryHint
); hints
.insert(retryHint
); // replace
1008 setInput(hints
, context
);
1011 secretItem
= mOutContext
.find(AGENT_PASSWORD
);
1014 secretItem
->getCssmData(passphrase
);
1016 } while ((reason
= accept(passphrase
, dbHandleArray
, dbHandleArrayCount
, dbHandleAuthenticated
)));
1021 Reason
QueryDBBlobSecret::accept(CssmManagedData
&passphrase
,
1022 DbHandle
*dbHandlesToAuthenticate
, uint8 dbHandleCount
, DbHandle
*dbHandleAuthenticated
)
1024 DbHandle
*currHdl
= dbHandlesToAuthenticate
;
1026 Boolean authenticated
= false;
1027 for (index
=0; index
< dbHandleCount
&& !authenticated
; index
++)
1031 RefPointer
<KeychainDatabase
> dbToUnlock
= Server::keychain(*currHdl
);
1032 dbToUnlock
->unlockDb(passphrase
, false);
1033 authenticated
= true;
1034 *dbHandleAuthenticated
= *currHdl
; // return the DbHandle that 'passphrase' authenticated with.
1036 catch (const CommonError
&err
)
1038 currHdl
++; // we failed to authenticate with this one, onto the next one.
1041 if ( !authenticated
)
1042 return SecurityAgent::invalidPassphrase
;
1044 return SecurityAgent::noReason
;
1047 // @@@ no pluggable authentication possible!
1049 QueryKeychainAuth::operator () (const char *database
, const char *description
, AclAuthorization action
, const char *prompt
)
1051 Reason reason
= SecurityAgent::noReason
;
1052 AuthItemSet hints
, context
;
1057 using CommonCriteria::Securityd::KeychainAuthLogger
;
1058 KeychainAuthLogger
logger(mAuditToken
, AUE_ssauthint
, database
, description
);
1060 hints
.insert(mClientHints
.begin(), mClientHints
.end());
1062 // put action/operation (sint32) into hints
1063 hints
.insert(AuthItemRef(AGENT_HINT_ACL_TAG
, AuthValueOverlay(sizeof(action
), static_cast<sint32
*>(&action
))));
1065 hints
.insert(AuthItemRef(AGENT_HINT_CUSTOM_PROMPT
, AuthValueOverlay(prompt
? (uint32_t)strlen(prompt
) : 0, const_cast<char*>(prompt
))));
1067 // item name into hints
1068 hints
.insert(AuthItemRef(AGENT_HINT_KEYCHAIN_ITEM_NAME
, AuthValueOverlay(description
? (uint32_t)strlen(description
) : 0, const_cast<char*>(description
))));
1070 // keychain name into hints
1071 hints
.insert(AuthItemRef(AGENT_HINT_KEYCHAIN_PATH
, AuthValueOverlay(database
? (uint32_t)strlen(database
) : 0, const_cast<char*>(database
))));
1073 create("builtin", "confirm-access-user-password");
1075 AuthItem
*usernameItem
;
1076 AuthItem
*passwordItem
;
1080 AuthItemRef
triesHint(AGENT_HINT_TRIES
, AuthValueOverlay(sizeof(retryCount
), &retryCount
));
1081 hints
.erase(triesHint
); hints
.insert(triesHint
); // replace
1083 if (++retryCount
> maxTries
)
1084 reason
= SecurityAgent::tooManyTries
;
1086 if (SecurityAgent::noReason
!= reason
)
1088 if (SecurityAgent::tooManyTries
== reason
)
1089 logger
.logFailure(NULL
, CommonCriteria::errTooManyTries
);
1091 logger
.logFailure();
1094 AuthItemRef
retryHint(AGENT_HINT_RETRY_REASON
, AuthValueOverlay(sizeof(reason
), &reason
));
1095 hints
.erase(retryHint
); hints
.insert(retryHint
); // replace
1097 setInput(hints
, context
);
1103 catch (...) // user probably clicked "deny"
1105 logger
.logFailure();
1108 usernameItem
= mOutContext
.find(AGENT_USERNAME
);
1109 passwordItem
= mOutContext
.find(AGENT_PASSWORD
);
1110 if (!usernameItem
|| !passwordItem
)
1112 usernameItem
->getString(username
);
1113 passwordItem
->getString(password
);
1114 } while ((reason
= accept(username
, password
)));
1116 if (SecurityAgent::noReason
== reason
)
1117 logger
.logSuccess();
1118 // else we logged the denial in the loop
1124 QueryKeychainAuth::accept(string
&username
, string
&passphrase
)
1126 // Note: QueryKeychainAuth currently requires that the
1127 // specified user be in the admin group. If this requirement
1128 // ever needs to change, the group name should be passed as
1129 // a separate argument to this method.
1131 const char *user
= username
.c_str();
1132 const char *passwd
= passphrase
.c_str();
1133 int checkpw_status
= checkpw(user
, passwd
);
1135 if (checkpw_status
!= CHECKPW_SUCCESS
) {
1136 return SecurityAgent::invalidPassphrase
;
1139 const char *group
= "admin";
1142 uuid_t group_uuid
, user_uuid
;
1143 rc
= mbr_group_name_to_uuid(group
, group_uuid
);
1144 if (rc
) { return SecurityAgent::userNotInGroup
; }
1146 rc
= mbr_user_name_to_uuid(user
, user_uuid
);
1147 if (rc
) { return SecurityAgent::userNotInGroup
; }
1149 rc
= mbr_check_membership(user_uuid
, group_uuid
, &ismember
);
1150 if (rc
|| !ismember
) { return SecurityAgent::userNotInGroup
; }
1153 return SecurityAgent::noReason
;