]> git.saurik.com Git - apple/securityd.git/blob - src/agentquery.cpp
securityd-55009.tar.gz
[apple/securityd.git] / src / agentquery.cpp
1 /*
2 * Copyright (c) 2000-2004,2008-2009 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 #include "agentquery.h"
28 #include "authority.h"
29 #include "ccaudit_extensions.h"
30
31 #include <Security/AuthorizationTags.h>
32 #include <Security/AuthorizationTagsPriv.h>
33 #include <Security/checkpw.h>
34 #include <System/sys/fileport.h>
35 #include <bsm/audit.h>
36 #include <bsm/audit_uevents.h> // AUE_ssauthint
37 #include <security_utilities/logging.h>
38 #include <security_utilities/mach++.h>
39 #include <stdlib.h>
40
41 //
42 // NOSA support functions. This is a test mode where the SecurityAgent
43 // is simulated via stdio in the client. Good for running automated tests
44 // of client programs. Only available if -DNOSA when compiling.
45 //
46 #if defined(NOSA)
47
48 #include <cstdarg>
49
50 static void getNoSA(char *buffer, size_t bufferSize, const char *fmt, ...)
51 {
52 // write prompt
53 va_list args;
54 va_start(args, fmt);
55 vfprintf(stdout, fmt, args);
56 va_end(args);
57
58 // read reply
59 memset(buffer, 0, bufferSize);
60 const char *nosa = getenv("NOSA");
61 if (!strcmp(nosa, "-")) {
62 if (fgets(buffer, bufferSize-1, stdin) == NULL)
63 CssmError::throwMe(CSSM_ERRCODE_NO_USER_INTERACTION);
64 buffer[strlen(buffer)-1] = '\0'; // remove trailing newline
65 if (!isatty(fileno(stdin)))
66 printf("%s\n", buffer); // echo to output if input not terminal
67 } else {
68 strncpy(buffer, nosa, bufferSize-1);
69 printf("%s\n", buffer);
70 }
71 if (buffer[0] == '\0') // empty input -> cancellation
72 CssmError::throwMe(CSSM_ERRCODE_USER_CANCELED);
73 }
74
75 #endif //NOSA
76
77
78 // SecurityAgentConnection
79
80 SecurityAgentConnection::SecurityAgentConnection(const AuthHostType type, Session &session)
81 : mAuthHostType(type),
82 mHostInstance(session.authhost(mAuthHostType)),
83 mConnection(&Server::connection()),
84 mAuditToken(Server::connection().auditToken())
85 {
86 // this may take a while
87 Server::active().longTermActivity();
88 secdebug("SecurityAgentConnection", "new SecurityAgentConnection(%p)", this);
89 }
90
91 SecurityAgentConnection::~SecurityAgentConnection()
92 {
93 secdebug("SecurityAgentConnection", "SecurityAgentConnection(%p) dying", this);
94 mConnection->useAgent(NULL);
95 }
96
97 void
98 SecurityAgentConnection::activate()
99 {
100 secdebug("SecurityAgentConnection", "activate(%p)", this);
101
102 Session &session = mHostInstance->session();
103 SessionId targetSessionId = session.sessionId();
104 MachPlusPlus::Bootstrap processBootstrap = Server::process().taskPort().bootstrap();
105 fileport_t userPrefsFP = MACH_PORT_NULL;
106
107 // send the the userPrefs to SecurityAgent
108 if (mAuthHostType == securityAgent || mAuthHostType == userAuthHost) {
109 CFRef<CFDataRef> userPrefs(mHostInstance->session().copyUserPrefs());
110 if (NULL != userPrefs)
111 {
112 FILE *mbox = NULL;
113 int fd = 0;
114 mbox = tmpfile();
115 if (NULL != mbox)
116 {
117 fd = dup(fileno(mbox));
118 fclose(mbox);
119 if (fd != -1)
120 {
121 CFIndex length = CFDataGetLength(userPrefs);
122 if (write(fd, CFDataGetBytePtr(userPrefs), length) != length)
123 Syslog::error("could not write userPrefs");
124 else
125 {
126 if (0 == fileport_makeport(fd, &userPrefsFP))
127 secdebug("SecurityAgentConnection", "stashed the userPrefs file descriptor");
128 else
129 Syslog::error("failed to stash the userPrefs file descriptor");
130 }
131 close(fd);
132 }
133 }
134 }
135 if (MACH_PORT_NULL == userPrefsFP)
136 {
137 secdebug("SecurityAgentConnection", "could not read userPrefs");
138 }
139 }
140
141 mConnection->useAgent(this);
142 try
143 {
144 StLock<Mutex> _(*mHostInstance);
145
146 mach_port_t lookupPort = mHostInstance->lookup(targetSessionId);
147 if (MACH_PORT_NULL == lookupPort)
148 {
149 Syslog::error("could not find real service, bailing");
150 MacOSError::throwMe(CSSM_ERRCODE_SERVICE_NOT_AVAILABLE);
151 }
152 // reset Client contact info
153 mPort = lookupPort;
154 SecurityAgent::Client::activate(mPort);
155
156 secdebug("SecurityAgentConnection", "%p activated", this);
157 }
158 catch (MacOSError &err)
159 {
160 mConnection->useAgent(NULL); // guess not
161 Syslog::error("SecurityAgentConnection: error activating %s instance %p",
162 mAuthHostType == privilegedAuthHost
163 ? "authorizationhost"
164 : "SecurityAgent", this);
165 throw;
166 }
167
168 secdebug("SecurityAgentConnection", "contacting service (%p)", this);
169 mach_port_name_t jobPort;
170 if (0 > audit_session_port(session.sessionId(), &jobPort))
171 Syslog::error("audit_session_port failed: %m");
172 MacOSError::check(SecurityAgent::Client::contact(jobPort, processBootstrap, userPrefsFP));
173 secdebug("SecurityAgentConnection", "contact didn't throw (%p)", this);
174
175 if (userPrefsFP != MACH_PORT_NULL)
176 mach_port_deallocate(mach_task_self(), userPrefsFP);
177 }
178
179 void
180 SecurityAgentConnection::reconnect()
181 {
182 // if !mHostInstance throw()?
183 if (mHostInstance)
184 {
185 activate();
186 }
187 }
188
189 void
190 SecurityAgentConnection::terminate()
191 {
192 activate();
193
194 // @@@ This happens already in the destructor; presumably we do this to tear things down orderly
195 mConnection->useAgent(NULL);
196 }
197
198
199 // SecurityAgentTransaction
200
201 SecurityAgentTransaction::SecurityAgentTransaction(const AuthHostType type, Session &session, bool startNow)
202 : SecurityAgentConnection(type, session),
203 mStarted(false)
204 {
205 secdebug("SecurityAgentTransaction", "New SecurityAgentTransaction(%p)", this);
206 activate(); // start agent now, or other SAConnections will kill and spawn new agents
207 if (startNow)
208 start();
209 }
210
211 SecurityAgentTransaction::~SecurityAgentTransaction()
212 {
213 try { end(); } catch(...) {}
214 secdebug("SecurityAgentTransaction", "Destroying %p", this);
215 }
216
217 void
218 SecurityAgentTransaction::start()
219 {
220 secdebug("SecurityAgentTransaction", "start(%p)", this);
221 MacOSError::check(SecurityAgentQuery::Client::startTransaction(mPort));
222 mStarted = true;
223 secdebug("SecurityAgentTransaction", "started(%p)", this);
224 }
225
226 void
227 SecurityAgentTransaction::end()
228 {
229 if (started())
230 {
231 MacOSError::check(SecurityAgentQuery::Client::endTransaction(mPort));
232 mStarted = false;
233 }
234 secdebug("SecurityAgentTransaction", "End SecurityAgentTransaction(%p)", this);
235 }
236
237 using SecurityAgent::Reason;
238 using namespace Authorization;
239
240 SecurityAgentQuery::SecurityAgentQuery(const AuthHostType type, Session &session)
241 : SecurityAgentConnection(type, session)
242 {
243 secdebug("SecurityAgentQuery", "new SecurityAgentQuery(%p)", this);
244 }
245
246 SecurityAgentQuery::~SecurityAgentQuery()
247 {
248 secdebug("SecurityAgentQuery", "SecurityAgentQuery(%p) dying", this);
249
250 #if defined(NOSA)
251 if (getenv("NOSA")) {
252 printf(" [query done]\n");
253 return;
254 }
255 #endif
256
257 if (SecurityAgent::Client::state() != SecurityAgent::Client::dead)
258 destroy();
259 }
260
261 void
262 SecurityAgentQuery::inferHints(Process &thisProcess)
263 {
264 string guestPath;
265 if (SecCodeRef clientCode = thisProcess.currentGuest())
266 guestPath = codePath(clientCode);
267 AuthItemSet processHints = clientHints(SecurityAgent::bundle, guestPath,
268 thisProcess.pid(), thisProcess.uid());
269 mClientHints.insert(processHints.begin(), processHints.end());
270 }
271
272 void SecurityAgentQuery::addHint(const char *name, const void *value, UInt32 valueLen, UInt32 flags)
273 {
274 AuthorizationItem item = { name, valueLen, const_cast<void *>(value), flags };
275 mClientHints.insert(AuthItemRef(item));
276 }
277
278
279 void
280 SecurityAgentQuery::readChoice()
281 {
282 allow = false;
283 remember = false;
284
285 AuthItem *allowAction = outContext().find(AGENT_CONTEXT_ALLOW);
286 if (allowAction)
287 {
288 string allowString;
289 if (allowAction->getString(allowString)
290 && (allowString == "YES"))
291 allow = true;
292 }
293
294 AuthItem *rememberAction = outContext().find(AGENT_CONTEXT_REMEMBER_ACTION);
295 if (rememberAction)
296 {
297 string rememberString;
298 if (rememberAction->getString(rememberString)
299 && (rememberString == "YES"))
300 remember = true;
301 }
302 }
303
304 void
305 SecurityAgentQuery::disconnect()
306 {
307 SecurityAgent::Client::destroy();
308 }
309
310 void
311 SecurityAgentQuery::terminate()
312 {
313 // you might think these are called in the wrong order, but you'd be wrong
314 SecurityAgentConnection::terminate();
315 SecurityAgent::Client::terminate();
316 }
317
318 void
319 SecurityAgentQuery::create(const char *pluginId, const char *mechanismId, const SessionId inSessionId)
320 {
321 activate();
322 OSStatus status = SecurityAgent::Client::create(pluginId, mechanismId, inSessionId);
323 if (status)
324 {
325 secdebug("SecurityAgentQuery", "agent went walkabout, restarting");
326 reconnect();
327 status = SecurityAgent::Client::create(pluginId, mechanismId, inSessionId);
328 }
329 if (status) MacOSError::throwMe(status);
330 }
331
332 //
333 // Perform the "rogue app" access query dialog
334 //
335 QueryKeychainUse::QueryKeychainUse(bool needPass, const Database *db)
336 : mPassphraseCheck(NULL)
337 {
338 // if passphrase checking requested, save KeychainDatabase reference
339 // (will quietly disable check if db isn't a keychain)
340 if (needPass)
341 mPassphraseCheck = dynamic_cast<const KeychainDatabase *>(db);
342 }
343
344 Reason QueryKeychainUse::queryUser (const char *database, const char *description, AclAuthorization action)
345 {
346 Reason reason = SecurityAgent::noReason;
347 int retryCount = 0;
348 OSStatus status;
349 AuthValueVector arguments;
350 AuthItemSet hints, context;
351
352 #if defined(NOSA)
353 if (getenv("NOSA")) {
354 char answer[maxPassphraseLength+10];
355
356 string applicationPath;
357 AuthItem *applicationPathItem = mClientHints.find(AGENT_HINT_APPLICATION_PATH);
358 if (applicationPathItem)
359 applicationPathItem->getString(applicationPath);
360
361 getNoSA(answer, sizeof(answer), "Allow %s to do %d on %s in %s? [yn][g]%s ",
362 applicationPath.c_str(), int(action), (description ? description : "[NULL item]"),
363 (database ? database : "[NULL database]"),
364 mPassphraseCheck ? ":passphrase" : "");
365 // turn passphrase (no ':') into y:passphrase
366 if (mPassphraseCheck && !strchr(answer, ':')) {
367 memmove(answer+2, answer, strlen(answer)+1);
368 memcpy(answer, "y:", 2);
369 }
370
371 allow = answer[0] == 'y';
372 remember = answer[1] == 'g';
373 return SecurityAgent::noReason;
374 }
375 #endif
376
377 // prepopulate with client hints
378 hints.insert(mClientHints.begin(), mClientHints.end());
379
380 // put action/operation (sint32) into hints
381 hints.insert(AuthItemRef(AGENT_HINT_ACL_TAG, AuthValueOverlay(sizeof(action), static_cast<sint32*>(&action))));
382
383 // item name into hints
384
385 hints.insert(AuthItemRef(AGENT_HINT_KEYCHAIN_ITEM_NAME, AuthValueOverlay(description ? strlen(description) : 0, const_cast<char*>(description))));
386
387 // keychain name into hints
388 hints.insert(AuthItemRef(AGENT_HINT_KEYCHAIN_PATH, AuthValueOverlay(database ? strlen(database) : 0, const_cast<char*>(database))));
389
390
391 if (mPassphraseCheck)
392 {
393 create("builtin", "confirm-access-password", noSecuritySession);
394
395 CssmAutoData data(Allocator::standard(Allocator::sensitive));
396
397 do
398 {
399
400 AuthItemRef triesHint(AGENT_HINT_TRIES, AuthValueOverlay(sizeof(retryCount), &retryCount));
401 hints.erase(triesHint); hints.insert(triesHint); // replace
402
403 if (retryCount++ > kMaximumAuthorizationTries)
404 {
405 reason = SecurityAgent::tooManyTries;
406 }
407
408 AuthItemRef retryHint(AGENT_HINT_RETRY_REASON, AuthValueOverlay(sizeof(reason), &reason));
409 hints.erase(retryHint); hints.insert(retryHint); // replace
410
411 setInput(hints, context);
412 status = invoke();
413
414 if (retryCount > kMaximumAuthorizationTries)
415 {
416 return reason;
417 }
418
419 checkResult();
420
421 AuthItem *passwordItem = outContext().find(kAuthorizationEnvironmentPassword);
422 if (!passwordItem)
423 continue;
424
425 passwordItem->getCssmData(data);
426 }
427 while (reason = (const_cast<KeychainDatabase*>(mPassphraseCheck)->decode(data) ? SecurityAgent::noReason : SecurityAgent::invalidPassphrase));
428 }
429 else
430 {
431 create("builtin", "confirm-access", noSecuritySession);
432 setInput(hints, context);
433 invoke();
434 }
435
436 readChoice();
437
438 return reason;
439 }
440
441 //
442 // Perform code signature ACL access adjustment dialogs
443 //
444 bool QueryCodeCheck::operator () (const char *aclPath)
445 {
446 OSStatus status;
447 AuthValueVector arguments;
448 AuthItemSet hints, context;
449
450 #if defined(NOSA)
451 if (getenv("NOSA")) {
452 char answer[10];
453
454 string applicationPath;
455 AuthItem *applicationPathItem = mClientHints.find(AGENT_HINT_APPLICATION_PATH);
456 if (applicationPathItem)
457 applicationPathItem->getString(applicationPath);
458
459 getNoSA(answer, sizeof(answer),
460 "Allow %s to match an ACL for %s [yn][g]? ",
461 applicationPath.c_str(), aclPath ? aclPath : "(unknown)");
462 allow = answer[0] == 'y';
463 remember = answer[1] == 'g';
464 return;
465 }
466 #endif
467
468 // prepopulate with client hints
469 hints.insert(mClientHints.begin(), mClientHints.end());
470
471 hints.insert(AuthItemRef(AGENT_HINT_APPLICATION_PATH, AuthValueOverlay(strlen(aclPath), const_cast<char*>(aclPath))));
472
473 create("builtin", "code-identity", noSecuritySession);
474
475 setInput(hints, context);
476 status = invoke();
477
478 checkResult();
479
480 // MacOSError::check(status);
481
482 return kAuthorizationResultAllow == result();
483 }
484
485
486 //
487 // Obtain passphrases and submit them to the accept() method until it is accepted
488 // or we can't get another passphrase. Accept() should consume the passphrase
489 // if it is accepted. If no passphrase is acceptable, throw out of here.
490 //
491 Reason QueryOld::query()
492 {
493 Reason reason = SecurityAgent::noReason;
494 OSStatus status;
495 AuthValueVector arguments;
496 AuthItemSet hints, context;
497 CssmAutoData passphrase(Allocator::standard(Allocator::sensitive));
498 int retryCount = 0;
499
500 #if defined(NOSA)
501 // return the passphrase
502 if (getenv("NOSA")) {
503 char passphrase_[maxPassphraseLength];
504 getNoSA(passphrase, maxPassphraseLength, "Unlock %s [<CR> to cancel]: ", database.dbName());
505 passphrase.copy(passphrase_, strlen(passphrase_));
506 return database.decode(passphrase) ? SecurityAgent::noReason : SecurityAgent::invalidPassphrase;
507 }
508 #endif
509
510 // prepopulate with client hints
511
512 const char *keychainPath = database.dbName();
513 hints.insert(AuthItemRef(AGENT_HINT_KEYCHAIN_PATH, AuthValueOverlay(strlen(keychainPath), const_cast<char*>(keychainPath))));
514
515 hints.insert(mClientHints.begin(), mClientHints.end());
516
517 create("builtin", "unlock-keychain", noSecuritySession);
518
519 do
520 {
521 AuthItemRef triesHint(AGENT_HINT_TRIES, AuthValueOverlay(sizeof(retryCount), &retryCount));
522 hints.erase(triesHint); hints.insert(triesHint); // replace
523
524 ++retryCount;
525
526 if (retryCount > maxTries)
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 status = invoke();
536
537 if (retryCount > maxTries)
538 {
539 return reason;
540 }
541
542 checkResult();
543
544 AuthItem *passwordItem = outContext().find(kAuthorizationEnvironmentPassword);
545 if (!passwordItem)
546 continue;
547
548 passwordItem->getCssmData(passphrase);
549
550 }
551 while (reason = accept(passphrase));
552
553 return SecurityAgent::noReason;
554 }
555
556
557 //
558 // Get existing passphrase (unlock) Query
559 //
560 Reason QueryOld::operator () ()
561 {
562 return query();
563 }
564
565
566 //
567 // End-classes for old secrets
568 //
569 Reason QueryUnlock::accept(CssmManagedData &passphrase)
570 {
571 if (safer_cast<KeychainDatabase &>(database).decode(passphrase))
572 return SecurityAgent::noReason;
573 else
574 return SecurityAgent::invalidPassphrase;
575 }
576
577
578 QueryPIN::QueryPIN(Database &db)
579 : QueryOld(db), mPin(Allocator::standard())
580 {
581 this->inferHints(Server::process());
582 }
583
584
585 Reason QueryPIN::accept(CssmManagedData &pin)
586 {
587 // no retries for now
588 mPin = pin;
589 return SecurityAgent::noReason;
590 }
591
592
593 //
594 // Obtain passphrases and submit them to the accept() method until it is accepted
595 // or we can't get another passphrase. Accept() should consume the passphrase
596 // if it is accepted. If no passphrase is acceptable, throw out of here.
597 //
598 Reason QueryNewPassphrase::query()
599 {
600 Reason reason = initialReason;
601 CssmAutoData passphrase(Allocator::standard(Allocator::sensitive));
602 CssmAutoData oldPassphrase(Allocator::standard(Allocator::sensitive));
603
604 OSStatus status;
605 AuthValueVector arguments;
606 AuthItemSet hints, context;
607
608 int retryCount = 0;
609
610 #if defined(NOSA)
611 if (getenv("NOSA")) {
612 char passphrase_[maxPassphraseLength];
613 getNoSA(passphrase_, maxPassphraseLength,
614 "New passphrase for %s (reason %d) [<CR> to cancel]: ",
615 database.dbName(), reason);
616 return SecurityAgent::noReason;
617 }
618 #endif
619
620 // prepopulate with client hints
621 hints.insert(mClientHints.begin(), mClientHints.end());
622
623 // keychain name into hints
624 hints.insert(AuthItemRef(AGENT_HINT_KEYCHAIN_PATH, AuthValueOverlay(database.dbName())));
625
626 switch (initialReason)
627 {
628 case SecurityAgent::newDatabase:
629 create("builtin", "new-passphrase", noSecuritySession);
630 break;
631 case SecurityAgent::changePassphrase:
632 create("builtin", "change-passphrase", noSecuritySession);
633 break;
634 default:
635 assert(false);
636 }
637
638 do
639 {
640 AuthItemRef triesHint(AGENT_HINT_TRIES, AuthValueOverlay(sizeof(retryCount), &retryCount));
641 hints.erase(triesHint); hints.insert(triesHint); // replace
642
643 if (++retryCount > maxTries)
644 {
645 reason = SecurityAgent::tooManyTries;
646 }
647
648 AuthItemRef retryHint(AGENT_HINT_RETRY_REASON, AuthValueOverlay(sizeof(reason), &reason));
649 hints.erase(retryHint); hints.insert(retryHint); // replace
650
651 setInput(hints, context);
652 status = invoke();
653
654 if (retryCount > maxTries)
655 {
656 return reason;
657 }
658
659 checkResult();
660
661 if (SecurityAgent::changePassphrase == initialReason)
662 {
663 AuthItem *oldPasswordItem = outContext().find(AGENT_PASSWORD);
664 if (!oldPasswordItem)
665 continue;
666
667 oldPasswordItem->getCssmData(oldPassphrase);
668 }
669
670 AuthItem *passwordItem = outContext().find(AGENT_CONTEXT_NEW_PASSWORD);
671 if (!passwordItem)
672 continue;
673
674 passwordItem->getCssmData(passphrase);
675
676 }
677 while (reason = accept(passphrase, (initialReason == SecurityAgent::changePassphrase) ? &oldPassphrase.get() : NULL));
678
679 return SecurityAgent::noReason;
680 }
681
682
683 //
684 // Get new passphrase Query
685 //
686 Reason QueryNewPassphrase::operator () (CssmOwnedData &passphrase)
687 {
688 if (Reason result = query())
689 return result; // failed
690 passphrase = mPassphrase;
691 return SecurityAgent::noReason; // success
692 }
693
694 Reason QueryNewPassphrase::accept(CssmManagedData &passphrase, CssmData *oldPassphrase)
695 {
696 //@@@ acceptance criteria are currently hardwired here
697 //@@@ This validation presumes ASCII - UTF8 might be more lenient
698
699 // if we have an old passphrase, check it
700 if (oldPassphrase && !safer_cast<KeychainDatabase&>(database).validatePassphrase(*oldPassphrase))
701 return SecurityAgent::oldPassphraseWrong;
702
703 // sanity check the new passphrase (but allow user override)
704 if (!(mPassphraseValid && passphrase.get() == mPassphrase)) {
705 mPassphrase = passphrase;
706 mPassphraseValid = true;
707 if (mPassphrase.length() == 0)
708 return SecurityAgent::passphraseIsNull;
709 if (mPassphrase.length() < 6)
710 return SecurityAgent::passphraseTooSimple;
711 }
712
713 // accept this
714 return SecurityAgent::noReason;
715 }
716
717 //
718 // Get a passphrase for unspecified use
719 //
720 Reason QueryGenericPassphrase::operator () (const char *prompt, bool verify,
721 string &passphrase)
722 {
723 return query(prompt, verify, passphrase);
724 }
725
726 Reason QueryGenericPassphrase::query(const char *prompt, bool verify,
727 string &passphrase)
728 {
729 Reason reason = SecurityAgent::noReason;
730 OSStatus status; // not really used; remove?
731 AuthValueVector arguments;
732 AuthItemSet hints, context;
733
734 #if defined(NOSA)
735 if (getenv("NOSA")) {
736 // FIXME 3690984
737 return SecurityAgent::noReason;
738 }
739 #endif
740
741 hints.insert(mClientHints.begin(), mClientHints.end());
742 hints.insert(AuthItemRef(AGENT_HINT_CUSTOM_PROMPT, AuthValueOverlay(prompt ? strlen(prompt) : 0, const_cast<char*>(prompt))));
743 // XXX/gh defined by dmitch but no analogous hint in
744 // AuthorizationTagsPriv.h:
745 // CSSM_ATTRIBUTE_ALERT_TITLE (optional alert panel title)
746
747 if (false == verify) { // import
748 create("builtin", "generic-unlock", noSecuritySession);
749 } else { // verify passphrase (export)
750 // new-passphrase-generic works with the pre-4 June 2004 agent;
751 // generic-new-passphrase is required for the new agent
752 create("builtin", "generic-new-passphrase", noSecuritySession);
753 }
754
755 AuthItem *passwordItem;
756
757 do {
758 setInput(hints, context);
759 status = invoke();
760 checkResult();
761 passwordItem = outContext().find(AGENT_PASSWORD);
762
763 } while (!passwordItem);
764
765 passwordItem->getString(passphrase);
766
767 return reason;
768 }
769
770
771 //
772 // Get a DB blob's passphrase--keychain synchronization
773 //
774 Reason QueryDBBlobSecret::operator () (DbHandle *dbHandleArray, uint8 dbHandleArrayCount, DbHandle *dbHandleAuthenticated)
775 {
776 return query(dbHandleArray, dbHandleArrayCount, dbHandleAuthenticated);
777 }
778
779 Reason QueryDBBlobSecret::query(DbHandle *dbHandleArray, uint8 dbHandleArrayCount, DbHandle *dbHandleAuthenticated)
780 {
781 Reason reason = SecurityAgent::noReason;
782 CssmAutoData passphrase(Allocator::standard(Allocator::sensitive));
783 OSStatus status; // not really used; remove?
784 AuthValueVector arguments;
785 AuthItemSet hints/*NUKEME*/, context;
786
787 #if defined(NOSA)
788 if (getenv("NOSA")) {
789 // FIXME akin to 3690984
790 return SecurityAgent::noReason;
791 }
792 #endif
793
794 hints.insert(mClientHints.begin(), mClientHints.end());
795
796 create("builtin", "generic-unlock-kcblob", noSecuritySession);
797
798 AuthItem *secretItem;
799
800 int retryCount = 0;
801
802 do {
803 AuthItemRef triesHint(AGENT_HINT_TRIES, AuthValueOverlay(sizeof(retryCount), &retryCount));
804 hints.erase(triesHint); hints.insert(triesHint); // replace
805
806 if (++retryCount > maxTries)
807 {
808 reason = SecurityAgent::tooManyTries;
809 }
810
811 AuthItemRef retryHint(AGENT_HINT_RETRY_REASON, AuthValueOverlay(sizeof(reason), &reason));
812 hints.erase(retryHint); hints.insert(retryHint); // replace
813
814 setInput(hints, context);
815 status = invoke();
816 checkResult();
817 secretItem = outContext().find(AGENT_PASSWORD);
818 if (!secretItem)
819 continue;
820 secretItem->getCssmData(passphrase);
821
822 } while (reason = accept(passphrase, dbHandleArray, dbHandleArrayCount, dbHandleAuthenticated));
823
824 return reason;
825 }
826
827 Reason QueryDBBlobSecret::accept(CssmManagedData &passphrase,
828 DbHandle *dbHandlesToAuthenticate, uint8 dbHandleCount, DbHandle *dbHandleAuthenticated)
829 {
830 DbHandle *currHdl = dbHandlesToAuthenticate;
831 short index;
832 Boolean authenticated = false;
833 for (index=0; index < dbHandleCount && !authenticated; index++)
834 {
835 try
836 {
837 RefPointer<KeychainDatabase> dbToUnlock = Server::keychain(*currHdl);
838 dbToUnlock->unlockDb(passphrase);
839 authenticated = true;
840 *dbHandleAuthenticated = *currHdl; // return the DbHandle that 'passphrase' authenticated with.
841 }
842 catch (const CommonError &err)
843 {
844 currHdl++; // we failed to authenticate with this one, onto the next one.
845 }
846 }
847 if ( !authenticated )
848 return SecurityAgent::invalidPassphrase;
849
850 return SecurityAgent::noReason;
851 }
852
853 QueryInvokeMechanism::QueryInvokeMechanism(const AuthHostType type, Session &session) :
854 SecurityAgentQuery(type, session) { }
855
856 void QueryInvokeMechanism::initialize(const string &inPluginId, const string &inMechanismId, const AuthValueVector &inArguments, const SessionId inSessionId)
857 {
858 if (SecurityAgent::Client::init == SecurityAgent::Client::state())
859 {
860 create(inPluginId.c_str(), inMechanismId.c_str(), inSessionId);
861 mArguments = inArguments;
862 }
863 }
864
865 // XXX/cs should return AuthorizationResult
866 void QueryInvokeMechanism::run(const AuthValueVector &inArguments, AuthItemSet &inHints, AuthItemSet &inContext, AuthorizationResult *outResult)
867 {
868 // prepopulate with client hints
869 inHints.insert(mClientHints.begin(), mClientHints.end());
870
871 setArguments(inArguments);
872 setInput(inHints, inContext);
873 MacOSError::check(invoke());
874
875 if (outResult) *outResult = result();
876
877 inHints = outHints();
878 inContext = outContext();
879 }
880
881 void QueryInvokeMechanism::terminateAgent()
882 {
883 terminate();
884 }
885
886 // @@@ no pluggable authentication possible!
887 Reason
888 QueryKeychainAuth::operator () (const char *database, const char *description, AclAuthorization action, const char *prompt)
889 {
890 Reason reason = SecurityAgent::noReason;
891 AuthItemSet hints, context;
892 AuthValueVector arguments;
893 int retryCount = 0;
894 string username;
895 string password;
896
897 using CommonCriteria::Securityd::KeychainAuthLogger;
898 KeychainAuthLogger logger(mAuditToken, AUE_ssauthint, database, description);
899
900 #if defined(NOSA)
901 /* XXX/gh probably not complete; stolen verbatim from rogue-app query */
902 if (getenv("NOSA")) {
903 char answer[maxPassphraseLength+10];
904
905 string applicationPath;
906 AuthItem *applicationPathItem = mClientHints.find(AGENT_HINT_APPLICATION_PATH);
907 if (applicationPathItem)
908 applicationPathItem->getString(applicationPath);
909
910 getNoSA(answer, sizeof(answer), "Allow %s to do %d on %s in %s? [yn][g]%s ",
911 applicationPath.c_str(), int(action), (description ? description : "[NULL item]"),
912 (database ? database : "[NULL database]"),
913 mPassphraseCheck ? ":passphrase" : "");
914 // turn passphrase (no ':') into y:passphrase
915 if (mPassphraseCheck && !strchr(answer, ':')) {
916 memmove(answer+2, answer, strlen(answer)+1);
917 memcpy(answer, "y:", 2);
918 }
919
920 allow = answer[0] == 'y';
921 remember = answer[1] == 'g';
922 return SecurityAgent::noReason;
923 }
924 #endif
925
926 hints.insert(mClientHints.begin(), mClientHints.end());
927
928 // put action/operation (sint32) into hints
929 hints.insert(AuthItemRef(AGENT_HINT_ACL_TAG, AuthValueOverlay(sizeof(action), static_cast<sint32*>(&action))));
930
931 hints.insert(AuthItemRef(AGENT_HINT_CUSTOM_PROMPT, AuthValueOverlay(prompt ? strlen(prompt) : 0, const_cast<char*>(prompt))));
932
933 // item name into hints
934 hints.insert(AuthItemRef(AGENT_HINT_KEYCHAIN_ITEM_NAME, AuthValueOverlay(description ? strlen(description) : 0, const_cast<char*>(description))));
935
936 // keychain name into hints
937 hints.insert(AuthItemRef(AGENT_HINT_KEYCHAIN_PATH, AuthValueOverlay(database ? strlen(database) : 0, const_cast<char*>(database))));
938
939 create("builtin", "confirm-access-user-password", noSecuritySession);
940
941 AuthItem *usernameItem;
942 AuthItem *passwordItem;
943
944 do {
945
946 AuthItemRef triesHint(AGENT_HINT_TRIES, AuthValueOverlay(sizeof(retryCount), &retryCount));
947 hints.erase(triesHint); hints.insert(triesHint); // replace
948
949 if (++retryCount > maxTries)
950 reason = SecurityAgent::tooManyTries;
951
952 if (SecurityAgent::noReason != reason)
953 {
954 if (SecurityAgent::tooManyTries == reason)
955 logger.logFailure(NULL, CommonCriteria::errTooManyTries);
956 else
957 logger.logFailure();
958 }
959
960 AuthItemRef retryHint(AGENT_HINT_RETRY_REASON, AuthValueOverlay(sizeof(reason), &reason));
961 hints.erase(retryHint); hints.insert(retryHint); // replace
962
963 setInput(hints, context);
964 try
965 {
966 invoke();
967 checkResult();
968 }
969 catch (...) // user probably clicked "deny"
970 {
971 logger.logFailure();
972 throw;
973 }
974 usernameItem = outContext().find(AGENT_USERNAME);
975 passwordItem = outContext().find(AGENT_PASSWORD);
976 if (!usernameItem || !passwordItem)
977 continue;
978 usernameItem->getString(username);
979 passwordItem->getString(password);
980 } while (reason = accept(username, password));
981
982 if (SecurityAgent::noReason == reason)
983 logger.logSuccess();
984 // else we logged the denial in the loop
985
986 return reason;
987 }
988
989 Reason
990 QueryKeychainAuth::accept(string &username, string &passphrase)
991 {
992 const char *user = username.c_str();
993 const char *passwd = passphrase.c_str();
994 int checkpw_status = checkpw(user, passwd);
995
996 if (checkpw_status != CHECKPW_SUCCESS)
997 return SecurityAgent::invalidPassphrase;
998
999 return SecurityAgent::noReason;
1000 }
1001