]> git.saurik.com Git - apple/security.git/blob - securityd/src/agentquery.cpp
Security-58286.1.32.tar.gz
[apple/security.git] / securityd / src / agentquery.cpp
1 /*
2 * Copyright (c) 2000-2015 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24 //
25 // passphrases - canonical code to obtain passphrases
26 //
27 #define __STDC_WANT_LIB_EXT1__ 1
28 #include <string.h>
29
30 #include "agentquery.h"
31 #include "ccaudit_extensions.h"
32
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>
44 #include <stdlib.h>
45 #include <xpc/xpc.h>
46 #include <xpc/private.h>
47 #include "securityd_service/securityd_service/securityd_service_client.h"
48
49 #define SECURITYAGENT_BOOTSTRAP_NAME_BASE "com.apple.security.agent"
50 #define SECURITYAGENT_LOGINWINDOW_BOOTSTRAP_NAME_BASE "com.apple.security.agent.login"
51
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"
57
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"
77
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))) }
80
81
82 // SecurityAgentXPCConnection
83
84 SecurityAgentXPCConnection::SecurityAgentXPCConnection(Session &session)
85 : mHostInstance(session.authhost()),
86 mSession(session),
87 mConnection(&Server::connection()),
88 mAuditToken(Server::connection().auditToken())
89 {
90 // this may take a while
91 Server::active().longTermActivity();
92 secnotice("SecurityAgentConnection", "new SecurityAgentConnection(%p)", this);
93 mXPCConnection = NULL;
94 mNobodyUID = -2;
95 struct passwd *pw = getpwnam("nobody");
96 if (NULL != pw) {
97 mNobodyUID = pw->pw_uid;
98 }
99 }
100
101 SecurityAgentXPCConnection::~SecurityAgentXPCConnection()
102 {
103 secnotice("SecurityAgentConnection", "SecurityAgentConnection(%p) dying", this);
104 mConnection->useAgent(NULL);
105
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);
111
112 // Then release the XPC connection
113 xpc_release(mXPCConnection);
114 mXPCConnection = NULL;
115 }
116 }
117
118 bool SecurityAgentXPCConnection::inDarkWake()
119 {
120 return mSession.server().inDarkWake();
121 }
122
123 void
124 SecurityAgentXPCConnection::activate(bool ignoreUid)
125 {
126 secnotice("SecurityAgentConnection", "activate(%p)", this);
127
128 mConnection->useAgent(this);
129 if (mXPCConnection != NULL) {
130 // If we already have an XPC connection, there's nothing to do.
131 return;
132 }
133
134 try {
135 uuid_t sessionUUID = UUID_INITIALIZER_FROM_SESSIONID(mSession.sessionId());
136
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);
140 if (inDarkWake())
141 CssmError::throwMe(CSSM_ERRCODE_IN_DARK_WAKE);
142 uid_t targetUid = mHostInstance->session().originatorUid();
143
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");
149 } else {
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");
153 }
154
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));
158 }
159 });
160 xpc_connection_resume(mXPCConnection);
161 secnotice("SecurityAgentXPCConnection", "%p activated", this);
162 }
163 catch (MacOSError &err) {
164 mConnection->useAgent(NULL); // guess not
165 Syslog::error("SecurityAgentConnection: error activating SecurityAgent instance %p", this);
166 throw;
167 }
168
169 secnotice("SecurityAgentXPCConnection", "contact didn't throw (%p)", this);
170 }
171
172 void
173 SecurityAgentXPCConnection::terminate()
174 {
175 activate(false);
176
177 // @@@ This happens already in the destructor; presumably we do this to tear things down orderly
178 mConnection->useAgent(NULL);
179 }
180
181
182 using SecurityAgent::Reason;
183 using namespace Authorization;
184
185 ModuleNexus<RecursiveMutex> gAllXPCClientsMutex;
186 ModuleNexus<set<SecurityAgentXPCQuery*> > allXPCClients;
187
188 void
189 SecurityAgentXPCQuery::killAllXPCClients()
190 {
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());
193
194 set<SecurityAgentXPCQuery*>::iterator clientIterator = allXPCClients().begin();
195 while (clientIterator != allXPCClients().end())
196 {
197 set<SecurityAgentXPCQuery*>::iterator thisClient = clientIterator++;
198 if ((*thisClient)->getTerminateOnSleep())
199 {
200 (*thisClient)->terminate();
201 }
202 }
203 }
204
205
206 SecurityAgentXPCQuery::SecurityAgentXPCQuery(Session &session)
207 : SecurityAgentXPCConnection(session), mAgentConnected(false), mTerminateOnSleep(false)
208 {
209 secnotice("SecurityAgentXPCQuery", "new SecurityAgentXPCQuery(%p)", this);
210 }
211
212 SecurityAgentXPCQuery::~SecurityAgentXPCQuery()
213 {
214 secnotice("SecurityAgentXPCQuery", "SecurityAgentXPCQuery(%p) dying", this);
215 if (mAgentConnected) {
216 this->disconnect();
217 }
218 }
219
220 void
221 SecurityAgentXPCQuery::inferHints(Process &thisProcess)
222 {
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;
229
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)));
234
235 /*
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.
239 */
240
241 if (guestPath == "/System/Library/CoreServices/loginwindow.app") {
242 clientHints.insert(AuthItemRef(AGENT_HINT_IGNORE_SESSION, AuthValueOverlay(sizeof(ignoreSession), &ignoreSession)));
243 }
244
245 mClientHints.insert(clientHints.begin(), clientHints.end());
246
247 bool validSignature = thisProcess.checkAppleSigned();
248 AuthItemSet clientImmutableHints;
249
250 clientImmutableHints.insert(AuthItemRef(AGENT_HINT_CLIENT_SIGNED, AuthValueOverlay(sizeof(validSignature), &validSignature)));
251
252 mImmutableHints.insert(clientImmutableHints.begin(), clientImmutableHints.end());
253 }
254
255 void SecurityAgentXPCQuery::addHint(const char *name, const void *value, UInt32 valueLen, UInt32 flags)
256 {
257 AuthorizationItem item = { name, valueLen, const_cast<void *>(value), flags };
258 mClientHints.insert(AuthItemRef(item));
259 }
260
261
262 void
263 SecurityAgentXPCQuery::readChoice()
264 {
265 allow = false;
266 remember = false;
267
268 AuthItem *allowAction = mOutContext.find(AGENT_CONTEXT_ALLOW);
269 if (allowAction)
270 {
271 string allowString;
272 if (allowAction->getString(allowString)
273 && (allowString == "YES"))
274 allow = true;
275 }
276
277 AuthItem *rememberAction = mOutContext.find(AGENT_CONTEXT_REMEMBER_ACTION);
278 if (rememberAction)
279 {
280 string rememberString;
281 if (rememberAction->getString(rememberString)
282 && (rememberString == "YES"))
283 remember = true;
284 }
285 }
286
287 void
288 SecurityAgentXPCQuery::disconnect()
289 {
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);
295 }
296
297 StLock<Mutex> _(gAllXPCClientsMutex());
298 allXPCClients().erase(this);
299 }
300
301 void
302 SecurityAgentXPCQuery::terminate()
303 {
304 this->disconnect();
305 }
306
307 static void xpcArrayToAuthItemSet(AuthItemSet *setToBuild, xpc_object_t input) {
308 setToBuild->clear();
309
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);
312
313 size_t length;
314 const void *data = xpc_dictionary_get_data(item, AUTH_XPC_ITEM_VALUE, &length);
315 void *dataCopy = 0;
316
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);
319 if (sensitive) {
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;
325 } else {
326 dataCopy = malloc(length);
327 memcpy(dataCopy, data, length);
328 }
329
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.
334 free(dataCopy);
335 return true;
336 });
337 }
338
339 void
340 SecurityAgentXPCQuery::create(const char *pluginId, const char *mechanismId)
341 {
342 bool ignoreUid = false;
343
344 do {
345 activate(ignoreUid);
346
347 mAgentConnected = false;
348
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);
353
354 uid_t targetUid = Server::process().uid();
355 bool doSwitchAudit = (ignoreUid || targetUid == 0 || targetUid == mNobodyUID);
356 bool doSwitchBootstrap = (ignoreUid || targetUid == 0 || targetUid == mNobodyUID);
357
358 if (doSwitchAudit) {
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");
365 }
366 }
367 }
368
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);
373 }
374
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;
382 } else {
383 secnotice("SecurityAgentXPCQuery", "plugin create failed in SecurityAgent");
384 MacOSError::throwMe(errAuthorizationInternal);
385 }
386 }
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
390 if (ignoreUid) {
391 secnotice("SecurityAgentXPCQuery", "failed to establish connection, no retries left");
392 xpc_release(object);
393 MacOSError::throwMe(errAuthorizationInternal);
394 } else {
395 secnotice("SecurityAgentXPCQuery", "failed to establish connection, retrying with no UID");
396 ignoreUid = true;
397 xpc_release(mXPCConnection);
398 mXPCConnection = NULL;
399 }
400 } else if (XPC_ERROR_CONNECTION_INTERRUPTED == object) {
401 // If we get an error before getting the create response, try again
402 }
403 }
404 xpc_release(object);
405 xpc_release(requestObject);
406 } while (!mAgentConnected);
407
408 StLock<Mutex> _(gAllXPCClientsMutex());
409 allXPCClients().insert(this);
410 }
411
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;
416
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);
422 }
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);
426 }
427 return outputArray;
428 }
429
430 void
431 SecurityAgentXPCQuery::invoke() {
432 xpc_object_t hintsArray = authItemSetToXPCArray(mInHints);
433 xpc_object_t contextArray = authItemSetToXPCArray(mInContext);
434 xpc_object_t immutableHintsArray = authItemSetToXPCArray(mImmutableHints);
435
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);
441
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);
454 }
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
460 }
461 }
462 xpc_release(object);
463
464 xpc_release(hintsArray);
465 xpc_release(contextArray);
466 xpc_release(immutableHintsArray);
467 xpc_release(requestObject);
468 }
469
470 void SecurityAgentXPCQuery::checkResult()
471 {
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);
478 }
479 }
480
481 //
482 // Perform the "rogue app" access query dialog
483 //
484 QueryKeychainUse::QueryKeychainUse(bool needPass, const Database *db)
485 : mPassphraseCheck(NULL)
486 {
487 // if passphrase checking requested, save KeychainDatabase reference
488 // (will quietly disable check if db isn't a keychain)
489 if (needPass)
490 mPassphraseCheck = dynamic_cast<const KeychainDatabase *>(db);
491
492 setTerminateOnSleep(true);
493 }
494
495 Reason QueryKeychainUse::queryUser (const char *database, const char *description, AclAuthorization action)
496 {
497 Reason reason = SecurityAgent::noReason;
498 uint32_t retryCount = 0;
499 AuthItemSet hints, context;
500
501 // prepopulate with client hints
502 hints.insert(mClientHints.begin(), mClientHints.end());
503
504 // put action/operation (sint32) into hints
505 hints.insert(AuthItemRef(AGENT_HINT_ACL_TAG, AuthValueOverlay(sizeof(action), static_cast<sint32*>(&action))));
506
507 // item name into hints
508
509 hints.insert(AuthItemRef(AGENT_HINT_KEYCHAIN_ITEM_NAME, AuthValueOverlay(description ? (uint32_t)strlen(description) : 0, const_cast<char*>(description))));
510
511 // keychain name into hints
512 hints.insert(AuthItemRef(AGENT_HINT_KEYCHAIN_PATH, AuthValueOverlay(database ? (uint32_t)strlen(database) : 0, const_cast<char*>(database))));
513
514 if (mPassphraseCheck)
515 {
516 create("builtin", "confirm-access-password");
517
518 CssmAutoData data(Allocator::standard(Allocator::sensitive));
519
520 do
521 {
522
523 AuthItemRef triesHint(AGENT_HINT_TRIES, AuthValueOverlay(sizeof(retryCount), &retryCount));
524 hints.erase(triesHint); hints.insert(triesHint); // replace
525
526 if (retryCount++ > kMaximumAuthorizationTries)
527 {
528 reason = SecurityAgent::tooManyTries;
529 }
530
531 AuthItemRef retryHint(AGENT_HINT_RETRY_REASON, AuthValueOverlay(sizeof(reason), &reason));
532 hints.erase(retryHint); hints.insert(retryHint); // replace
533
534 setInput(hints, context);
535 invoke();
536
537 if (retryCount > kMaximumAuthorizationTries)
538 {
539 return reason;
540 }
541
542 checkResult();
543
544 AuthItem *passwordItem = mOutContext.find(kAuthorizationEnvironmentPassword);
545 if (!passwordItem)
546 continue;
547
548 passwordItem->getCssmData(data);
549 }
550 while ((reason = (const_cast<KeychainDatabase*>(mPassphraseCheck)->decode(data) ? SecurityAgent::noReason : SecurityAgent::invalidPassphrase)));
551 }
552 else
553 {
554 create("builtin", "confirm-access");
555 setInput(hints, context);
556 invoke();
557 }
558
559 readChoice();
560
561 return reason;
562 }
563
564
565 //
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.
569 //
570 Reason QueryOld::query()
571 {
572 Reason reason = SecurityAgent::noReason;
573 AuthItemSet hints, context;
574 CssmAutoData passphrase(Allocator::standard(Allocator::sensitive));
575 int retryCount = 0;
576
577 // prepopulate with client hints
578
579 const char *keychainPath = database.dbName();
580 hints.insert(AuthItemRef(AGENT_HINT_KEYCHAIN_PATH, AuthValueOverlay((uint32_t)strlen(keychainPath), const_cast<char*>(keychainPath))));
581
582 hints.insert(mClientHints.begin(), mClientHints.end());
583
584 create("builtin", "unlock-keychain");
585
586 do
587 {
588 AuthItemRef triesHint(AGENT_HINT_TRIES, AuthValueOverlay(sizeof(retryCount), &retryCount));
589 hints.erase(triesHint); hints.insert(triesHint); // replace
590
591 ++retryCount;
592
593 if (retryCount > maxTries)
594 {
595 reason = SecurityAgent::tooManyTries;
596 }
597
598 AuthItemRef retryHint(AGENT_HINT_RETRY_REASON, AuthValueOverlay(sizeof(reason), &reason));
599 hints.erase(retryHint); hints.insert(retryHint); // replace
600
601 setInput(hints, context);
602 invoke();
603
604 if (retryCount > maxTries)
605 {
606 return reason;
607 }
608
609 checkResult();
610
611 AuthItem *passwordItem = mOutContext.find(kAuthorizationEnvironmentPassword);
612 if (!passwordItem)
613 continue;
614
615 passwordItem->getCssmData(passphrase);
616
617 }
618 while ((reason = accept(passphrase)));
619
620 return SecurityAgent::noReason;
621 }
622
623
624 //
625 // Get existing passphrase (unlock) Query
626 //
627 Reason QueryOld::operator () ()
628 {
629 return query();
630 }
631
632
633 //
634 // End-classes for old secrets
635 //
636 Reason QueryUnlock::accept(CssmManagedData &passphrase)
637 {
638 if (safer_cast<KeychainDatabase &>(database).decode(passphrase))
639 return SecurityAgent::noReason;
640 else
641 return SecurityAgent::invalidPassphrase;
642 }
643
644 Reason QueryUnlock::retrievePassword(CssmOwnedData &passphrase) {
645 CssmAutoData pass(Allocator::standard(Allocator::sensitive));
646
647 AuthItem *passwordItem = mOutContext.find(kAuthorizationEnvironmentPassword);
648 if (!passwordItem)
649 return SecurityAgent::invalidPassphrase;
650
651 passwordItem->getCssmData(pass);
652
653 passphrase = pass;
654
655 return SecurityAgent::noReason;
656 }
657
658 QueryKeybagPassphrase::QueryKeybagPassphrase(Session & session, int32_t tries) : mSession(session), mContext(), mRetries(tries)
659 {
660 setTerminateOnSleep(true);
661 mContext = mSession.get_current_service_context();
662 }
663
664 Reason QueryKeybagPassphrase::query()
665 {
666 Reason reason = SecurityAgent::noReason;
667 AuthItemSet hints, context;
668 CssmAutoData passphrase(Allocator::standard(Allocator::sensitive));
669 int retryCount = 0;
670
671 // prepopulate with client hints
672
673 const char *keychainPath = "iCloud";
674 hints.insert(AuthItemRef(AGENT_HINT_KEYCHAIN_PATH, AuthValueOverlay((uint32_t)strlen(keychainPath), const_cast<char*>(keychainPath))));
675
676 hints.insert(mClientHints.begin(), mClientHints.end());
677
678 create("builtin", "unlock-keychain");
679
680 int currentTry = 0;
681 do
682 {
683 currentTry = retryCount;
684 if (retryCount > mRetries)
685 {
686 return SecurityAgent::tooManyTries;
687 }
688 retryCount++;
689
690 AuthItemRef triesHint(AGENT_HINT_TRIES, AuthValueOverlay(sizeof(currentTry), &currentTry));
691 hints.erase(triesHint); hints.insert(triesHint); // replace
692
693 AuthItemRef retryHint(AGENT_HINT_RETRY_REASON, AuthValueOverlay(sizeof(reason), &reason));
694 hints.erase(retryHint); hints.insert(retryHint); // replace
695
696 setInput(hints, context);
697 invoke();
698
699 checkResult();
700
701 AuthItem *passwordItem = mOutContext.find(kAuthorizationEnvironmentPassword);
702 if (!passwordItem)
703 continue;
704
705 passwordItem->getCssmData(passphrase);
706 }
707 while ((reason = accept(passphrase)));
708
709 return SecurityAgent::noReason;
710 }
711
712 Reason QueryKeybagPassphrase::accept(Security::CssmManagedData & password)
713 {
714 if (service_client_kb_unlock(&mContext, password.data(), (int)password.length()) == 0) {
715 mSession.keybagSetState(session_keybag_unlocked);
716 return SecurityAgent::noReason;
717 } else
718 return SecurityAgent::invalidPassphrase;
719 }
720
721 QueryKeybagNewPassphrase::QueryKeybagNewPassphrase(Session & session) : QueryKeybagPassphrase(session) {}
722
723 Reason QueryKeybagNewPassphrase::query(CssmOwnedData &oldPassphrase, CssmOwnedData &passphrase)
724 {
725 CssmAutoData pass(Allocator::standard(Allocator::sensitive));
726 CssmAutoData oldPass(Allocator::standard(Allocator::sensitive));
727 Reason reason = SecurityAgent::noReason;
728 AuthItemSet hints, context;
729 int retryCount = 0;
730
731 // prepopulate with client hints
732
733 const char *keychainPath = "iCloud";
734 hints.insert(AuthItemRef(AGENT_HINT_KEYCHAIN_PATH, AuthValueOverlay((uint32_t)strlen(keychainPath), const_cast<char*>(keychainPath))));
735
736 const char *showResetString = "YES";
737 hints.insert(AuthItemRef(AGENT_HINT_SHOW_RESET, AuthValueOverlay((uint32_t)strlen(showResetString), const_cast<char*>(showResetString))));
738
739 hints.insert(mClientHints.begin(), mClientHints.end());
740
741 create("builtin", "change-passphrase");
742
743 int currentTry = 0;
744 AuthItem *resetPassword = NULL;
745 do
746 {
747 currentTry = retryCount;
748 if (retryCount > mRetries)
749 {
750 return SecurityAgent::tooManyTries;
751 }
752 retryCount++;
753
754 AuthItemRef triesHint(AGENT_HINT_TRIES, AuthValueOverlay(sizeof(currentTry), &currentTry));
755 hints.erase(triesHint); hints.insert(triesHint); // replace
756
757 AuthItemRef retryHint(AGENT_HINT_RETRY_REASON, AuthValueOverlay(sizeof(reason), &reason));
758 hints.erase(retryHint); hints.insert(retryHint); // replace
759
760 setInput(hints, context);
761 invoke();
762
763 checkResult();
764
765 resetPassword = mOutContext.find(AGENT_CONTEXT_RESET_PASSWORD);
766 if (resetPassword != NULL) {
767 return SecurityAgent::resettingPassword;
768 }
769
770 AuthItem *oldPasswordItem = mOutContext.find(AGENT_PASSWORD);
771 if (!oldPasswordItem)
772 continue;
773
774 oldPasswordItem->getCssmData(oldPass);
775 }
776 while ((reason = accept(oldPass)));
777
778 if (reason == SecurityAgent::noReason) {
779 AuthItem *passwordItem = mOutContext.find(AGENT_CONTEXT_NEW_PASSWORD);
780 if (!passwordItem)
781 return SecurityAgent::invalidPassphrase;
782
783 passwordItem->getCssmData(pass);
784
785 oldPassphrase = oldPass;
786 passphrase = pass;
787 }
788
789 return SecurityAgent::noReason;
790 }
791
792 QueryPIN::QueryPIN(Database &db)
793 : QueryOld(db), mPin(Allocator::standard())
794 {
795 this->inferHints(Server::process());
796 }
797
798
799 Reason QueryPIN::accept(CssmManagedData &pin)
800 {
801 // no retries for now
802 mPin = pin;
803 return SecurityAgent::noReason;
804 }
805
806
807 //
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.
811 //
812 Reason QueryNewPassphrase::query()
813 {
814 Reason reason = initialReason;
815 CssmAutoData passphrase(Allocator::standard(Allocator::sensitive));
816 CssmAutoData oldPassphrase(Allocator::standard(Allocator::sensitive));
817
818 AuthItemSet hints, context;
819
820 int retryCount = 0;
821
822 // prepopulate with client hints
823 hints.insert(mClientHints.begin(), mClientHints.end());
824
825 // keychain name into hints
826 hints.insert(AuthItemRef(AGENT_HINT_KEYCHAIN_PATH, AuthValueOverlay(database.dbName())));
827
828 switch (initialReason)
829 {
830 case SecurityAgent::newDatabase:
831 create("builtin", "new-passphrase");
832 break;
833 case SecurityAgent::changePassphrase:
834 create("builtin", "change-passphrase");
835 break;
836 default:
837 assert(false);
838 }
839
840 do
841 {
842 AuthItemRef triesHint(AGENT_HINT_TRIES, AuthValueOverlay(sizeof(retryCount), &retryCount));
843 hints.erase(triesHint); hints.insert(triesHint); // replace
844
845 if (++retryCount > maxTries)
846 {
847 reason = SecurityAgent::tooManyTries;
848 }
849
850 AuthItemRef retryHint(AGENT_HINT_RETRY_REASON, AuthValueOverlay(sizeof(reason), &reason));
851 hints.erase(retryHint); hints.insert(retryHint); // replace
852
853 setInput(hints, context);
854 invoke();
855
856 if (retryCount > maxTries)
857 {
858 return reason;
859 }
860
861 checkResult();
862
863 if (SecurityAgent::changePassphrase == initialReason)
864 {
865 AuthItem *oldPasswordItem = mOutContext.find(AGENT_PASSWORD);
866 if (!oldPasswordItem)
867 continue;
868
869 oldPasswordItem->getCssmData(oldPassphrase);
870 }
871
872 AuthItem *passwordItem = mOutContext.find(AGENT_CONTEXT_NEW_PASSWORD);
873 if (!passwordItem)
874 continue;
875
876 passwordItem->getCssmData(passphrase);
877
878 }
879 while ((reason = accept(passphrase, (initialReason == SecurityAgent::changePassphrase) ? &oldPassphrase.get() : NULL)));
880
881 return SecurityAgent::noReason;
882 }
883
884
885 //
886 // Get new passphrase Query
887 //
888 Reason QueryNewPassphrase::operator () (CssmOwnedData &oldPassphrase, CssmOwnedData &passphrase)
889 {
890 if (Reason result = query())
891 return result; // failed
892 passphrase = mPassphrase;
893 oldPassphrase = mOldPassphrase;
894 return SecurityAgent::noReason; // success
895 }
896
897 Reason QueryNewPassphrase::accept(CssmManagedData &passphrase, CssmData *oldPassphrase)
898 {
899 //@@@ acceptance criteria are currently hardwired here
900 //@@@ This validation presumes ASCII - UTF8 might be more lenient
901
902 // if we have an old passphrase, check it
903 if (oldPassphrase && !safer_cast<KeychainDatabase&>(database).validatePassphrase(*oldPassphrase))
904 return SecurityAgent::oldPassphraseWrong;
905
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;
915 }
916
917 // accept this
918 return SecurityAgent::noReason;
919 }
920
921 //
922 // Get a passphrase for unspecified use
923 //
924 Reason QueryGenericPassphrase::operator () (const CssmData *prompt, bool verify,
925 string &passphrase)
926 {
927 return query(prompt, verify, passphrase);
928 }
929
930 Reason QueryGenericPassphrase::query(const CssmData *prompt, bool verify,
931 string &passphrase)
932 {
933 Reason reason = SecurityAgent::noReason;
934 AuthItemSet hints, context;
935
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)
941
942 if (false == verify) { // import
943 create("builtin", "generic-unlock");
944 } else { // verify passphrase (export)
945 create("builtin", "generic-new-passphrase");
946 }
947
948 AuthItem *passwordItem;
949
950 do {
951 setInput(hints, context);
952 invoke();
953 checkResult();
954 passwordItem = mOutContext.find(AGENT_PASSWORD);
955
956 } while (!passwordItem);
957
958 passwordItem->getString(passphrase);
959
960 return reason;
961 }
962
963
964 //
965 // Get a DB blob's passphrase--keychain synchronization
966 //
967 Reason QueryDBBlobSecret::operator () (DbHandle *dbHandleArray, uint8 dbHandleArrayCount, DbHandle *dbHandleAuthenticated)
968 {
969 return query(dbHandleArray, dbHandleArrayCount, dbHandleAuthenticated);
970 }
971
972 Reason QueryDBBlobSecret::query(DbHandle *dbHandleArray, uint8 dbHandleArrayCount, DbHandle *dbHandleAuthenticated)
973 {
974 Reason reason = SecurityAgent::noReason;
975 CssmAutoData passphrase(Allocator::standard(Allocator::sensitive));
976 AuthItemSet hints/*NUKEME*/, context;
977
978 hints.insert(mClientHints.begin(), mClientHints.end());
979 create("builtin", "generic-unlock-kcblob");
980
981 AuthItem *secretItem;
982
983 int retryCount = 0;
984
985 do {
986 AuthItemRef triesHint(AGENT_HINT_TRIES, AuthValueOverlay(sizeof(retryCount), &retryCount));
987 hints.erase(triesHint); hints.insert(triesHint); // replace
988
989 if (++retryCount > maxTries)
990 {
991 reason = SecurityAgent::tooManyTries;
992 }
993
994 AuthItemRef retryHint(AGENT_HINT_RETRY_REASON, AuthValueOverlay(sizeof(reason), &reason));
995 hints.erase(retryHint); hints.insert(retryHint); // replace
996
997 setInput(hints, context);
998 invoke();
999 checkResult();
1000 secretItem = mOutContext.find(AGENT_PASSWORD);
1001 if (!secretItem)
1002 continue;
1003 secretItem->getCssmData(passphrase);
1004
1005 } while ((reason = accept(passphrase, dbHandleArray, dbHandleArrayCount, dbHandleAuthenticated)));
1006
1007 return reason;
1008 }
1009
1010 Reason QueryDBBlobSecret::accept(CssmManagedData &passphrase,
1011 DbHandle *dbHandlesToAuthenticate, uint8 dbHandleCount, DbHandle *dbHandleAuthenticated)
1012 {
1013 DbHandle *currHdl = dbHandlesToAuthenticate;
1014 short index;
1015 Boolean authenticated = false;
1016 for (index=0; index < dbHandleCount && !authenticated; index++)
1017 {
1018 try
1019 {
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.
1024 }
1025 catch (const CommonError &err)
1026 {
1027 currHdl++; // we failed to authenticate with this one, onto the next one.
1028 }
1029 }
1030 if ( !authenticated )
1031 return SecurityAgent::invalidPassphrase;
1032
1033 return SecurityAgent::noReason;
1034 }
1035
1036 // @@@ no pluggable authentication possible!
1037 Reason
1038 QueryKeychainAuth::operator () (const char *database, const char *description, AclAuthorization action, const char *prompt)
1039 {
1040 Reason reason = SecurityAgent::noReason;
1041 AuthItemSet hints, context;
1042 int retryCount = 0;
1043 string username;
1044 string password;
1045
1046 using CommonCriteria::Securityd::KeychainAuthLogger;
1047 KeychainAuthLogger logger(mAuditToken, (short)AUE_ssauthint, database, description);
1048
1049 hints.insert(mClientHints.begin(), mClientHints.end());
1050
1051 // put action/operation (sint32) into hints
1052 hints.insert(AuthItemRef(AGENT_HINT_ACL_TAG, AuthValueOverlay(sizeof(action), static_cast<sint32*>(&action))));
1053
1054 hints.insert(AuthItemRef(AGENT_HINT_CUSTOM_PROMPT, AuthValueOverlay(prompt ? (uint32_t)strlen(prompt) : 0, const_cast<char*>(prompt))));
1055
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))));
1058
1059 // keychain name into hints
1060 hints.insert(AuthItemRef(AGENT_HINT_KEYCHAIN_PATH, AuthValueOverlay(database ? (uint32_t)strlen(database) : 0, const_cast<char*>(database))));
1061
1062 create("builtin", "confirm-access-user-password");
1063
1064 AuthItem *usernameItem;
1065 AuthItem *passwordItem;
1066
1067 do {
1068
1069 AuthItemRef triesHint(AGENT_HINT_TRIES, AuthValueOverlay(sizeof(retryCount), &retryCount));
1070 hints.erase(triesHint); hints.insert(triesHint); // replace
1071
1072 if (++retryCount > maxTries)
1073 reason = SecurityAgent::tooManyTries;
1074
1075 if (SecurityAgent::noReason != reason)
1076 {
1077 if (SecurityAgent::tooManyTries == reason)
1078 logger.logFailure(NULL, CommonCriteria::errTooManyTries);
1079 else
1080 logger.logFailure();
1081 }
1082
1083 AuthItemRef retryHint(AGENT_HINT_RETRY_REASON, AuthValueOverlay(sizeof(reason), &reason));
1084 hints.erase(retryHint); hints.insert(retryHint); // replace
1085
1086 setInput(hints, context);
1087 try
1088 {
1089 invoke();
1090 checkResult();
1091 }
1092 catch (...) // user probably clicked "deny"
1093 {
1094 logger.logFailure();
1095 throw;
1096 }
1097 usernameItem = mOutContext.find(AGENT_USERNAME);
1098 passwordItem = mOutContext.find(AGENT_PASSWORD);
1099 if (!usernameItem || !passwordItem)
1100 continue;
1101 usernameItem->getString(username);
1102 passwordItem->getString(password);
1103 } while ((reason = accept(username, password)));
1104
1105 if (SecurityAgent::noReason == reason)
1106 logger.logSuccess();
1107 // else we logged the denial in the loop
1108
1109 return reason;
1110 }
1111
1112 Reason
1113 QueryKeychainAuth::accept(string &username, string &passphrase)
1114 {
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.
1119
1120 const char *user = username.c_str();
1121 const char *passwd = passphrase.c_str();
1122 int checkpw_status = checkpw(user, passwd);
1123
1124 if (checkpw_status != CHECKPW_SUCCESS) {
1125 return SecurityAgent::invalidPassphrase;
1126 }
1127
1128 const char *group = "admin";
1129 if (group) {
1130 int rc, ismember;
1131 uuid_t group_uuid, user_uuid;
1132 rc = mbr_group_name_to_uuid(group, group_uuid);
1133 if (rc) { return SecurityAgent::userNotInGroup; }
1134
1135 rc = mbr_user_name_to_uuid(user, user_uuid);
1136 if (rc) { return SecurityAgent::userNotInGroup; }
1137
1138 rc = mbr_check_membership(user_uuid, group_uuid, &ismember);
1139 if (rc || !ismember) { return SecurityAgent::userNotInGroup; }
1140 }
1141
1142 return SecurityAgent::noReason;
1143 }
1144